<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.empower.addName')"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleConfirm"
  >
    <div class="pt-2px pr-3px zdysrk">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }"> {{ model[field] }}{{ fileFlow.type }} </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onMounted, reactive, computed, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { remarkschemas } from './data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { authorizeModelingaddOrUpdate } from '/@/api/authorizeModeling';
  import { incrementUseTypeList } from '/@/api/account';
  import { useUserStore } from '/@/store/modules/user';
  import { getSubAgent } from '/@/api/retailer';
  import { RoleEnum } from '/@/enums/roleEnum';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      // const otherInfo = otherInfoStore();
      const userStore = useUserStore();
      const agent = computed(() => userStore.getAgent);
      const canEditAuthorizeKey = computed(() => {
        const roleList = userStore.getRoleList || [];
        return !roleList.some((role) =>
          [RoleEnum.LEVEL2, RoleEnum.LEVEL2s, RoleEnum.DISTRIBUTOR].includes(role),
        );
      });
      // const overviewInfo = computed(() => otherInfo.getOverviewInfo);
      // const overviewInfo = getOverviewInfo() || {}
      const fileFlow = reactive({
        file: null,
        id: '',
        type: 'down', //down-下载，equity-权益
      });
      const { createMessage, createConfirm } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          show: false,
          label: 'id',
        },
        // {
        //   field: 'useType',
        //   component: 'ApiSelect',
        //   required: true,
        //   label: '使用类型',
        //   componentProps: {
        //     // filterOption: onFilterOption,
        //     // showSearch: true,
        //     api: incrementUseTypeList,
        //     labelField: 'name',
        //     valueField: 'id',
        //     immediate: true,
        //   },
        //   itemProps: {
        //     autoLink: false,
        //   },
        //   colProps: {
        //     span: 20,
        //   },
        // },
        {
          field: 'customerName',
          component: 'Input',
          label: t('routes.empower.customerName'),
          required: true,
          colProps: { span: 20 },
        },
        // {
        //   field: 'customerType',
        //   component: 'Select',
        //   label: '客户类别',
        //   required: true,
        //   colProps: { span: 20 },
        //   componentProps: {
        //     options: [
        //       {
        //         label: '直销',
        //         value: 0,
        //         key: '0',
        //       },
        //       {
        //         label: '经销',
        //         value: 1,
        //         key: '1',
        //       },
        //     ],
        //     onChange: (value) => {
        //       updateSchema({ field: 'agentId', ifShow: value == '1' });
        //     },
        //   },
        // },
        {
          field: 'endCustomer',
          component: 'Input',
          label: t('routes.empower.endCustomer'),
          required: true,
          colProps: { span: 20 },
        },
        {
          field: 'authorizeKey',
          component: 'Input',
          required: true,
          label: t('routes.empower.authorize'),
          colProps: { span: 20 },
        },
        {
          field: 'cameraSn',
          component: 'Input',
          label: t('routes.empower.cameraSn'),
          required: true,
          colProps: { span: 20 },
        },
        {
          field: 'authorizeStartTime',
          label: t('routes.empower.authorizeStartTime'),
          required: true,
          component: 'DatePicker',
          componentProps: {
            maxLength: 100,
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            // showTime: true,
          },
          colProps: { span: 20 },
        },
        {
          field: 'authorizeEndTime',
          label: t('routes.empower.authorizeEndTime'),
          component: 'DatePicker',
          required: true,
          componentProps: {
            maxLength: 100,
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD',
            // showTime: true,
          },
          colProps: { span: 20 },
        },
        {
          field: 'agentId',
          component: 'ApiSelect',
          label: t('routes.empower.agentId'),
          required: true,
          componentProps: {
            maxLength: 50,
            api: getSubAgent,
            // numberToString: true,
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            params: {
              type: 1,
            },
            style: 'max-width: 250px',
          },
          colProps: {
            xl: 20,
            xxl: 20,
          },
        },
        // {
        //   field: 'authorizeTime',
        //   component: 'Select',
        //   label: '授权期限',
        //   required: true,
        //   defaultValue: '10_1',
        //   componentProps: {
        //     options: [
        //       {
        //         label: '10天',
        //         value: '10_1',
        //         key: '10',
        //       },
        //       {
        //         label: '1个月',
        //         value: '1_2',
        //         key: '30',
        //       },
        //       {
        //         label: '3个月',
        //         value: '3_2',
        //         key: '90',
        //       },
        //       {
        //         label: '1年',
        //         value: '1_3',
        //         key: '365',
        //       },
        //       {
        //         label: '2年',
        //         value: '2_3',
        //         key: '730',
        //       },
        //       {
        //         label: '3年',
        //         value: '3_3',
        //         key: '1095',
        //       },
        //       {
        //         label: '5年',
        //         value: '3_5',
        //         key: '1825',
        //       },
        //     ],
        //   },
        //   colProps: {
        //     span: 18,
        //   },
        // },
      ];

      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 200,
        schemas: [...schemas, ...remarkschemas],
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      async function onDataReceive(data) {
        resetFields();
        fileFlow.id = data.id;
        updateSchema([
          {
            field: 'authorizeKey',
            componentProps: {
              disabled: !!data.id && !canEditAuthorizeKey.value,
            },
          },
          {
            field: 'useType',
            componentProps: {
              // onChange: (value) => {
              //   updateSchema({ field: 'projectNum', ifShow: value == '4' });
              // },
            },
          },
          // {
          //   field: 'projectNum',
          //   ifShow: data.useType == '4',
          // },
        ]);
        data.authorizeTime = [data.authorizeStartTime, data.authorizeEndTime];
        setFieldsValue(data);
      }
      async function handleConfirm() {
        const { id } = await validate();
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.reminder')),
          content: () =>
            h('span', id ? t('routes.empower.editTips') : t('routes.empower.addtTips')),
          onOk: async () => {
            handleSubmit();
          },
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log(params);
          // let authorizeTime = params.authorizeTime;
          const apiData = {
            // agentId: agent.value.id,
            ...params,
            // authorizeStartTime: authorizeTime[0],
            // authorizeEndTime: authorizeTime[1],
          };
          await authorizeModelingaddOrUpdate(apiData);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        handleConfirm,
        t,
      };
    },
  });
</script>
<style lang="less">
  .zdysrk {
    .ant-calendar-picker {
      min-width: 285px;
    }
  }
</style>
