<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="1" header="评审信息">
        <MaterialUpload ref="MaterialUploadRef" :data="psxxData" @change-psfs="changePsfs" />
      </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>
</template>
<script lang="ts" name="dkgl-repair-modal-ReviewMaterialUpload" setup>
  import { getZjyj, updateZjcy, submitZjyj, getZjzmbUrl, getChrymbtUrl, getScchryUrl } 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 { useMessage } from '/@/hooks/web/useMessage';
  import { isMobile, checkPhone, checkEmail } from '/@/utils/validate';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  const activeKey = ref(['1', '2', '3']);
  const router = useRouter();
  const { createMessage } = useMessage();
  // 如果只用一个变量，当用户填写评审信息之后，再填写专家组信息或者参会人员信息，会把评审信息清空
  const psxxData = 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 { 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,
      memo: '',
    };
  }
  let participantRow = ref({
    zjxm: '',
    gzdw: '',
    zczw: '',
    lxdh: '',
    mail: '',
    memo: '',
  });
  // 获取评审信息
  async function getInfo() {
    const 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;
    }
  }
  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;
        }
      }
    }
    let obj = { pgtype: pgtype.value };
    let objs = JSON.stringify(p);
    let result = JSON.parse(objs);
    result = { ...result, ...obj };
    if (type === 'save') {
      try {
        loadingSave.value = true;
        await updateZjcy(result);
      } finally {
        loadingSave.value = false;
      }
    }
    if (type === 'submit') {
      try {
        loadingSubmit.value = true;
        await submitZjyj(result);
        router.go(-1);
      } finally {
        loadingSubmit.value = false;
      }
    }
  }
  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;
  }
</script>
