<template>
  <BasicModal v-bind="$attrs" @register="registerModal" @ok="handleSubmit" @cancel="handleCancel" :title="title" width="70%">
    <BasicForm @register="registerForm" style="height: 400px; margin-top: 10px" v-if="basicFormRef"/>
    <!-- 专家列表 -->
    <div v-if="!showFooter">
      <a-table :columns="sjcolumn" :data-source="dataList"> </a-table>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useSpeciality, sjcolumn } from '../GZjcyb.data';
  import { decryptData } from '/@/api/common/api';

  import { saveCq, searDkbm, getFaList, getCqXqZjList } from '../GZjcyb.api';

  const showFooter = ref(true);
  const dataList = ref<any>([]);
  const cqdkId = ref();
  const formSchemas: FormSchema[] = [
    {
      label: '地块编号',
      field: 'wrdkbm',
      required: true,
      component: 'ApiSelect',
      componentProps: ({ formModel, formActionType }) => {
        return {
          showSearch: true,
          api: searDkbm,
          params: { wrdkbm: '' },
          labelField: 'remark',
          valueField: 'wrdkbm',
          onChange: async (val) => {
            console.log('val', val);
            const { updateSchema } = formActionType;
            formModel.scjdbm = undefined;
            if (val) {
              formModel.scjdbm = await getDkbm(val);
              if (formModel.scjdbm != 'S2' && val != 'S3') {
                updateSchema({
                  field: 'pgtype',
                  component: 'ApiSelect',
                  componentProps: {
                    api: getFaList,
                    params: { scjdbm: formModel.scjdbm, wrdkid: wrdkid.value },
                    labelField: 'bt',
                    valueField: 'pgtype',
                  },
                });
              } else {
                formModel.pgtype = '';
              }
            }
          },
          disabled: !showFooter.value,
        };
      },
    },
    {
      label: '所处阶段',
      field: 'scjdbm',
      component: 'Select',
      colProps: { span: 6 },
      required: true,
      componentProps: {
        options: [
          { label: '地块调查', value: 'S2' },
          { label: '风险评估', value: 'S3' },
          { label: '风险管控', value: 'S4' },
          { label: '修复', value: 'S5' },
          { label: '风险管控及修复', value: 'S10' },
          { label: '风险管控及修复效果评估', value: 'S6' },
        ],
        disabled: true,
      },
    },
    {
      label: '方案/效果评估标题',
      field: 'pgtype',
      ifShow: ({ values }) => values.scjdbm != 'S2' && values.scjdbm != 'S3' && values.scjdbm,
      colProps: { span: 6 },
      required: true,
      component: 'ApiSelect',
      componentProps: ({}) => {
        return {
          disabled: !showFooter.value,
        };
      },
      // componentProps: ({ formModel }) => {
      //   if (!showFooter.value) getDkbm(formModel.wrdkbm);
      //   return {
      //     api: getFaList,
      //     params: { scjdbm: formModel.scjdbm, wrdkid: wrdkid.value },
      //     labelField: 'bt',
      //     valueField: 'pgtype',
      //   };
      // },
    },
    {
      label: '专业方向',
      field: 'cqzyfx',
      component: 'CheckboxGroup',
      colProps: { span: 24 },
      required: true,
      componentProps: {
        options: useSpeciality().data,
        disabled: !showFooter.value,
      },
    },
  ];

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);

  const basicFormRef = ref(false);

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    rowProps: { gutter: 24, justify: 'start', align: 'middle' },
    //全局col列占比(每列显示多少位)，和schemas中的colProps属性一致
    baseColProps: { span: 12 },
    //使用labelCol的样式参数来控制标题宽度
    labelCol: { style: { width: '150px' } },
    //row行的样式
    baseRowStyle: { width: '100%' },
    //表单布局属性，支持（vertical,horizontal），默认为horizontal
    layout: 'horizontal',
    schemas: formSchemas,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    showFooter.value = data?.showFooter;
    basicFormRef.value = true
    if (unref(isUpdate)) {
      //表单赋值
      data.record.pgtype = Number(data.record.pgtype);
      cqdkId.value = data.record.cqdkId;
      if (!showFooter.value) init();
      await setFieldsValue({
        ...data.record,
      });
    }
  });
  async function init() {
    const res = await getCqXqZjList({ cqdkId: cqdkId.value });
    dataList.value = res.records;
    decry();
  }
  // 解密
  function decry() {
    dataList.value.forEach((record) => {
      const rule = /^[0-9]+$/.test(record.lxdh);

      if (record.lxdh) {
        if (!rule) {
          const regex = /[*]/.test(record.lxdh);

          if (!regex) {
            decryptData({ str: record.lxdh }).then((res) => {
              record.lxdh = res.replace(res.substring(3, 7), '****');
            });
          }
        } else {
          record.lxdh = record.lxdh.replace(record.lxdh.substring(3, 7), '****');
        }
      }
    });
  }
  //设置标题
  const title = '抽取';

  // 获取地块编码
  const wrdkid = ref();
  async function getDkbm(val) {
    const res = await searDkbm({ wrdkbm: val });
    let dkmc = '';

    res.forEach((v) => {
      if (v.wrdkbm == val) {
        dkmc = v.scjdbm;
        wrdkid.value = v.wrdkid;
      }
    });

    return dkmc;
  }

  //关闭弹窗
  function handleCancel() {
    basicFormRef.value = false
    closeModal();
  }

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      values.wrdkid = wrdkid.value;
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveCq(values);
      //关闭弹窗
      handleCancel()
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped></style>
