<template>
  <BasicModal :maskClosable="false" :width="1200" @register="registerModal" v-bind="$attrs" :title="getTitle"
    @ok="handleSubmit">
    <div class="form-box">
      <BasicForm @register="registerForm" />
      <a-button :disabled="isUpdate" class="form-btn" type="primary" @click="generate">生成</a-button>
    </div>
    <div class="rich-text-box">
      月报审阅
      <div>
        <img src="/src/assets/images/sw-home/word-icon.png" />
        <span @click="exportWord"> 导出为word </span>
        <!-- <img src="/src/assets/images/sw-home/pdf-icon.png" />
        <span> 导出为pdf </span> -->
      </div>
    </div>
    <div class="rich">
      <Tinymce v-model="TinymceData" :options="tinymceOptions" @change="handleChange" :height="500" width="100%" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, onMounted } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { useMessage } from '/@/hooks/web/useMessage';
import { getNewJianbao, getJianbaoTemplate, getJianbaoGenerate, getModifyJianbao } from '/@/api/swHome/index';
import { useUserStore } from '/@/store/modules/user';
import { Tinymce } from '/@/components/Tinymce/index';
import moment from 'moment';
import FileSaver from 'file-saver';
import htmlDocx from 'html-docx-js/dist/html-docx';
const userStore = useUserStore();
export default defineComponent({
  name: 'AccountModal',
  components: { BasicModal, BasicForm, Tinymce },
  setup(_, { emit }) {
    const { createMessage } = useMessage();
    let TinymceData = ref('');
    let tinymceOptions = reactive({
      parameters: {
        type: 'M',
      },
    });
    let accountFormSchema = ref([
      {
        field: 'time',
        label: '日期选择:',
        colProps: { span: 10 },
        component: 'DatePicker',
        required: true,
        componentProps: {
          disabled:false,
          showTime: {
            format: 'YYYY-MM-DD HH:mm:ss',
          },
        },
      },
      {
        field: 'template',
        label: '模版选择',
        component: 'Select',
        colProps: { span: 10 },
        required: true,
        componentProps: {
          disabled:false,
          maxLength: 30,
          // disabled: true,
          options: [
            // { lable: '字典1', value: '字典1' },
            // { lable: '字典2', value: '字典2' },
            // { lable: '字典3', value: '字典3' },
          ],
        },
      },
      {
        field: 'name',
        label: '月报名称',
        component: 'Input',
        colProps: { span: 20 },
        required: true,
        componentProps: {
          disabled:false,
          maxLength: 30,
        },
      },
    ]);
    let getTitle = ref('新增');
    const isUpdate = ref(false);
    const isCopy = ref(false);
    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      console.log('data', data);
      isUpdate.value = data.isUpdate
      isCopy.value = data.isCopy
      getTitle.value = isUpdate.value?'编辑':'新增'
     
      accountFormSchema.value[0].componentProps.disabled = data.isUpdate
      accountFormSchema.value[1].componentProps.disabled = data.isUpdate
      accountFormSchema.value[2].componentProps.disabled = data.isUpdate
      accountFormSchema.value[0].required = !data.isUpdate
      accountFormSchema.value[1].required = !data.isUpdate
      accountFormSchema.value[2].required = !data.isUpdate
      if(isCopy.value){
        getTitle.value = '复制'
      }
      if(isUpdate.value){
        setFieldsValue({
          name:data.itemData.name,
          time:data.itemData.time
        })
       
        setTimeout(() => {
          TinymceData.value = data.itemData.html
        }, 500);
        // console.log(data.itemData.html)
      }else{
        TinymceData.value = ''
        resetFields()
      }
    });
    const [registerForm, { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue }] =
      useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 18,
        },
      });

    async function handleSubmit() {
      try {
        if (!isUpdate.value) {
          const userInfo = await userStore;
          console.log(userInfo)
          const _value = await validate();
          let formData = JSON.parse(JSON.stringify(getFieldsValue()))
          formData.type = 'M'
          formData.content = TinymceData.value
          formData.user = userInfo.userInfo.username;
          formData.operation_time = moment().format('YYYY-MM-DD HH:mm:ss')
          getNewJianbao(formData).then(res => {
            if (res.code == 200) {
              createMessage.success('新增成功');
              closeModal();
              emit('success');
              TinymceData.value = ''
              resetFields()
            }
          })
        }else{
          if(!isCopy.value){
            const userInfo = await userStore;
            let formData = JSON.parse(JSON.stringify(getFieldsValue()))
            formData.type = "M"
            formData.user = userInfo.userInfo.username;
            formData.operation_time = moment().format('YYYY-MM-DD HH:mm:ss')
            formData.content = TinymceData.value
            getModifyJianbao(formData).then(res => {
              if (res.code == 200) {
                createMessage.success('编辑成功');
                closeModal();
                emit('success');
                TinymceData.value = ''
                resetFields()
              }
            })
          }else{
            const userInfo = await userStore;
            let formData = JSON.parse(JSON.stringify(getFieldsValue()))
            formData.type = "M"
            formData.user = userInfo.userInfo.username;
            formData.operation_time = moment().format('YYYY-MM-DD HH:mm:ss')
            formData.content = TinymceData.value
            console.log(formData)
            getNewJianbao(formData).then(res => {
            if (res.code == 200) {
              createMessage.success('复制成功');
              closeModal();
              emit('success');
              TinymceData.value = ''
              resetFields()
            }
          })
          }
         
        }

      } catch (error) {

      }
    }
    const generate = async () => {
      try {
        const _value = await validate();
        let formData = JSON.parse(JSON.stringify(getFieldsValue()))
        formData.type = 'M'
        formData.content = ''
        templateData.forEach(element => {
          if (element.name == formData.template) {
            formData.content = element.content
          }
        });
        getJianbaoGenerate(formData).then(res => {
          TinymceData.value = res.data
        })
      } catch (error) {

      }

    };
    const handleChange = () => {
      console.log('这里是富文本插件');
    };
    const exportWord = () => {
      let content = `
       	<!DOCTYPE html><html>
            	<head>
                  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              </head>
              <body>
                  <table>
                  		${TinymceData.value}
                	</table>
              </body>
            </html>`;
      let converted = htmlDocx.asBlob(content);
      FileSaver.saveAs(converted, getFieldsValue().name + '.docx');
    };
    let templateData = []
    const getJianbaoTemplateFn = () => {
      getJianbaoTemplate().then(res => {
        let templateArr = []
        templateData = JSON.parse(JSON.stringify(res.data))
        res.data.forEach(element => {
          templateArr.push({
            laber: element.name,
            value: element.name
          })
        });
        accountFormSchema.value[1].componentProps.options = templateArr
      })
    }
    onMounted(() => {
      getJianbaoTemplateFn()
    })
    return {
      registerModal,
      getTitle,
      handleSubmit,
      registerForm,
      generate,
      TinymceData,
      handleChange,
      tinymceOptions,
      exportWord,
      isUpdate
    };
  },
});
</script>
<style scoped lang="less">
.form-box {
  position: relative;

  .form-btn {
    position: absolute;
    bottom: 20px;
    right: 0px;
  }
}

.rich-text-box {
  border-left: 4px solid #2d74e7;
  position: relative;
  padding-left: 10px;
  margin-bottom: 10px;

  div {
    position: absolute;
    right: 0px;
    top: 0px;

    img {
      display: inline-block;
      vertical-align: middle;
      margin-left: 10px;
    }

    span {
      vertical-align: middle;
      // margin-left: 5px;
      cursor: pointer;
    }
  }
}

.rich {
  height: 480px;
}

::v-deep(.ant-calendar-picke) {
  width: 100%;
}
</style>
