<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, 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 fileFlow = reactive({
        file: null,
      });
      const { createMessage } = useMessage();
      const title = ref('新增客户');
      const optionsName = ref([]);
      const schemas: FormSchema[] = [
        {
          field: 'num',
          component: 'Input',
          show: false,
          label: 'id',
          required: false,
        },
        {
          field: 'ryId',
          component: 'AutoComplete',
          label: '警员ID',
          required: true,
          componentProps: {
            filterOption: onFilterOption,
            onSearch: onSearch,
            onChange: (data) => {
              const item = optionsName.value && optionsName.value.find(ele => ele.ryId == data)
              setFieldsValue({ryNickName: item && item.ryNickName ? item.ryNickName : ''});
            },
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'ryNickName',
          component: 'Input',
          label: '姓名',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            disabled: true,
          },
        },
        {
          field: 'editAuth',
          component: 'RadioGroup',
          label: '编辑权限',
          defaultValue: 0,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: [
              { label: '无权编辑', value: 0 },
              { label: '不限时编辑', value: 1 },
              { label: '限时编辑', value: 2 },
            ],
            onChange: async (value) => {
              let params = await getFieldsValue();
              console.log('params', params);
              isEdit.value = value.target.value == 0 ? true : false;
              if (value.target.value == 1) {
                params.lookAuth = 1;
              }
              params.isEmpower = isEdit.value ? [] : params.isEmpower;
              setFieldsValue({...params, editAuth: value.target.value});
              updateSchema([
                {
                  field: 'editEndTime',
                  ifShow: value.target.value == 2,
                },
                {
                  field: 'isEmpower',
                  componentProps: {
                    options: setOption(),
                  },
                },
              ]);
            },
          },
        },
        {
          field: 'editEndTime',
          component: 'DatePicker',
          label: '编辑到期日期',
          ifShow: false,
          required: true,
          defaultValue: dayjs().add(1, 'month').format('YYYY-MM-DD HH:mm:ss'),
          componentProps: {
            disabled: false,
            'show-time': true,
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm:ss',
            disabledDate: (current) => {
              return current && current < dayjs().endOf('day');
            },
          },
        },
        {
          field: 'lookAuth',
          component: 'RadioGroup',
          label: '查看权限',
          defaultValue: 1,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: [
              { label: '不限时查看', value: 1 },
              { label: '限时查看', value: 2 },
            ],
            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:ss'),
          componentProps: {
            disabled: false,
            'show-time': true,
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            format: 'YYYY-MM-DD HH:mm:ss',
            disabledDate: (current) => {
              return current && current < dayjs().endOf('day');
            },
          },
        },
        {
          field: 'isAuthor',
          component: 'RadioGroup',
          label: '是否可授权他人',
          defaultValue: 0,
          colProps: {
            span: 24,
          },
          componentProps: {
            options: [
              { label: '不可授权', value: 0 },
              { label: '可授权他人', value: 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 });
        if (data) {
          title.value = data.id ? '编辑授权' : '新增授权';
          modelRef.value = data.id ? true : false;
          console.log('checkAuthOther', checkAuthOther);
          setFieldsValue({
            ...data,
            isEmpower:[data.canAuthLook?0:'',data.canEditLook?1:'']
          });
        } else {
          title.value = '新增客户';
        }
        updateSchema([
          { field: 'isEmpower', ifShow: data.isAuthor == 1 },
          { field: 'isAuthor', componentProps: { disabled: !checkAuthOther} },
          { field: 'editEndTime', ifShow: data.editAuth == 2 },
          { field: 'lookEndTime', ifShow: data.lookAuth == 2 },
        ]);
      });
      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 list = await getByRyId({ ryId: searchText });
        optionsName.value = list.map((ele) => {
            return { ...ele, value: ele.ryId };
          }) || [];
        // console.log('paramList', optionsList);
        // optionsName.value = optionsList || [];
        updateSchema({
          field: 'ryId',
          componentProps: {
            options: optionsName.value,
          },
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('params', params);
          await addAuth({
            ...params,
            canAuthLook: params.isEmpower &&  params.isEmpower.every(item => item == 0) ? 1 : 0,
            canEditLook: params.isEmpower &&  params.isEmpower.every(item => item == 1) ? 1 : 0,
          });
          closeModal();
          resetFields();
          emit('update');
          createMessage.success('操作成功');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function setOption() {
        return [
          { label: '查看权限', value: 0 },
          { label: '编辑权限', value: 1, disabled: isEdit.value },
        ];
      }
      function handleVisibleChange(_) {
        // console.log(v);
        // v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        schemas,
        registerForm,
        modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        title,
        t,
      };
    },
  });
</script>
