<template>
  <BasicModal
    v-bind="$attrs"
    @cancel="resetFields"
    @register="register"
    :title="title"
    @ok="handlestd"
  >
    <div class="BasicForms">
      <Select
        v-model:value="undefined"
        show-search
        placeholder="请输入姓名/手机号码/身份证号码搜索"
        style="width: 350px"
        :default-active-first-option="false"
        :show-arrow="false"
        :filter-option="false"
        not-found-content="暂无数据"
        :options="options"
        @search="fetchUser"
        @change="handleChange"
      />
      <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>
    </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 { platformallList, 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 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 = [];
        setFieldsValue({
          id: null,
        });
        queryByKey({ queryKey: value }).then((res) => {
          console.log('queryByKey', res);
          const data = res.map((user) => ({
            ...user,
            label: `${user.name}/${user.phone || '暂无手机号码'}/${user.idCard || ''}/${
              user.platformName || '未分配'
            }`,
            value: user.id,
          }));
          options.value = data;
          updateSchema([
            {
              field: 'id',
              ifShow: true,
              componentProps: {
                options: options.value,
              },
            },
          ]);
        });
      }, 300);
      const schemas: FormSchema[] = [
        {
          field: 'idkey',
          component: 'Input',
          label: '账号查询',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            placeholder: '请输入姓名/手机号码/身份证号码搜索',
            onChange: fetchUser,
          },
        },
        {
          field: 'id',
          component: 'Select',
          label: '查询结果',
          required: true,
          ifShow: false,
          colProps: {
            span: 20,
          },
          componentProps: {
            placeholder: '请选择平台',
            'label-in-value': true,
            options: options.value,
            showSearch: true,
            onSearch: fetchUser,
            numberToString: true,
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            // onChange: handleChange,
          },
        },
      ];
      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);
        modelRef.value = undefined;
        active.value = {};
        // 方式1;
        setTimeout(() => {
          preventAutoFill.value = false;
          updateSchema([
            {
              field: 'userName',
              componentProps: {
                readonly: false,
              },
            },
            {
              field: 'password',
              componentProps: {
                readonly: false,
              },
            },
          ]);
          // updateSchema(schemas);
        }, 500);
      }
      function companyIdChange(companyId) {
        // resetFields(['permList'])
        updateSchema([
          {
            field: 'permList',
            componentProps: {
              params: {
                companyId: companyId,
              },
            },
          },
        ]);
        setFieldsValue({
          permList: [],
        });
      }
      function handlestd(){
        if(active.value.platformId){
          createConfirm({
              title: '提示',
              content: '该用户已属其他平台，确定为其更换平台？',
              onOk: async () => {
                handleOk()
              },
            });
        }else{
          handleOk()
        }
      }
      async function handleOk() {
            let res = await jyUserPlatformadd({
              id: modelRef.value,
            });
            context && context.emit('ok', res);
            createMessage.success(t('common.optSuccess'));
            closeModal();
            resetFields();
      }
      function handleChange(value, b ) {
        active.value = b;
      }
      return {
        register,
        title,
        preventAutoFill,
        schemas,
        registerForm,
        modelRef,
        handleOk,
        resetFields,
        fetchUser,
        options,
        handleChange,
        active,
        handlestd,
      };
    },
  });
</script>
<style lang="less" scoped>
  .BasicForms {
    margin: 0 auto;
    text-align: center;
  }
  .from{
    width: 350px;
    margin: 0 auto;
    .form-item{
      display: flex;
      margin-top: 10px;
      div{
        width: 60px;
        text-align: right;
        margin-right: 10px;
      }
    }
  }
</style>
