<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
    :min-height="400"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, 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 { companyAdd, companyUpdate } from '/@/api/customer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { getByRyId, getinnerByRyId, addAuth, checkAuthOtherApi } from '/@/api/operate';
  import { useModalInner } from '/@/components/Modal';
  import dayjs from 'dayjs';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref(false);
      const isEdit = ref(true);
      const editTime = ref('');
      const fileFlow = reactive({
        file: null,
        qxType: null,
      });
      const { createMessage } = useMessage();
      const title = ref('新增客户');
      const optionsName = ref([]);
      const range = (start, end) => {
        const result = [];
        for (let i = start; i < end; i++) {
          result.push(i);
        }
        return result;
      };
      const disabledLookTime = (date) => {
        let startTime = editTime.value || '';
        const hour = dayjs(startTime).hour(); // 获取当前的小时
        const min = dayjs(startTime).minute(); // 获取当前的分钟
        const second = dayjs(startTime).second(); // 获取当前秒
        if (dayjs(date).format('YYYY-MM-DD') === dayjs(startTime).format('YYYY-MM-DD')) {
          if (dayjs(date).format('HH') === dayjs(startTime).format('HH')) {
            if (dayjs(date).format('mm') === dayjs(startTime).format('mm')) {
              return {
                disabledHours: () => range(0, 24).splice(0, hour),
                disabledMinutes: () => range(0, 60).splice(0, min),
                disabledSeconds: () => range(0, 60).splice(0, second),
              };
            } else {
              return {
                disabledHours: () => range(0, 24).splice(0, hour),
                disabledMinutes: () => range(0, 60).splice(0, min),
              };
            }
          } else {
            return {
              disabledHours: () => range(0, 24).splice(0, hour),
            };
          }
        }
      };
      const disabledTime = (date) => {
        const hour = dayjs().hour(); // 获取当前的小时
        const min = dayjs().minute(); // 获取当前的分钟
        const second = dayjs().second(); // 获取当前秒
        if (dayjs(date).format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')) {
          if (dayjs(date).format('HH') === dayjs().format('HH')) {
            if (dayjs(date).format('mm') === dayjs().format('mm')) {
              return {
                disabledHours: () => range(0, 24).splice(0, hour),
                disabledMinutes: () => range(0, 60).splice(0, min),
                disabledSeconds: () => range(0, 60).splice(0, second),
              };
            } else {
              return {
                disabledHours: () => range(0, 24).splice(0, hour),
                disabledMinutes: () => range(0, 60).splice(0, min),
              };
            }
          } else {
            return {
              disabledHours: () => range(0, 24).splice(0, hour),
            };
          }
        }
      };
      const schemas: FormSchema[] = [
        {
          field: 'num',
          component: 'Input',
          show: false,
          label: 'id',
          required: false,
        },
        {
          field: 'caseId',
          component: 'Input',
          show: false,
          label: 'caseId',
          required: false,
        },
        {
          field: 'ryNo',
          component: 'AutoComplete',
          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;
                console.log('id', myData.id != ryNickName || !myData.id);
                if(myData.ryNickName != ryNickName || !myData.ryNickName){
                  setFieldsValue({
                    ryNickName: res && res.data ? res.data.ryNickName : '',
                    id: res && res.data ? res.data.id : '',
                  });
                }
              },
              trigger: 'blur',
            },
          ],
          // 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,
          },
        },
        {
          field: 'editAuth',
          component: 'RadioGroup',
          label: '编辑权限',
          defaultValue: 0,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: getOptionList('editAuth', 1),
            onChange: async (value) => {
              let params = await getFieldsValue();
              isEdit.value = value.target.value == 0 ? true : false;
              if (value.target.value == 1) {
                params.lookAuth = 1;
              }
              params.isEmpower = isEdit.value ? [0] : params.isEmpower;
              setFieldsValue({ ...params, editAuth: value.target.value });
              updateSchema([
                {
                  field: 'editEndTime',
                  ifShow: value.target.value == 2,
                },
                {
                  field: 'lookAuth',
                  componentProps: {
                    disabled: value.target.value == 1,
                  },
                },
                {
                  field: 'lookEndTime',
                  ifShow: value.target.value != 1 && params.lookAuth == 2,
                },
                {
                  field: 'isEmpower',
                  componentProps: {
                    options: (isEdit.value ||!fileFlow.qxType)?[
                      { label: '查看权限', value: 0, disabled: true },
                      { label: '编辑权限', value: 1, disabled: true },
                    ]:setOption(),
                  },
                },
              ]);
            },
          },
        },
        {
          field: 'editEndTime',
          component: 'DatePicker',
          label: '编辑到期日期',
          ifShow: false,
          required: true,
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                console.log('value', value, dayjs().isBefore(dayjs(value)));
                if (!value) {
                  return Promise.reject('请选中日期');
                }
                if (!dayjs().isBefore(dayjs(value))) {
                  /* eslint-disable-next-line */
                return Promise.reject('到期时间已过期');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: {
            disabled: false,
            showTime: {
              valueFormat: 'HH:mm',
              format: 'HH:mm',
            },
            showToday: false,
            valueFormat: 'YYYY-MM-DD HH:mm',
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm',
            disabledDate: (current) => {
              return current && current < dayjs().startOf('day');
            },
            disabledTime: disabledTime,
            onChange: (value) => {
              editTime.value = value;
              setFieldsValue({ lookEndTime: '' });
              updateSchema({
                field: 'lookEndTime',
                componentProps: {
                  disabledTime: disabledLookTime,
                  disabledDate: (current) => {
                    return current && (current < dayjs().startOf('day') || current < dayjs(value));
                  },
                },
              });
            },
          },
        },
        {
          field: 'lookAuth',
          component: 'RadioGroup',
          label: '查看权限',
          defaultValue: 1,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: getOptionList('lookAuth', 1),
            onChange: (value) => {
              updateSchema({
                field: 'lookEndTime',
                ifShow: value.target.value == 2,
              });
            },
          },
        },
        {
          field: 'lookEndTime',
          component: 'DatePicker',
          label: '查看到期日期',
          ifShow: false,
          required: true,
          // defaultValue: dayjs().add(1, 'month').format('YYYY-MM-DD HH:mm'),
          componentProps: {
            disabled: false,
            type: 'datetime',
            showTime: {
              valueFormat: 'HH:mm',
              format: 'HH:mm',
            },
            showToday: false,
            valueFormat: 'YYYY-MM-DD HH:mm',
            format: 'YYYY-MM-DD HH:mm',
            disabledTime: disabledLookTime,
            disabledDate: (current) => {
              console.log('current', current);
              return current && current < dayjs();
            },
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject('请选中日期');
                }
                if (!dayjs().isBefore(dayjs(value))) {
                  /* eslint-disable-next-line */
                return Promise.reject('到期时间已过期');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
        },
        {
          field: 'isAuthor',
          component: 'RadioGroup',
          label: '是否可授权他人',
          defaultValue: 0,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: getOptionList('isAuthor', 1),
            onChange: (value) => {
              updateSchema({
                field: 'isEmpower',
                ifShow: value.target.value == 1,
              });
            },
          },
        },
        {
          field: 'isEmpower',
          component: 'CheckboxGroup',
          label: '授权他人权限',
          ifShow: false,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: setOption(),
          },
        },
      ];
      const [
        registerForm,
        { validate, getFieldsValue, resetFields, setFieldsValue, updateSchema },
      ] = useForm({
        labelWidth: 110,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner(async (data) => {
        onSearch('');
        let checkAuthOther = await checkAuthOtherApi({ num: data.num, caseId: data.caseId, authType: data.qxType ? 0 : 1, });
        let setData = {
          ...checkAuthOther,
          ...data,
          isEmpower: data.qxType?[0]:[0,1], //[data.canAuthLook ? 0 : '', data.canEditLook ? 1 : ''],
        };
        console.log(setData, 'setData', data.qxType)
        let lookEndTime = checkAuthOther.lookEndTime
          ? checkAuthOther.lookEndTime
          : dayjs().format('YYYY-MM-DD HH:mm:ss');
        let mylookEndTime =
          checkAuthOther.editEndTime > lookEndTime ? checkAuthOther.editEndTime : lookEndTime;
        editTime.value = checkAuthOther.editEndTime;
        isEdit.value = data.qxType ? true : false;
        fileFlow.qxType = data.qxType;
        if (data) {
          title.value = data.id ? '编辑授权' : '新增授权';
          modelRef.value = data.id ? true : false;
          setFieldsValue({
            ...setData,
            editAuth: data.qxType ? 0 : setData.editAuth ? setData.editAuth : 1,
            isAuthor: 0,
          });
        } else {
          title.value = '新增客户';
        }
        updateSchema([
          {
            field: 'isEmpower',
            ifShow: false,
            componentProps: {
              options: !isEdit.value?[
                { label: '查看权限', value: 0, disabled: true },
                { label: '编辑权限', value: 1, disabled: true },
              ]:setOption(),
            },
          },
          {
            field: 'isAuthor',
            componentProps: {
              disabled: setData.isAuthor == 0,
            },
          },
          {
            field: 'editAuth',
            defaultValue: 1,
            componentProps: {
              options: fileFlow.qxType 
                ? getOptionList('editAuth', setData.editAuth)
                : [
                    { label: '不限时编辑', value: 1 ,disabled: setData.editAuth == 2},
                    { label: '限时编辑', value: 2 },
                  ],
            },
          },
          {
            field: 'lookAuth',
            ifShow: setData.qxType,
            componentProps: {
              disabled: false,
              options: getOptionList('lookAuth', setData.lookAuth),
            },
          },
          {
            field: 'editEndTime',
            ifShow: setData.editAuth == 2,
            componentProps: {
              disabled: checkAuthOther.editEndTime,
              disabledDate: (current) => {
                if (checkAuthOther.editEndTime) {
                  return (
                    current &&
                    (current < dayjs().startOf('day') ||
                      current > dayjs(checkAuthOther.editEndTime))
                  );
                } else {
                  return current && current < dayjs().startOf('day');
                }
              },
            },
          },
          {
            field: 'lookEndTime',
            ifShow: setData.lookAuth == 2 && setData.qxType,
            componentProps: {
              disabled: checkAuthOther.lookEndTime,
              disabledDate: (current) => {
                if (mylookEndTime) {
                  return current && current < dayjs(mylookEndTime);
                } else {
                  return current && current < dayjs().startOf('day');
                }
              },
            },
          },
        ]);
      });
      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;
      }
      function throttle(func, delay) {
        var timer = null;
        return function () {
          var context = this;
          var args = arguments;
          if (!timer) {
            timer = setTimeout(function () {
              func.apply(context, args);
              timer = null;
            }, delay);
          }
        };
      }
      async function onSearch(searchText) {
        if (searchText.length < 7) return;
        const list = await getByRyId({ ryNo: searchText });
        optionsName.value =
          list.map((ele) => {
            return { ...ele, value: ele.ryNo };
          }) || [];
        // console.log('paramList', optionsList);
        // optionsName.value = optionsList || [];
        updateSchema({
          field: 'ryNo',
          componentProps: {
            options: optionsName.value,
          },
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('params', params);
          let canEditLook = params.isEmpower && params.isEmpower.some((item) => item == 1) ? 1 : 0;
          await addAuth({
            ...params,
            lookAuth: fileFlow.qxType ? params.lookAuth : 1,
            lookEndTime:
              params.lookAuth == 2 ? dayjs(params.lookEndTime).format('YYYY-MM-DD HH:mm:ss') : '',
            editEndTime:
              params.editAuth == 2 ? dayjs(params.editEndTime).format('YYYY-MM-DD HH:mm:ss') : '',
            canEditLook,
            canAuthLook:
              canEditLook || (params.isEmpower && params.isEmpower.some((item) => item == 0))
                ? 1
                : 0,
            authType: fileFlow.qxType ? 0 : 1,
          });
          closeModal();
          resetFields();
          emit('update');
          createMessage.success('操作成功');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function setOption() {
        return [
          { label: '查看权限', value: 0, disabled: true },
          { label: '编辑权限', value: 1, disabled: isEdit.value },
        ];
      }
      function handleVisibleChange(_) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      function getOptionList(type: string, auth: any) {
        let optionList = {
          editAuth: [
            { label: '无权编辑', value: 0 },
            { label: '不限时编辑', value: 1 },
            { label: '限时编辑', value: 2 },
          ],
          lookAuth: [
            { label: '不限时查看', value: 1 },
            { label: '限时查看', value: 2 },
          ],
          isAuthor: [
            { label: '不可授权', value: 0 },
            { label: '可授权他人', value: 1 },
          ],
        };
        let option = optionList[type];
        console.log((!auth && auth != 0) , auth == 1, 'optionListauth', type);
        if ((!auth && auth != 0) || auth == 1) {
          return option;
        } else if (auth == 2) {
          return option.map((ele) => {
            return {
              ...ele,
              disabled: ele.value == 1,
            };
          });
        } else {
          return option.map((ele) => {
            if (type == 'lookAuth' && ele.value == 2) {
              return {
                ...ele,
                disabled: false,
              };
            } else {
              return {
                ...ele,
                disabled: ele.value != 0,
              };
            }
          });
        }
      }
      return {
        register,
        schemas,
        registerForm,
        modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        getOptionList,
        addListFunc,
        resetFields,
        title,
        t,
        disabledTime,
        throttle,
      };
    },
  });
</script>
