<template>
  <div class="bg-[#fff]">
    <a-page-header :backIcon="false">
      <template #extra>
        <a-button type="primary" :loading="loadingSubmit" @click="toSaveOrSubmit('submit')">提交</a-button>
        <a-button type="primary" :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" class="collapse-bg">
      <a-collapse-panel key="4" header="材料信息" v-show="psxxData.xghdcl">
        <label>修改后材料:</label> <a-button type="primary" @click="down(psxxData?.xghdcl, '修改材料')"> 下载</a-button>
      </a-collapse-panel>
      <a-collapse-panel key="1" header="评审信息">
        <!-- 与地块调查有不同之处 -->
        <MaterialUpload ref="MaterialUploadRef" :data="psxxData1" @change-psfs="changePsfs" :dksdzt="dksdzt" />
      </a-collapse-panel>
      <a-collapse-panel key="2">
        <template #header>
          <span v-if="psfs === 2">专家组信息(选填)</span>
          <span v-else class="required">专家组信息</span>
        </template>
        <template #extra>
          <a-button type="primary" @click.stop="handleExportXls('专家组模板', getZjzmbUrl)">下载模板</a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :customRequest="
              (d) => {
                onImportXls(d, 'panel');
              }
            "
            @click.stop
            class="ml-2"
          >
            <a-button type="primary">上传</a-button>
          </a-upload>
          <a-button type="primary" @click.stop="handleInfo('panel', 'add')" class="ml-2">添加</a-button>
        </template>
        <PanelInfo ref="PanelInfoRef" v-model:data="zjzData" :psfs="psfs" />
      </a-collapse-panel>
      <a-collapse-panel key="3">
        <template #header>
          <span v-if="psfs === 2">参会人员信息(选填)</span>
          <span v-else class="required">参会人员信息</span>
        </template>
        <template #extra>
          <a-button type="primary" @click.stop="handleExportXls('参会人员模板', getChrymbtUrl)">下载模板</a-button>
          <a-upload
            name="file"
            :showUploadList="false"
            :customRequest="
              (d) => {
                onImportXls(d, 'participant');
              }
            "
            @click.stop
            class="ml-2"
          >
            <a-button type="primary">上传</a-button>
          </a-upload>
          <a-button type="primary" @click.stop="handleInfo('participant', 'add')" class="ml-2">添加</a-button>
        </template>
        <ParticipantInfo ref="ParticipantInfoRef" v-model:data="chryData" :psfs="psfs" />
      </a-collapse-panel>
    </a-collapse>
    <div class="m-4">
      <HistoryInfo :wrdkid="wrdkid" :pgtype="pgtype" :scjdbm="scjdbm" :dksdzt="dksdzt" :faid="faid" type="xfpg" />
    </div>
  </div>
