<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" :height="450" @ok="handleSubmit">
    <a-tabs v-show="step == 1" v-model:activeKey="activeKey" type="card">
      <a-tab-pane key="1" tab="组织">
        <DepartCheckbox :actCheckbox="configCheckData.departCheck" />
      </a-tab-pane>
      <a-tab-pane key="2" tab="人员">
        <UserCheckbox ref="userCheckboxRef" :actCheckbox="configCheckData.userCheck" :depIds="getDepdIs()" />
      </a-tab-pane>
      <a-tab-pane key="3" tab="系统">
        <SysCheckbox :actCheckbox="configCheckData.sysCheck" />
      </a-tab-pane>
      <a-tab-pane key="4" tab="外包商">
        <OuterCheckbox :actCheckbox="configCheckData.outerCheck" />
      </a-tab-pane>
      <a-tab-pane key="5" tab="项目">
        <ProjectCheckbox :actCheckbox="configCheckData.projectCheck" />
      </a-tab-pane>
    </a-tabs>
    <!-- <div v-show="step==2">
      <a-form  
      :labelCol="{xs: {span: 24},sm: {span: 4},}"
      :wrapperCol="{xs: {span: 24},sm: {span: 20},}">
        <a-form-item label="控制活动集合"  :rules="[{ required: true, message: '请选择控制活动集合!' }]">
          <SelectActCollectionInput :model="actSelect" field="caNo" :caNo="actSelect.caNo" />
        </a-form-item>
      </a-form>
    </div>  -->
    <div v-show="step == 2">
      <a-table :dataSource="userDataSource" :columns="userColumns" :pagination="false" bordered :scroll="{ y: 250 }">
        <template #bodyCell="{ text, record, index, column }">
          <template v-if="column.key === 'index'">{{ index + 1 }}</template>
          <template v-if="column.key === 'operation'"
            ><a-button type="link" :disabled="record.projectRole == 'head'" @click="handlerUserDelete(record.id)">移除</a-button></template
          >
        </template>
      </a-table>
      <a-button type="primary" style="width: 100%" @click="addConfigUser">添加新人员</a-button>
      <UserAddModal @register="registerModalAddUser" @success="handleUserAddModalSuccess" />
    </div>

    <div v-show="step == 3">
      <CheckMethodConfig ref="ckmRef" :projectCreId="proCreData.id" />
    </div>
    <div v-show="step == 4">
      <DutyConfig ref="dcRef" :projectCreId="proCreData.id" />
    </div>
    <div v-show="step == 5">
      <CollectionConfig ref="ccRef" :projectCreId="proCreData.id" :projectName="proCreData.projectName" />
    </div>
    <div v-show="step == 6">
      <PlanConfig ref="pcRef" :projectCreId="proCreData.id" :projectName="proCreData.projectName" />
    </div>
    <template #footer>
      <a-button v-if="step == 1" @click="handlerCancel">取消</a-button>
      <a-button v-if="step < 7 && step > 1" @click="goUpperStep">上一步</a-button>
      <!-- <a-button v-if="step<6" type="primary" @click="goStepNoSave">下一步</a-button> -->
      <a-button v-if="step < 6" type="primary" @click="goStep">保存并下一步</a-button>
      <a-button v-if="step == 6" @click="saveHandler">仅保存</a-button>
      <a-button v-if="step == 6" type="primary" @click="saveAndSubmitHandler">保存并提交</a-button>
    </template>
  </BasicModal>
