<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      @register="register"
      title="查询权限"
      okText="查询"
      @cancel="resetFields"
      min-height="220px"
      @ok="handleSubmit"
    >
      <div class="pt-2px pr-3px">
        <div class="text" style="padding: 0 20px 20px 20px"
          >案件不支持新增权限。您可以搜索指定人员名称查询是否用于有权限，若无可联系场景管理员开通。</div
        >
        <BasicForm @register="registerForm">
          <template #text="{ model, field }">
            {{ model[field] }}
          </template>
        </BasicForm>
        <div class="text" style="padding: 0 20px"
          >只要用户拥有至少一个场景的编辑权限，则拥有案件的编辑权限</div
        >
        <div class="text" style="padding: 0 20px"
          >只要用户拥有至少一个场景的查看权限，则拥有案件的查看权限。</div
        >
      </div>
    </BasicModal>
    <resultListModal @register="registerModal" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, onMounted, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { getinnerByRyId, userShareAdd } from '/@/api/operate';
  import resultListModal from './resultListModal.vue';
  import { useModal } from '/@/components/Modal';
  import { getNotAuthScene } from '/@/api/operate/case';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, resultListModal },
    props: {
      userData: { type: Object },
    },
    emits: ['ok'],
    setup(_, { emit }) {
      const modelRef = ref(false);
      const fileFlow = reactive({
        file: null,
      });
      const { createMessage } = useMessage();
      const [registerModal, { openModal }] = useModal();
      const optionsName = ref([]);
      const schemas: FormSchema[] = [
        {
          field: 'caseId',
          component: 'Input',
          show: false,
          label: 'caseId',
          defaultValue: '111',
          required: false,
        },
        {
          field: 'ryId',
          component: 'Input',
          show: false,
          label: 'id',
        },
        {
          field: 'ryNo',
          component: 'Input',
          label: '人员编号',
          required: true,
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                let myData = await getFieldsValue();
                if (!value) {
                  return Promise.reject('请输入人员编号');
                }
                let res = await getinnerByRyId({ ryNo: value });
                console.log('value', value, res);
                if (res && !res.data) {
                  return Promise.reject('人员编号不存在');
                }
                Promise.resolve();
                let ryNickName = res && res.data && res.data.ryNickName;
                if (myData.ryNickName != ryNickName || !myData.ryNickName) {
                  setFieldsValue({
                    ryNickName: res && res.data ? res.data.ryNickName : '',
                    id: res && res.data ? res.data.id : '',
                    ryId: res && res.data ? res.data.ryId : '',
                  });
                }
              },
              trigger: 'blur',
            },
          ],
          colProps: {
            span: 20,
          },
        },
        // {
        //   field: 'ryNo',
        //   component: 'AutoComplete',
        //   label: '人员编号',
        //   required: true,
        //   componentProps: {
        //     filterOption: onFilterOption,
        //     onSearch: onSearch,
        //     onChange: (data) => {
        //       setTimeout(() => {
        //         const item = optionsName.value && optionsName.value.find((ele) => ele.ryNo == data);
        //         setFieldsValue({
        //           ryNickName: item && item.ryNickName ? item.ryNickName : '',
        //           id: item && item.id ? item.id : '',
        //         });
        //       }, 100);
        //     },
        //   },
        //   colProps: {
        //     span: 20,
        //   },
        // },
        {
          field: 'ryNickName',
          component: 'Input',
          label: '姓名',
          // rules: [
          //   {
          //     required: true,
          //     // @ts-ignore
          //     validator: async (rule, value) => {
          //       if (!value) {
          //         return Promise.reject('请输入正确的人员编号');
          //       }
          //       return Promise.resolve();
          //     },
          //     trigger: 'change',
          //   },
          // ],
          colProps: {
            span: 20,
          },
          componentProps: {
            disabled: true,
          },
        },
      ];
      const [
        registerForm,
        { validate, resetFields, setFieldsValue, getFieldsValue, updateSchema },
      ] = useForm({
        labelWidth: 110,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner(async (data) => {
        console.log('useModalInner', data);
        setFieldsValue({caseId: data.caseId})
      });
      function onFilterOption(inputText: string, option) {
        console.log('option', inputText, option.value);
        if (option.value) {
          return option.value.indexOf(inputText) >= 0;
        }
        // return option.value.indexOf(inputText.toUpperCase()) >= 0;
      }
      async function onSearch(searchText) {
        const res = await getinnerByRyId({ ryNo: searchText });
        console.log('res', res.data);
        if (!res.data) return;
        optionsName.value = res.data || {};
        updateSchema({
          field: 'ryNo',
          componentProps: {
            options: [optionsName.value],
          },
        });
      }
      const handleSubmit = async () => {
        const params = await validate();
        try {
          let data = await getNotAuthScene({ ...params, authType: 0, sourceType: 'scene' },true) || [];
          console.log('not passing', data);
          let isChecke = data.some((item) => item.list && item.list.length);
          console.log('not passing', data, isChecke);
          if ( !isChecke ) {
            closeModal();
            resetFields();
            emit('ok');
            createMessage.success('此用户拥有所有场景或者多元融合的查看、编辑权限');
          } else {
            openModal(true, {...params, name: params.ryNickName});
          }
        } catch (error) {
          console.log('not passing', error);
        }
      };

      return {
        register,
        schemas,
        registerForm,
        modelRef,
        fileFlow,
        handleSubmit,
        addListFunc,
        registerModal,
        resetFields,
        t,
      };
    },
  });
</script>
