<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    @ok="handlestd"
  >
    <div class="BasicForms">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #selectUser="{ model, field }">
          <Select
            v-model:value="model[field]"
            show-search
            placeholder="请输入姓名/手机号码/身份证号码搜索"
            style="width: 350px; text-align: left"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            not-found-content="暂无数据"
            :options="options"
            @search="fetchUser"
            @change="handleChange"
          />
        </template>
      </BasicForm>
      <div v-if="addData.type == 2">
        <div class="from" v-if="active && active.name">
          <div class="form-item"> <div>姓名</div>{{ active.name }} </div>
          <div class="form-item"> <div>手机号码</div>{{ active.phone || '暂无手机号码' }} </div>
          <div class="form-item"> <div>身份证</div>{{ active.idCard || '暂无身份证' }} </div>
          <div class="form-item"> <div>平台</div>{{ active.platformName || '未分配' }} </div>
          <div class="form-item">
            <div>状态</div
            >{{
              active.status == null ? '未注册' : active.status == 1 ? '启用' : '禁用' || '未分配'
            }}
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, reactive } from 'vue';
  import { checkUserApi, saveAddApi, updateApi, getRoleListByParam } 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 { debounce } from 'lodash-es';
  import { Select } from 'ant-design-vue';
  import { jyPlatformlist, delplatformList } from '/@/api/jyUserPlatform/index'; //roleLIstApi
  import { addWaitUser, jyUserPlatformadd, queryByKey } from '/@/api/jyUserPlatform/index';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, Select },
    props: {
      userData: { type: Object },
    },
    emits: ['ok'],
    setup(_, context) {
      const modelRef = ref(undefined);
      const active = ref({});
      const addData = ref({
        type: 1,
        name: '',
        idCard: '',
      });
      const options = ref([]);
      const userStore = useUserStore();
      const userinfo = computed(() => userStore.getUserInfo);
      const preventAutoFill = ref(true);
      const { companyId } = userinfo.value;
      let lastFetchId = 0;
      const fetchUser = debounce((value) => {
        if (!value) {
          return;
        }
        lastFetchId += 1;
        const fetchId = lastFetchId;
        options.value = [];
        queryByKey({ queryKey: value }).then((res) => {
          console.log('queryByKey', res);
          setFieldsValue({idkey: null,});
          const data = res.map((user) => ({
            ...user,
            label: `${user.name}/${user.phone || '暂无手机号码'}/${user.idCard || '暂无身份证'}/${
              user.platformName || '未分配'
            }`,
            value: user.id,
          }));
          options.value = data;
        });
      }, 300);
      const schemas: FormSchema[] = [
        {
          field: 'type',
          component: 'RadioGroup',
          label: '添加用户类型',
          defaultValue: 0,
          colProps: {
            span: 24,
          },
          defaultValue: 1,
          componentProps: {
            options: [
              { label: '添加新用户', value: 1 },
              { label: '搜索平台用户', value: 2 },
            ],
            style: { textAlign: 'left' },
            onChange: async (e) => {
              let value = e.target.value;
              addData.value.type = value;
              updateSchema(
                [{
                  field: 'idkey',
                  ifShow: value == 2,
                },
                {
                  field: 'name',
                  ifShow: value == 1,
                },
                {
                  field: 'idCard',
                  ifShow: value == 1,
                },]
              );
              console.log('value', addData.value);
            },
          },
        },
        {
          field: 'idkey',
          component: 'Input',
          label: '账号查询',
          required: true,
          ifShow: false,
          colProps: {
            span: 20,
          },
          slot: 'selectUser',
          componentProps: {
            placeholder: '请输入姓名/手机号码/身份证号码搜索',
            onChange: fetchUser,
          },
        },
        {
          field: 'name',
          component: 'Input',
          label: '姓名',
          required: true,
          componentProps: {
            maxLength: 100,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'idCard',
          component: 'Input',
          label: '身份证',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            maxLength: 18,
          },
          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',
            },
          ],
        },
      ];
      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) {
        console.log('onDataReceive', data);
        setFieldsValue({
          type: 1,
          idkey: null,
          name: '',
          idCard: '',
        })
        options.value = [];
        updateSchema(
          [{
            field: 'idkey',
            ifShow: false,
          },
          {
            field: 'name',
            ifShow: true,
          },
          {
            field: 'idCard',
            ifShow: true,
          }]
        )
        modelRef.value = undefined;
        active.value = {};
        // 方式1;
        setTimeout(() => {
          preventAutoFill.value = false;
          // updateSchema(schemas);
        }, 500);
      }
      function companyIdChange(companyId) {
        // resetFields(['permList'])
        updateSchema([
          {
            field: 'permList',
            componentProps: {
              params: {
                companyId: companyId,
              },
            },
          },
        ]);
        setFieldsValue({
          permList: [],
        });
      }
      async function handlestd() {
        let param = await validate()
        console.log('param', param);
        if (param.type == 1) {
          let jgres = await queryByKey({ queryKey: param.idCard })
          console.log('jgres', jgres);
          let item = jgres && jgres[0] || {};
          if (item.platformId && userinfo.value.platformId == item.platformId) {
            createMessage.warning('该用户已存在此平台。');
            return;
          }
          if(item.platformId){
            createConfirm({
              title: '提示',
              content: '该用户已属其他平台，确定为其更换平台？',
              onOk: async () => {
                handleAddUser();
              },
            });
          }else {
            handleAddUser();
          }
          return;
        }
        if (active.value.platformId && userinfo.value.platformId == active.value.platformId) {
          createMessage.warning('该用户已存在此平台。');
          return;
        }
        if (active.value.platformId) {
          createConfirm({
            title: '提示',
            content: '该用户已属其他平台，确定为其更换平台？',
            onOk: async () => {
              handleOk();
            },
          });
        } else {
          handleOk();
        }
      }
      async function handleOk() {
        let param = await validate()
        let res = await jyUserPlatformadd({
          ...active.value,
        });
        context && context.emit('ok', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }
      async function handleAddUserqr() {
        let param = await validate()

       }
      async function handleAddUser() {
        let param = await validate()
        let res = await addWaitUser(param);
        context && context.emit('ok', res);
        createMessage.success(t('common.optSuccess'));
        closeModal();
        resetFields();
      }
      function handleChange(value, b) {
        active.value = b;
      }
      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,
        modelRef,
        handleOk,
        fetchUser,
        options,
        handleChange,
        active,
        handlestd,
        addData,
        registerForm,
        handleAddUserqr,
      };
    },
  });
</script>
<style lang="less" scoped>
  .ant-select-selection-item {
    text-align: left;
  }
  .BasicForms {
    margin: 0 auto;
    text-align: left;
  }
  .from {
    width: 350px;
    margin: 0 auto;
    .form-item {
      display: flex;
      margin-top: 10px;
      div {
        width: 60px;
        min-width: 60px;
        text-align: right;
        margin-right: 10px;
      }
    }
  }
</style>
