<template>
  <div class="bg-[#fff]">
    <a-page-header :backIcon="false">
      <template #extra>
        <a-button type="primary" v-if="params.flag != '1' && params.flag != '2'" :loading="loadingSubmit" @click="toSaveOrSubmit('submit')"
          >提交</a-button
        >
        <a-button type="primary" v-if="params.flag != '1' && params.flag != '2'" :loading="loadingSave" @click="toSaveOrSubmit('save')" class="ml-2"
          >保存</a-button
        >
        <a-button type="primary" @click="router.go(-1)">返回</a-button>
      </template>
    </a-page-header>
    <a-collapse v-model:activeKey="activeKey" :bordered="false">
      <a-collapse-panel key="1" header="监理单位基本信息">
        <unitMessageForm ref="jldw" upload=" " :data="jlDw" :isRead="params.flag == '1' || params.flag == '2'" />
      </a-collapse-panel>
      <a-collapse-panel key="2" header="运输单位基本信息">
        <unitMessageForm ref="ysdw" upload=" " :data="ysDw" :isRead="params.flag == '1' || params.flag == '2'" />
      </a-collapse-panel>
      <a-collapse-panel key="3" header="处置单位基本信息">
        <unitMessageForm ref="czdw" upload=" " :data="czDw" :isRead="params.flag == '1' || params.flag == '2'" />
      </a-collapse-panel>
    </a-collapse>
    <div class="pt-5">
      <!-- 详情：转运计划填报 -->
      <BasicForm @register="registerForm" />
      <!-- 详情：接收完成填报 -->
      <template v-if="params.type === 'detail'">
        <a-divider orientation="left" />
        <fillingendInfo :data="fillingendData" />
      </template>
      <div v-if="params.type === 'detail'" class="p-3">
        <a-divider orientation="left">历史记录</a-divider>
        <a-table :columns="historyColumns" :data-source="zyjhHisList" :pagination="false" bordered size="middle">
          <!--操作栏-->
          <template #action="{ record }">
            <a-button type="link" @click="toDetail(record)">查看</a-button>
          </template>
        </a-table>
      </div>
      <fillingHistoryInfoModal @register="registerModal" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  import { saveOredit, findSzdzg, findJsdzg, queryZyjh } from '../api';
  import { useMessage } from '/@/hooks/web/useMessage';
  import unitMessageForm from '/@/components/customComponent/unitMessageForm.vue';
  import fillingHistoryInfoModal from '../modal/fillingHistoryInfoModal.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import { historyColumns } from '../data';
  import fillingendInfo from './fillingendInfo.vue';
  const [registerModal, { openModal }] = useModal();
  // Emits声明
  const { createMessage } = useMessage();
  const emit = defineEmits(['register']);
  const activeKey = ref(['1', '2', '3', '4']);
  const loadingSubmit = ref(false);
  const loadingSave = ref(false);
  const router = useRouter();
  const params = ref<any>(router.currentRoute.value.query);
  const userStore: any = useUserStore();
  const jszgId = ref<any>({ realname: '' });

  const AdviceFormSchema: FormSchema[] = [
    { label: '污染地块ID', field: 'id', component: 'Input', show: false },
    {
      label: '地块所在地主管部门',
      field: 'szdzgbm',
      required: true,
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '接收地主管部门',
      field: 'jsdzgbm',
      required: true,
      component: 'ApiSelect',
      componentProps: () => {
        let bm = params.value.wrdkbm;
        if (userStore.userInfo.userType == 'S') bm = '';
        return {
          api: findJsdzg,
          params: { wrdkbm: bm },
          labelField: 'realname',
          valueField: 'id',
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
        };
      },
    },
    {
      label: '土壤转运时间',
      field: 'trzysj',
      required: true,
      component: 'Input',
      // component: 'DatePicker',
      componentProps: {
        // format: 'YYYY-MM-DD',
        // valueFormat: 'YYYY-MM-DD',
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '土壤运输方式',
      field: 'trysfs',
      required: true,
      component: 'Input',
      componentProps: {
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '土壤运输路线',
      field: 'tryslx',
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: '起点→XX路→XX大道→XX高速→终点',
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '污染土壤转运总量',
      field: 'wrtryzzl',
      required: true,
      component: 'InputNumber',
      componentProps: {
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '处置措施',
      field: 'czcs',
      required: true,
      component: 'CheckboxGroup',
      componentProps: {
        //options里面由一个一个的radio组成,支持disabled
        options: [
          { label: '水泥窑', value: '水泥窑' },
          { label: '集中处置场所', value: '集中处置场所' },
          { label: '填埋', value: '填埋' },
          { label: '其他', value: '其他' },
        ],
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '计划处置完成期限',
      field: 'jhczwcqx',
      required: true,
      component: 'InputNumber',
      componentProps: {
        disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
      },
    },
    {
      label: '土壤转运计划表',
      field: 'tryzjhb',
      required: true,
      component: 'JUpload',
      componentProps: () => {
        return {
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
          showUploadList: false,
          fileName: '土壤转运计划表',
          accept: '.xls,.xlsx',
          beforeUpload: (file) => {
            let isshow = false;
            if (file.type == 'application/vnd.ms-excel' || file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
              isshow = true;
            } else {
              createMessage.error('只能上传.xls/.xlsx格式的文件');
              isshow = false;
            }
            return isshow;
          },
        };
      },
    },
    {
      label: '处置单位环评材料',
      field: 'czdwhpcl',
      required: true,
      component: 'JUpload',
      componentProps: () => {
        return {
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
          showUploadList: false,
          fileName: '处置单位环评材料',
          accept: '.pdf,.zip',
          beforeUpload: (file) => {
            let isshow = false;
            const isFile = file.name.split('.')[file.name.split('.').length - 1];
            if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF') {
              isshow = true;
            } else {
              createMessage.error('只能上传.pdf/.zip格式的文件');
              isshow = false;
            }

            return isshow;
          },
        };
      },
    },
    {
      label: '污染土壤处置合同或协议',
      field: 'wrtrczhthxy',
      required: true,
      component: 'JUpload',
      componentProps: () => {
        return {
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
          showUploadList: false,
          fileName: '污染土壤处置合同或协议',
          accept: '.pdf,.zip,.doc,.docx',
          beforeUpload: (file) => {
            let isshow = false;
            const isFile = file.name.split('.')[file.name.split('.').length - 1];
            if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF' || isFile == 'doc' || isFile == 'docx') {
              isshow = true;
            } else {
              createMessage.error('只能上传.pdf/.zip格式的文件');
              isshow = false;
            }

            return isshow;
          },
        };
      },
    },
    {
      label: '对处置单位的现场核查材料',
      field: 'dczdwdxchccl',
      required: true,
      component: 'JUpload',
      componentProps: () => {
        return {
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
          showUploadList: false,
          fileName: '对处置单位的现场核查材料',
          accept: '.pdf,.zip',
          beforeUpload: (file) => {
            let isshow = false;
            const isFile = file.name.split('.')[file.name.split('.').length - 1];
            if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF') {
              isshow = true;
            } else {
              createMessage.error('只能上传.pdf/.zip格式的文件');
              isshow = false;
            }

            return isshow;
          },
        };
      },
    },
    {
      label: '土壤危废鉴别材料',
      field: 'trwfjbcl',
      required: true,
      component: 'JUpload',
      componentProps: () => {
        return {
          disabled: params.value.type == 'detail' || params.value.flag == '1' || params.value.flag == '2',
          showUploadList: false,
          fileName: '土壤危废鉴别材料',
          accept: '.pdf,.zip',
          beforeUpload: (file) => {
            let isshow = false;
            const isFile = file.name.split('.')[file.name.split('.').length - 1];
            if (isFile == 'pdf' || isFile == 'zip' || isFile == 'PDF') {
              isshow = true;
            } else {
              createMessage.error('只能上传.pdf/.zip格式的文件');
              isshow = false;
            }

            return isshow;
          },
        };
      },
    },
  ];
  const jlDw = ref();
  const ysDw = ref();
  const czDw = ref();

  const jldw = ref();
  const ysdw = ref();
  const czdw = ref();

  //表单配置
  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 220,
    schemas: AdviceFormSchema,
    showActionButtonGroup: false,
    baseColProps: { span: 12 },
  });
  const getJSZG = async () => {
    let bm = params.value.wrdkbm;
    if (userStore.userInfo.userType == 'S') bm = '';
    jszgId.value = await findSzdzg({ wrdkbm: bm });
    const res = { szdzgbm: jszgId?.value?.realname };
    setFieldsValue({ ...res });
  };
  getJSZG();
  const fillingendData = ref();
  async function getData() {
    const res = await queryZyjh({ id: params.value.id });
    fillingendData.value = {
      sjzysj: res.czwc?.sjzysj,
      sjzyzl: res.czwc?.sjzyzl,
      jhsfypy: res.czwc?.jhsfypy,
      pyqksm: res.czwc?.pyqksm,
      zyldlj: res.czwc?.zyldlj,
    };
    jlDw.value = res.dwxxList[0];
    ysDw.value = res.dwxxList[1];
    czDw.value = res.dwxxList[2];
    zyjhHisList.value = res.zyjhHisList;
    res.szdzgbm = jszgId?.value?.realname;

    setFieldsValue({ ...res });
  }
  if (params.value.flag != '-1') getData();

  // 调接口复制根据flg=1代表提交过的

  async function toSaveOrSubmit(type) {
    const jlList = await jldw.value.getFormValueBz();
    jlList.jgtype = 'jldw';
    const ysList = await ysdw.value.getFormValueBz();
    ysList.jgtype = 'ysdw';
    const czList = await czdw.value.getFormValueBz();
    czList.jgtype = 'czdw';

    let values = await validate();
    values.dwxxList = [jlList, ysList, czList];
    values.id = params.value.id;
    values.szdzgbm = jszgId.value.id;

    if (type === 'save') {
      try {
        values.flag = 0;
        loadingSave.value = true;
        await saveOredit(values);
      } finally {
        loadingSave.value = false;
      }
    }
    if (type === 'submit') {
      try {
        values.flag = 1;
        loadingSubmit.value = true;
        await saveOredit(values);
        router.go(-1);
      } finally {
        loadingSubmit.value = false;
      }
    }
  }
  const zyjhHisList = ref([]);
  const toDetail = (record) => {
    openModal(true, {
      record: record.his ? JSON.parse(record.his) : {},
    });
  };
</script>

<style lang="less" scoped>
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
