<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    :min-height="150"
    @ok="handleOk"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, h, unref } from 'vue';
  import { updateUcenterUser } from '/@/api/staff/list'; //roleLIstApi
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useUserStore } from '/@/store/modules/user';
  import { addOrUpdate } from '/@/api/jyUserPlatform/index';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['ok'],
    setup(_, context) {
      const modelRef = ref({});
      const userStore = useUserStore();
      const userinfo = computed(() => userStore.getUserInfo);
      const preventAutoFill = ref(true);
      const { companyId } = userinfo.value;
      console.log('companyId', companyId);
      const schemas: FormSchema[] = [
        {
          field: 'label1',
          component: 'Divider',
          label: '平台首页',
          colProps: {
            span: 24,
          },
        },
        {
          field: 'platformName',
          component: 'Input',
          label: '平台名称',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            maxLength: 100,
            required: true,
          },
        },
        {
          field: 'label2',
          component: 'Divider',
          label: '平台管理员',
          colProps: {
            span: 24,
          },
        },
        {
          field: 'name',
          component: 'Input',
          label: '姓名',
          colProps: {
            span: 20,
          },
          required: true,
          componentProps: {
            maxLength: 100,
          },
        },
        {
          field: 'idCard',
          component: 'Input',
          required: true,
          label: '身份证',
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                const regPos = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; // 非中文
                if (!value) {
                  return Promise.reject('请输入身份证');
                }
                if (!visitCertCodetip(value)) {
                  /* eslint-disable-next-line */
                  return Promise.reject('请输入正确的身份证号码');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 20,
          },
          componentProps: {
            maxLength: 18,
          },
        },
        // {
        //   field: 'phone',
        //   component: 'Input',
        //   required: true,
        //   label: '手机号码',
        //   colProps: {
        //     span: 20,
        //   },
        //   componentProps: {
        //     maxLength: 15,
        //   },
        // },
        {
          field: 'id',
          component: 'Input',
          label: 'id',
          show: false,
        },
        {
          field: 'status',
          component: 'Input',
          label: 'status',
          show: false,
        },
      ];
      const title = ref('创建平台');
      const { createMessage, createConfirm } = useMessage();
      const [registerForm, { setFieldsValue, validate, updateSchema, resetFields }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        // 方式1;
        title.value = data.status == 1 ? '启用平台' : data.id ? '修改平台' : '创建平台';
        // preventAutoFill.value = false
        setTimeout(() => {
          console.log('useModalInner', data);
          setFieldsValue({
            ...data,
            userName: '',
            password: '',
            roleId: data.roleId != 2 ? data.roleId : '',
          });
        }, 200);
      }
      function companyIdChange(companyId) {
        // resetFields(['permList'])
        updateSchema([
          {
            field: 'permList',
            componentProps: {
              params: {
                companyId: companyId,
              },
            },
          },
        ]);
        setFieldsValue({
          permList: [],
        });
      }
      async function handleOk() {
        let data = await validate();
        let res = await addOrUpdate({
          ...data,
          // userName: data.phone,
          phone: data.phone,
          nickName: data.nickName,
          roleId: data.roleId,
          id: data.id,
        });
        console.log('res', res);
        context && context.emit('ok', res);
        let url = window.location.origin + window.location.pathname + '?key=' + res.platformAddress;
        createConfirm({
          iconType: 'warning',
          okText: '复制',
          title: () =>
            h('span', data.status == 1 ? '平台启用成功' : data.id ? '修改成功' : '平台创建成功'),
          content: () =>
            h('div', {}, [
              h('div', null, `平台名称：${res.platformName}`),
              h('div', null, `平台地址：${url}`),
              h('div', null, `平台管理员：${res.name}，${res.idCard}`),
            ]),
          onOk: async () => {
            await handleCopy(url);
          },
        });
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }
      function handleCopy(url) {
        const { isSuccessRef } = useCopyToClipboard(url);
        isSuccessRef && createMessage.success('复制成功');
      }
      const visitCertCodetip = (code: any) => {
        //身份证号前两位代表区域
        const city = {
          11: '北京',
          12: '天津',
          13: '河北',
          14: '山西',
          15: '内蒙古',
          21: '辽宁',
          22: '吉林',
          23: '黑龙江 ',
          31: '上海',
          32: '江苏',
          33: '浙江',
          34: '安徽',
          35: '福建',
          36: '江西',
          37: '山东',
          41: '河南',
          42: '湖北 ',
          43: '湖南',
          44: '广东',
          45: '广西',
          46: '海南',
          50: '重庆',
          51: '四川',
          52: '贵州',
          53: '云南',
          54: '西藏 ',
          61: '陕西',
          62: '甘肃',
          63: '青海',
          64: '宁夏',
          65: '新疆',
          71: '台湾',
          81: '香港',
          82: '澳门',
          91: '国外 ',
        };
        //身份证格式正则表达式
        const idCardReg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i;
        //如果身份证不满足格式正则表达式
        if (!code || !idCardReg.test(code)) {
          return false;
        }

        //区域数组中不包含需验证的身份证前两位
        else if (!city[code.substr(0, 2)]) {
          return false;
        } else {
          //18位身份证需要验证最后一位校验位
          if (code.length == 18) {
            code = code.split('');
            //∑(ai×Wi)(mod 11)
            //加权因子
            const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
            //校验位
            const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
            let sum = 0;
            let ai = 0;
            let wi = 0;
            for (let i = 0; i < 17; i++) {
              ai = code[i];
              wi = factor[i];
              sum += ai * wi;
            }
            // var last = parity[sum % 11];
            if (parity[sum % 11] != code[17]) {
              return false;
            }
          }
        }
        return true;
      };
      return {
        register,
        title,
        preventAutoFill,
        schemas,
        registerForm,
        modelRef,
        handleOk,
        resetFields,
      };
    },
  });
</script>

.