</template>
<script setup>
  import { message } from 'ant-design-vue';
  import { computed, ref, unref, watch } from 'vue';
  import {
    add3Step,
    add4Step,
    add5Step,
    add6Step,
    add7Step,
    addOneStep,
    addTwoStep,
    deletePerpetrate,
    queryNoCheckCount,
    queryNoDutyCount,
    queryNoGatherCount,
    queryNoInterviewCount,
    queryPerpetratePageList,
    save2Submit,
  } from '../StProjectConfig.api';
  import CheckMethodConfig from './config/CheckMethodConfig.vue';
  import CollectionConfig from './config/CollectionConfig.vue';
  import DepartCheckbox from './config/DepartCheckbox.vue';
  import DutyConfig from './config/DutyConfig.vue';
  import OuterCheckbox from './config/OuterCheckbox.vue';
  import PlanConfig from './config/PlanConfig.vue';
  import ProjectCheckbox from './config/ProjectCheckbox.vue';
  import SelectActCollectionInput from './config/SelectActCollectionInput.vue';
  import SysCheckbox from './config/SysCheckbox.vue';
  import UserAddModal from './config/UserAddModal.vue';
  import UserCheckbox from './config/UserCheckbox.vue';
  import { BasicModal, useModal, useModalInner } from '/@/components/Modal';

  const [registerModalAddUser, { openModal: openModalAddUser }] = useModal();
  const userCheckboxRef = ref(null);
  const step = ref(1);
  const isUpdate = ref(true);
  const activeKey = ref('1');
  const ckmRef = ref(null);
  const dcRef = ref(null);
  const ccRef = ref(null);
  const pcRef = ref(null);
  const actSelect = ref({
    caNo: '',
  });
  // 项目信息
  const proCreData = ref({});
  const configCheckData = ref({
    projectCreId: '',
    departCheck: {},
    userCheck: {},
    sysCheck: {},
    outerCheck: {},
    projectCheck: {},
  });
  const userColumns = ref([
    {
      title: '序号',
      align: 'left',
      key: 'index',
      dataIndex: 'index',
    },
    {
      title: '人员姓名',
      align: 'left',
      dataIndex: 'userName',
    },
    {
      title: '所属部门',
      align: 'left',
      dataIndex: 'depName',
    },
    {
      title: '岗位',
      align: 'left',
      dataIndex: 'postName',
    },
    {
      title: '项目角色',
      align: 'left',
      dataIndex: 'projectRoleName',
    },
    {
      title: '操作',
      key: 'operation',
    },
  ]);
  const userDataSource = ref([]);
  const emit = defineEmits(['register', 'success']);
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    step.value = 1;
    proCreData.value = Object.assign({}, data.record);
    if (unref(isUpdate)) {
      step.value = !proCreData.value.configStep ? 1 : proCreData.value.configStep;
      if (step.value == 3) {
        handleQueryPerpetratePageList();
      }
    }
  });
  let config = ['', '配置检查范围', '配置实施人员', '配置检查项', '配置责任分工', '配置信息采集', '配置访谈计划'];
  const title = computed(() => '项目准备（' + unref(step) + '/6）- ' + config[unref(step)]);
  watch(activeKey, (newVal, oldVal) => {
    let data = configCheckData.value;
    if (newVal == '2') {
      // if(!checkMap(data.departCheck)){
      //   message.warning("请先选择部门")
      //   activeKey.value = '1'
      //   return
      // }
      // }else{
      //   let ids = []
      //   for(let k in data.departCheck){
      //     if(!!k && data.departCheck[k]){
      //       ids.push(k)
      //     }
      //   }
      //   userCheckboxRef.value?.searchByDepIds(ids)
      // }
    }
  });
  function getDepdIs() {
    let data = configCheckData.value;
    if (checkMap(data.departCheck)) {
      //   message.warning("请先选择部门")
      //   activeKey.value = '1'
      //   return []
      // }else{
      let ids = [];
      for (let k in data.departCheck) {
        if (!!k && data.departCheck[k]) {
          ids.push(k);
        }
      }
      //userCheckboxRef.value?.searchByDepIds(ids)
      return ids;
    }
    return [];
  }
  // 添加人员
  function addConfigUser() {
    openModalAddUser(true, {
      record: { projectCreId: proCreData.value.id },
      isUpdate: false,
      showFooter: true,
    });
  }
  // 删除人员
  function handlerUserDelete(id) {
    deletePerpetrate({ id: id }, function () {
      handleQueryPerpetratePageList();
    });
  }
  function handleUserAddModalSuccess() {
    handleQueryPerpetratePageList();
  }

  async function handleQueryPerpetratePageList() {
    await queryPerpetratePageList({ projectCreId: proCreData.value.id }).then((rep) => {
      userDataSource.value = rep;
    });
  }
  // 上一步
  function goUpperStep() {
    step.value--;
  }

  function goStepNoSave() {
    step.value++;
    if (step.value == 2) {
      handleQueryPerpetratePageList();
    }
    if (step.value == 3) {
      ckmRef.value?.searchByProjectCreId({ projectCreId: proCreData.value.id });
    }
  }
  // 保存并下一步
  function goStep() {
    switch (step.value) {
      case 1:
        if (!oneSave()) {
          return;
        }
        step.value++;
        break;
      case 2:
        threeSave();
        step.value++;
        break;
      case 3:
        queryNoCheckCount({ projectCreId: proCreData.value.id }).then((rep) => {
          if (rep == 0) {
            fourSave();
            step.value++;
            dcRef.value?.searchByProjectCreId({ projectCreId: proCreData.value.id });
          } else {
            message.warning('当前有' + rep + '项未配置的检查方法，请先完成配置。');
          }
        });
        break;
      case 4:
        queryNoDutyCount({ projectCreId: proCreData.value.id }).then((rep) => {
          if (rep == 0) {
            fiveSave();
            step.value++;
            ccRef.value?.searchByProjectCreId({ projectCreId: proCreData.value.id });
          } else {
            message.warning('当前有' + rep + '项检查内容未完成分配，请先完成分配。');
          }
        });
        break;
      case 5:
        queryNoGatherCount({ projectCreId: proCreData.value.id }).then((rep) => {
          if (rep == 0) {
            sixSave();
            step.value++;
            pcRef.value?.searchByProjectCreId({ projectCreId: proCreData.value.id });
          } else {
            message.warning('当前有' + rep + '项检查资料未分配，请先完成分配。');
          }
        });
        break;
      default:
    }
    if (step.value == 2) {
      handleQueryPerpetratePageList();
    }
    if (step.value == 3) {
      ckmRef.value?.searchByProjectCreId({ projectCreId: proCreData.value.id });
    }
  }
  function checkMap(data) {
    for (let k in data) {
      if (!!k && data[k]) {
        return true;
      }
    }
    return false;
  }
  function getKList(data) {
    let ids = [];
    for (let k in data) {
      if (!!k && data[k]) {
        ids.push(k);
      }
    }
    return ids;
  }
  function oneSave() {
    let data = configCheckData.value;
    // if(!checkMap(data.departCheck)){
    //   message.warning("请选择部门")
    //   return false
    // }
    // if(!checkMap(data.userCheck)){
    //   message.warning("请选择人员")
    //   return false
    // }
    // if(!checkMap(data.sysCheck)){
    //   message.warning("请选择系统")
    //   return false
    // }
    // if(!checkMap(data.outerCheck)){
    //   message.warning("请选择外包商")
    //   return false
    // }
    // if(!checkMap(data.projectCheck)){
    //   message.warning("请选择项目")
    //   return false
    // }

    let saveData = {};
    saveData['projectCreId'] = proCreData.value.id;

    if (checkMap(data.departCheck)) {
      saveData['departCheck'] = getKList(data.departCheck);
    }
    if (checkMap(data.userCheck)) {
      saveData['userCheck'] = getKList(data.userCheck);
    }
    if (checkMap(data.sysCheck)) {
      saveData['sysCheck'] = getKList(data.sysCheck);
    }
    if (checkMap(data.outerCheck)) {
      saveData['outerCheck'] = getKList(data.outerCheck);
    }
    if (checkMap(data.projectCheck)) {
      saveData['projectCheck'] = getKList(data.projectCheck);
    }

    try {
      setModalProps({ confirmLoading: true });
      addOneStep(saveData);
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
    return true;
  }
  function twoSave() {
    let data = actSelect.value;
    if (!data.caNo) {
      message.warning('请选择控制活动集合');
      return false;
    }
    let saveData = {};
    saveData['projectCreId'] = proCreData.value.id;
    saveData['collectionNo'] = data.caNo;
    try {
      setModalProps({ confirmLoading: true });
      addTwoStep(saveData);
      // todo
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
    return true;
  }
  function threeSave() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      add3Step(saveData);
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function fourSave() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      add4Step(saveData);
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function fiveSave() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      add5Step(saveData);
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function sixSave() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      add6Step(saveData);
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function saveHandler() {
    queryNoInterviewCount({ projectCreId: proCreData.value.id }).then((rep) => {
      if (rep == 0) {
        onlySave();
      } else {
        message.warning('当前有' + rep + '项访谈计划未分配，请先完成分配。');
      }
    });
  }
  function saveAndSubmitHandler() {
    queryNoInterviewCount({ projectCreId: proCreData.value.id }).then((rep) => {
      if (rep == 0) {
        saveAndSubmit();
      } else {
        message.warning('当前有' + rep + '项访谈计划未分配，请先完成分配。');
      }
    });
  }
  function onlySave() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      add7Step(saveData);
      emit('success');
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function saveAndSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      let saveData = {};
      saveData['projectCreId'] = proCreData.value.id;
      save2Submit(saveData);
      emit('success');
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  // 取消
  function handlerCancel() {
    //关闭弹窗
    closeModal();
  }
  function handlerPlanSelect() {}
  async function handleSubmit() {
    try {
      setModalProps({ confirmLoading: true });

      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
