<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="50%">
    <BasicForm @register="registerForm" style="padding-bottom:20px;"> 
      <template #upload="{ model, field }">
        <a-upload 
          :beforeUpload="beforeUpload" 
          :showDownloadBtn="true"
          :headers="headers"
          :multiple="multiple"
          :action="uploadUrl"
          :showUploadList="false"
          fileName="相关材料"
          :maxCount="1"
          @change="onFileChange"
          accept=".pdf,.zip,.doc,.docx">
          <a-button>
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
        <a-button size="small" type="primary" v-show="fileList" @click="down(fileList, '相关材料')" style="height:32px;padding:4px 15px;margin-left:10px;">
          <DownloadOutlined></DownloadOutlined> 下载
        </a-button>
      </template>
    </BasicForm>
    <a-table :dataSource="dataSource" :columns="columns" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref, reactive } from 'vue';
  import { FormSchema } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { submiDqr, fhHis } from '@/api/common/api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadUrl, downloadFile} from '/@/api/common/api';
  import { getToken } from '/@/utils/auth';
  import { UploadOutlined, DownloadOutlined } from '@ant-design/icons-vue';
  const emit = defineEmits(['register', 'success']);
  const fjcllj = ref('');
  const ishow = ref(false);
  const isUpdate = ref(true);
  const uploadRef = ref();
  const { createMessage } = useMessage();
  const fileList = ref('');
  const headers = reactive({
    'X-Access-Token': getToken(),
  });
  function down(url, name) {
    let fileExtension = url.split('.').pop();
    downloadFile('/sys/common/static' + url, `${name}.${fileExtension}`);
  }
  const AdviceFormSchema: FormSchema[] = [
    { label: '污染地块ID', field: 'wrdkid', required: true, component: 'Input', show: false },
    { label: '所处阶段编码', field: 'scjdbm', component: 'Input', show: false },
    { label: 'pgtype', field: 'pgtype', component: 'Input', show: false },
    { label: '填报阶段编码', field: 'jdnzt', component: 'Input', show: false },
    {
      label: '复核报告是否通过 ',
      field: 'nodeType',
      component: 'Select',
      required: true,
      defaultValue: 1,
      componentProps: {
        options: [
          { label: '复核通过', value: 1 },
          { label: '复核需继续修改', value: 2 },
        ],
        onChange: (v) => {
          if (v == 2) {
            updateSchema({
              label: '退回意见',
              required: true,
              field: 'clyj',
              component: 'InputTextArea',
              show: true,
            });
            updateSchema({
              field: 'clyjfj',
              show: false,
            });
          } else {
            updateSchema({
              label: '退回意见',
              required: false,
              field: 'clyj',
              component: 'InputTextArea',
              show: false,
            });
            updateSchema({
              label: '相关材料',
              field: 'clyjfj',
              component: 'JUpload',
              show: true,
              slot: 'upload',
              // componentProps: {
              //   showUploadList: false,
              //   maxCount: 1,
              //   fileName: '相关材料',
              //   accept: '.pdf,.zip,.rar,.doc,.docx',
              //   beforeUpload: (file) => {
              //     let isshow = false;
              //     const isFile = file.name.split('.')[file.name.split('.').length - 1];
              //     console.log(file, 'file');
              //     if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF' || isFile == 'rar' || isFile == 'doc' || isFile == 'docx') {
              //       isshow = true;
              //     } else {
              //       createMessage.error('只能上传.pdf/.zip/.rar/word格式的文件');
              //       isshow = false;
              //     }
              //     return isshow;
              //   },
              // },
            });
          }
        },
      },
    },
    {
      label: '复核时间',
      field: 'clsj',
      required: true,
      component: 'DatePicker',
        componentProps: {
            //日期格式化，页面上显示的值
            format: 'YYYY-MM-DD',
            //返回值格式化（绑定值的格式）
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            //是否显示今天按钮
            showToday: true,
        },
    },
    {
      label: '报告编制单位首次提交报告修改稿的时间',
      field: 'submitTsamp',
      required: true,
      component: 'DatePicker',
        componentProps: {
            //日期格式化，页面上显示的值
            format: 'YYYY-MM-DD',
            //返回值格式化（绑定值的格式）
            valueFormat: 'YYYY-MM-DD',
            //是否显示今天按钮
            showToday: true,
        },
    },
    {
      label: '退回意见',
      field: 'clyj',
      component: 'InputTextArea',
      show: false,
    },
    {
      label: '相关材料',
      field: 'clyjfj',
      component: 'JUpload',
      show: true,
      slot: 'upload',
      // componentProps: {
      //   showUploadList: false,
      //   fileName: '相关材料',
      //   maxCount: 1,
      //   accept: '.pdf,.zip,.doc,.docx',
        
      // },
    },
  ];
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 300,
    schemas: AdviceFormSchema,
    showActionButtonGroup: false,
  });
  const datas = ref();
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    //表单赋值
    datas.value = data.record;
    getfhHis({ wrdkid: datas.value.wrdkid, scjdbm: datas.value.scjdbm, jdnzt: datas.value.jdnzt, pgtype: datas.value.pgtype });

    await setFieldsValue({
      ...data.record,
    });
  });
  //设置标题
  const title = ref('复核评审信息');
  const dataSource = ref<any>();
  const columns = [
    {
      title: '记录生成时间',
      dataIndex: 'clsj',
      key: 'clsj',
    },

    {
      title: '复核是否通过',
      dataIndex: 'nodeType',
      key: 'nodeType',
      customRender: ({ record }: any) => {
        if (record.nodeType == '1') {
          return '是';
        } else if (record.nodeType == '2') return '否';
      },
    },
    {
      title: '退回意见',
      dataIndex: 'clyj',
      key: 'clyj',
    },
  ];
  //  获取历史评审
  async function getfhHis(v) {
    console.log(v, 'v');
    dataSource.value = await fhHis(v);
  }
  function beforeUpload(file) {
    // console.log(file, 'file');
    let isshow = false;
    const isFile = file.name.split('.')[file.name.split('.').length - 1];
    if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF' || isFile == 'rar' || isFile == 'doc' || isFile == 'docx') {
      isshow = true;
    } else {
      createMessage.error('只能上传.pdf/.zip/.rar/word格式的文件');
      isshow = false;
    }
    return isshow;
  }
  // upload组件change事件
  async function onFileChange(info) {
    console.log(info, 'info');
    if (info.file.status === 'done') {
      if (info.file.response.success) {
        createMessage.success('上传成功');
        fileList.value = info.file.response.message;
      } else {
        createMessage.error(`${info.file.response.message}`);
      }
    } else if (info.file.status === 'error') {
      createMessage.error(`${info.file.response.message}`);
    }
    if (info.file.status === 'removed') {
      fileList.value = '';
    }
  }
  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      values.clyjfj = fileList.value;
      if (values.nodeType == 1) {
        values.clyj = '复核通过';
      }
      //提交表单
      await submiDqr(values);
      //关闭弹窗
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped></style>