</template>
<script lang="ts" name="dkgl-xfpg-modal-ReviewMaterialUpload" setup>
  import { getZjyj, updateZjcy, submitZjyj, getZjzmbUrl, getChrymbtUrl, getScchryUrl, getCcxx, updateCcZjcy, submitCcZjyj } from '@/api/dkgl.api';
  import MaterialUpload from '../components/MaterialUpload.vue'; // 新组件
  import PanelInfo from '@/views/dkgl/investigate/components/PanelInfo.vue'; // 完全一样（地块调查的组件）
  import ParticipantInfo from '@/views/dkgl/investigate/components/ParticipantInfo.vue'; //完全一样（地块调查的组件）
  import HistoryInfo from '@/components/customComponent/HistoryInfo.vue'; // 新组件
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isMobile, checkPhone, checkEmail } from '/@/utils/validate';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { encryptData, downloadFile } from '/@/api/common/api';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';

  const activeKey = ref(['1', '2', '3', '4']);
  const router = useRouter();
  const { createMessage } = useMessage();
  // 如果只用一个变量，当用户填写评审信息之后，再填写专家组信息或者参会人员信息，会把评审信息清空
  const psxxData = ref<any>({}); // 存储评审信息
  const psxxData1 = ref<any>({}); // 存储评审信息
  const zjzData = ref<any>([]); // 存储专家组信息
  const chryData = ref<any>([]); // 存储参会人员信息
  const MaterialUploadRef = ref<any>(null);
  const PanelInfoRef = ref<any>(null);
  const ParticipantInfoRef = ref<any>(null);
  const wrdkid = ref<any>(router.currentRoute.value.query.wrdkid);
  const pgtype = ref<any>(router.currentRoute.value.query.pgtype);
  const scjdbm = ref<any>(router.currentRoute.value.query.scjdbm);
  const dksdzt = ref<any>(router.currentRoute.value.query.dksdzt); //只有抽查的时候才有值
  const faid = ref<any>(router.currentRoute.value.query.faid);

  const { handleImportXls, handleExportXls } = useMethods();

  const psfs = ref(1);
  const loadingSubmit = ref(false);
  const loadingSave = ref(false);
  getInfo();
  function changePsfs(val) {
    psfs.value = val;
  }
  function onImportXls(d, type) {
    handleImportXls(d, getScchryUrl, (res) => {
      if (res.code === 200) {
        if (type === 'panel') {
          if (!zjzData.value) zjzData.value = [];
          zjzData.value.push(...res.result);
        }
        if (type === 'participant') {
          if (!chryData.value) chryData.value = [];
          chryData.value.push(...res.result);
        }
      }
    });
  }
  function createPanelRow(isHead = 0) {
    return {
      zjxm: '',
      gzdw: '',
      zczw: '',
      lxdh: '',
      mail: '',
      isHead,
      bz: '',
    };
  }
  let participantRow = ref({
    zjxm: '',
    gzdw: '',
    zczw: '',
    lxdh: '',
    mail: '',
    bz: '',
  });
  // 获取评审信息
  async function getInfo() {
    let res;
    if (dksdzt.value == 1) {
      res = await getCcxx({
        wrdkid: wrdkid.value,
        faid: faid.value,
        scjdbm: scjdbm.value,
        pgtype: pgtype.value,
      });
    } else {
      res = await getZjyj({
        wrdkid: wrdkid.value,
        pgtype: pgtype.value,
        scjdbm: scjdbm.value,
      });
    }
    if (res) {
      psxxData.value = res;
      zjzData.value = res.zjz;
      chryData.value = res.chry;
      // 添加的时候人员或者专家的时候会清空上面的数据 响应式的问题
      psxxData1.value = res;
      delete psxxData1.value.zjz;
      delete psxxData1.value.chry;
    }
  }
  async function toSaveOrSubmit(type) {
    // 提交，校验，保存，不校验
    let p = type === 'submit' ? await MaterialUploadRef?.value.validate() : await MaterialUploadRef?.value.getFormValues();
    if (PanelInfoRef?.value) {
      p.zjz = await PanelInfoRef?.value?.localData;
    } else {
      p.zjz = zjzData.value;
    }
    if (ParticipantInfoRef?.value) {
      p.chry = await ParticipantInfoRef?.value?.localData;
    } else {
      p.chry = chryData.value.chry;
    }
    p.wrdkid = psxxData.value.wrdkid;
    p.zjyjid = psxxData.value.zjyjid;
    p.scjdbm = psxxData.value.scjdbm;
    if (!(router.currentRoute.value.query.isnyd2yzlg === '1')) {
      // 不是一住两公,手动赋值，是的话，能最直接获取到表单的值
      p.dcjdPsfs = 1;
    }
    console.log('参数', p);
    if (type === 'submit') {
      // 专家组信息、参会人员信息-必填
      if (psfs.value === 1) {
        if (!p.zjz?.length) {
          createMessage.info('请填写专家组信息');
          return;
        }
        if (!p.chry?.length) {
          createMessage.info('请填写参会人员信息');
          return;
        }
      }
      // 专家组信息-必填、选填
      if (p.zjz && p.zjz.length) {
        if (p.zjz.every((i) => i.isHead === 0)) {
          createMessage.info('请选择专家组长');
          return;
        }
        let isDuplicate = checkDuplicate(p.zjz);
        if (isDuplicate) {
          createMessage.info('有重复的专家信息');
          return;
        }
        if (p.zjz.some((i) => !i.zjxm)) {
          createMessage.info('专家姓名不能为空');
          return;
        }
        if (p.zjz.some((i) => !i.gzdw)) {
          createMessage.info('专家工作单位不能为空');
          return;
        }
        if (p.zjz.some((i) => !i.zczw)) {
          createMessage.info('专家职务不能为空');
          return;
        }
        if (p.zjz.some((i) => !i.lxdh)) {
          createMessage.info('专家联系电话不能为空');
          return;
        }
        if (p.zjz.some((i) => i.lxdh && !isMobile(i.lxdh) && !checkPhone(i.lxdh))) {
          createMessage.info('请输入正确的联系方式，如：13800138000/01012345678');
          return;
        }
        if (p.zjz.some((i) => i.mail && !checkEmail(i.mail))) {
          createMessage.info('请输入正确的邮箱，如：xxxx@qq.com');
          return;
        }
      }
      // 参会人员信息-必填、选填
      if (p.chry && p.chry.length) {
        let isDuplicate = checkDuplicate(p.chry);
        if (isDuplicate) {
          createMessage.info('有重复的参会人员信息');
          return;
        }
        if (p.chry.some((i) => !i.zjxm)) {
          createMessage.info('参会人姓名不能为空');
          return;
        }
        if (p.chry.some((i) => !i.gzdw)) {
          createMessage.info('参会人工作单位不能为空');
          return;
        }
        if (p.chry.some((i) => !i.zczw)) {
          createMessage.info('参会人职务不能为空');
          return;
        }
        if (p.chry.some((i) => !i.lxdh)) {
          createMessage.info('参会人电话不能为空');
          return;
        }
        if (p.chry.some((i) => i.lxdh && !isMobile(i.lxdh) && !checkPhone(i.lxdh))) {
          createMessage.info('请输入正确的联系方式，如：13800138000/01012345678');
          return;
        }
        if (p.chry.some((i) => i.mail && !checkEmail(i.mail))) {
          createMessage.info('请输入正确的邮箱，如：xxxx@qq.com');
          return;
        }
      }
    }
    p.zjz.forEach((element) => {
      if (element.isHead) {
        element.isHead = '1';
      }
    });
    let obj = { pgtype: pgtype.value };
    let objs = JSON.stringify(p);
    let result = JSON.parse(objs);
    result = { ...result, ...obj };

    // 专家组电话加密
    // if (result.zjz.length > 0) {
    //   result.zjz.forEach(async (item) => {
    //     if (item.lxdh) {
    //       item.lxdh = await encryptData({ str: item.lxdh });
    //     }
    //   });
    // }
    // 参会人员电话加密
    // if (result.chry.length > 0) {
    //   result.chry.forEach(async (item) => {
    //     if (item.lxdh) {
    //       item.lxdh = await encryptData({ str: item.lxdh });
    //     }
    //   });
    // }
    setTimeout(async () => {
      if (type === 'save') {
        try {
          loadingSave.value = true;
          if (dksdzt.value != 1) await updateZjcy(result);
          else await updateCcZjcy(result);
        } finally {
          loadingSave.value = false;
        }
      }
      if (type === 'submit') {
        try {
          loadingSubmit.value = true;
          if (dksdzt.value != 1) await submitZjyj(result);
          else await submitCcZjyj(result);
          router.go(-1);
        } finally {
          loadingSubmit.value = false;
        }
      }
    }, 1000);
  }
  async function handleInfo(page, type) {
    // 添加
    if (type === 'add') {
      if (page === 'panel') {
        zjzData.value = zjzData.value || [];
        if (zjzData.value.length) {
          zjzData.value.push(createPanelRow(0));
        } else {
          zjzData.value.push(createPanelRow(1));
        }
      }
      if (page === 'participant') {
        chryData.value = chryData.value || [];
        chryData.value.push(participantRow.value);
      }
    }
  }
  function checkDuplicate(arr) {
    let uniqueSet = new Set();
    let isDuplicate = arr.some((i) => {
      let key = `${i.zjxm}${i.lxdh}`;
      let oldSize = uniqueSet.size;
      uniqueSet.add(key);
      return uniqueSet.size === oldSize;
    });
    return isDuplicate;
  }
  function down(url, name) {
    let fileExtension = url.split('.').pop();
    downloadFile('/sys/common/static' + url, `${name}.${fileExtension}`);
  }
</script>
