<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    destroyOnClose
    title="发起计划"
    :width="1000"
    @ok="handleSubmit"
    @cancel="handleCance"
    :centered="true"
  >
    <a-form :model="formModel" ref="formRef" style="overflow-x: hidden" :disabled="isDetail">
      <a-row gutter="8">
        <a-col :span="12">
          <a-form-item label="计划名称" name="projectName" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-input v-model:value="formModel.projectName" allow-clear :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="类型" name="projectType" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <JCategorySelect pcode="B09" :value="formModel.projectType" :disabled="isDetail" @change="changeJCategory" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计划开始日期" name="planStartDate" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-date-picker v-model:value="formModel.planStartDate" value-format="YYYY-MM-DD" style="width: 100%" :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="计划结束日期" name="planEndDate" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-date-picker v-model:value="formModel.planEndDate" value-format="YYYY-MM-DD" style="width: 100%" :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="依据" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <div>
              <a-tag
                v-for="item in formModel.basisList"
                :key="item.id"
                closable
                @close="removeBasis(item.id)"
                @click="viewBasisDetail(item)"
                :disabled="isDetail"
              >
                {{ item.name }}
              </a-tag>
              <a-button type="link" v-if="showSelectorBtn" @click="openBasisSelector" :disabled="isDetail">添加依据</a-button>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="要求" name="planRequest" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-textarea v-model:value="formModel.planRequest" rows="3" allow-clear :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="交付物" name="planDeliverable" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-input v-model:value="formModel.planDeliverable" allow-clear :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="描述" name="projectDesc" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <a-textarea v-model:value="formModel.projectDesc" rows="3" allow-clear :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="执行规则" name="exeRule" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <vxe-radio-group v-model="formModel.exeRule" :options="exeRules" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="相关附件" name="fileUploadPath" :label-col="{ style: { width: '120px' } }" :wrapperCol="{ span: 16 }">
            <JUpload v-model:value="formModel.fileUploadPath" desText="支持扩展名: .rar .zip .doc .docx .pdf .jpg..." :disabled="isDetail" />
          </a-form-item>
        </a-col>
        <a-col :span="0">
          <a-form-item name="id">
            <a-input v-model:value="formModel.id" type="hidden" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <!-- 选择依据组件 -->
    <BasicCtrlSelector ref="selectorRef" @click="handleSelectorClick" />
    <!-- 依据详情抽屉 -->
    <AuditInnerDetailDrawer ref="AuditInnerDetailDrawerRef" :visible="showDetailDrawer" :basis="selectedBasis" @close="showDetailDrawer = false" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, unref, reactive, h } from 'vue';
  import { message } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { JCategorySelect, JSearchSelectDuty, JSelectDept } from '/@/components/Form';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { list } from '/@/views/newlib/components/api/AuditInnerCtrl.api';
  import { listAll } from '/@/views/newlib/components/api/AuditInnerCtrlItem.api';
  import { saveOrUpdate } from '../StPlanMan.api';

  import AuditInnerDetailDrawer from '/@/views/newlib/components/modal/AuditInnerDetailDrawer.vue';

  defineProps<{
    showSelectorBtn?: boolean;
  }>();
  const AuditInnerDetailDrawerRef = ref();
  const showDetailDrawer = ref(false);
  const selectedBasis = ref<any>(null);

  const viewBasisDetail = (item: any) => {
    selectedBasis.value = item;
    const data = {
      name: item.name,
      comeFrom: item.comeFrom,
    };
    AuditInnerDetailDrawerRef.value?.open(data);
    showDetailDrawer.value = true;
  };
  // Emits声明
  const emit = defineEmits(['register', 'success', 'selector-click']);
  const isUpdate = ref(true);
  const isDetail = ref(false);
  const visible = ref(false);
  const formRef = ref();

  const exeRules = ref([
    { value: 1, label: '每发生' },
    { value: 2, label: '周期性' },
    { value: 3, label: '一次性' },
  ]);


  const formModel = reactive({
    projectName: '',
    projectType: '',
    planRequest: '',
    planDeliverable: '',
    planStartDate: '',
    planEndDate: '',
    basisList: [],
    executeType: '',
    projectDesc: '',
    fileUploadPath: '',
    planBasis: '',
    exeRule:1,
    id: '',
  });
  const resetForm = () => {
    Object.assign(formModel, {
      projectName: '',
      projectType: '',
      planRequest: '',
      planDeliverable: '',
      planStartDate: '',
      planEndDate: '',
      basisList: [],
      executeType: '',
      projectDesc: '',
      fileUploadPath: '',
      planBasis: '',
      exeRule:1,
      id: '',
    });
  };
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    isDetail.value = !data?.showFooter;
    if (unref(isUpdate)) {
      if (data.record['planBasis']) {
        data.record['basisList'] = JSON.parse(data.record['planBasis']);
      }
      Object.assign(formModel, data.record);
    } else {
      formModel.basisList = data.record.map((item) => ({
        id: item.id,
        name: item.name || item.tname,
        ...item,
      }));
    }
  });

  const handleSubmit = async () => {
    try {
      const valids = await formRef.value.validate();
      //const idList = formModel.basisList?.map(item => item.id);
      //if(idList) {
      //  valids["planBasis"] = JSON.stringify(formModel.basisList)
      //}

      if (formModel.basisList) {
        valids['planBasis'] = JSON.stringify(formModel.basisList);
      }

      isUpdate.value = valids.id ? true : false;
      await saveOrUpdate(valids, isUpdate.value);
      emit('success');
      visible.value = false;
      resetForm();
      closeModal();
    } catch (e) {
      console.log(e);
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };
  // const basisSelectMode = ref<'flat' | 'nested'>('flat');
  const selectorRef = ref();
  const basisSelectorConfig = {
    title: '选择依据',
    columns: [
      { title: '内控文件名称', dataIndex: 'name' },
      { title: '说明', dataIndex: 'des' },
      { title: '创建时间', dataIndex: 'createTime' },
      { title: '创建人', dataIndex: 'createUser' },
      {
        title: '操作',
        key: 'action',
        customRender: ({ record }) => {
          return h(
            'a',
            {
              onClick: async () => {
                // 加载二级数据并更新组件中的表格
                const detailData = await listAll({ checkid: record.id });
                selectorRef.value.setDetail({
                  title: '详细内容',
                  columns: [
                    { title: '分类', dataIndex: 'tp', customRender: ({ record }) => formatTp(record) },
                    { title: '监管要求', dataIndex: 'name' },
                    { title: '来源', dataIndex: 'comeForm', customRender: ({ record }) => formatComeFrom(record) },
                    { title: '执行规则', dataIndex: 'exeRule', customRender: ({ record }) => formatExeRules(record) },
                  ],
                  data: detailData,
                  enableRowSelection: true,
                });
              },
            },
            '查看详情'
          );
        },
      },
    ],
    fetchData: async () => {
      const res = await list({ pageNo: 1, pageSize: 10 });
      return {
        records: res.records,
        total: res.total,
      };
    },
  };

  const openBasisSelector = async () => {
    const selected = await selectorRef.value.openSelector({
      multiple: true,
      config: basisSelectorConfig,
    });

    const mergedArray = [...formModel.basisList, ...selected.selectedRows];
    formModel.basisList = mergedArray;
  };

  const removeBasis = (id: string) => {
    formModel.basisList = formModel.basisList.filter((item) => item.id !== id);
    selectorRef.value?.unselectRowById(id);
  };

  const handleSelectorClick = () => {
    emit('selector-click');
  };

  const handleCance = () => {
    resetForm();
    closeModal();
  };

  const changeJCategory = (val, obj) => {
    formModel['projectType'] = val;
  };
  const formatTp = (row) => {
    return row.tp == 1 ? '工具要求' : row.tp == 2 ? '记录要求' : '制度要求';
  };
  const formatComeFrom = (row) => {
    return row.comeFrom == 1 ? '自建' : row.tp == 2 ? '合规库' : '内控制度';
  };
  const formatExeRules = (row) => {
    return row.comeFrom == 1 ? '每发生' : row.tp == 2 ? '周期性' : '一次性';
  };

</script>

<style scoped>
  .ant-tag {
    cursor: pointer;
    margin-right: 4px;
    margin-bottom: 4px;
  }
</style>
