<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="相机授权"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    minHeight="900px"
    @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, Addschemas, newAddschemas } from './data';
  import { InvoiceRegister } from '/@/api/order';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { ResultEnum } from '/@/enums/httpEnum';
  import { authorizeCameraaddOrUpdate } from '/@/api/authorizeModeling';
  import { copyTextToClipboard } from '/@/hooks/web/useCopyToClipboard';
  import dayjs from 'dayjs';
  import { otherInfoStore } from '/@/store/modules/other';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const otherInfo = otherInfoStore();
      const overviewInfo = computed(() => otherInfo.getOverviewInfo);
      // const overviewInfo = getOverviewInfo() || {}
      const fileFlow = reactive({
        file: null,
        id: '',
        key: '',
        type: 'down', //down-下载，equity-权益
      });
      const { createMessage, createConfirm, createSuccessModal } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          show: false,
          label: 'id',
        },
        {
          field: 'machineCode',
          component: 'InputTextArea',
          required: true,
          componentProps: {
            rows: 4,
          },
          label: '机器码',
          colProps: { span: 20 },
        },
        {
          field: 'modelAuthCode',
          component: 'Input',
          required: true,
          label: '算法授权码',
          colProps: { span: 20 },
          componentProps: {
            maxlength: 100,
          },
        },
        {
          field: 'snCodes',
          component: 'InputTextArea',
          required: true,
          label: '授权SN码',
          componentProps: {
            placeholder: '请输入授权SN码，多个sn码换行输入',
            rows: 4,
          },
          colProps: { span: 20 },
        },
      ];

      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: [...newAddschemas, ...Addschemas, ...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;
        fileFlow.key = data.authorizeKey;
        updateSchema([
          {
            field: 'useType',
            componentProps: {
              onChange: useTypeChange,
            },
          },
          {
            field: 'projectNum',
            ifShow: data.useType == '4',
          },
          {
            field: 'machineCode',
            componentProps: {
              disabled: data.id ? true : false,
            },
          },
          {
            field: 'snCodes',
            componentProps: {
              disabled: data.id ? true : false,
            },
          },
        ]);
        useTypeChange(data.useType || 0);
        setFieldsValue(data);
      }
      const useTypeChange = (value) => {
        updateSchema([
          { field: 'projectNum', ifShow: value == '4' },
          { field: 'companyName', ifShow: value != '3' },
          { field: 'businessDept', ifShow: value != '3' },
          { field: 'businessName', ifShow: value != '3' },
          { field: 'customerPayTime', ifShow: value != '3' },
          { field: 'customerName', ifShow: value != '3' },
          { field: 'customerType', ifShow: value != '3' },
          { field: 'endCustomer', ifShow: value != '3' },
        ]);
      };
      async function handleConfirm() {
        const { id } = await validate();
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '温馨提示'),
          content: () => h('span', `确定要${id ? '编辑' : '新增'}授权吗？`),
          onOk: async () => {
            handleSubmit();
          },
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('params', params)
          // let authorizeTime = params.authorizeTime.split('_');
          const apiData = {
            ...params,
            snCodes:params.snCodes && params.snCodes.split(' ').join(''),
            machineCode:params.machineCode && params.machineCode.replace(/\s*/g,""),
            userId: params.id,
            // authorizeTime: authorizeTime[0],
            // authorizeTimeUnit: authorizeTime[1],
          };
          console.log('apiData', apiData)
          let res = await authorizeCameraaddOrUpdate(apiData);
          let count = (res.snCodes && res.snCodes.split('\n')) || [];
          closeModal();
          resetFields();
          createSuccessModal({
            title: t('layout.setting.operatingTitle'),
            content: h('div', {}, [
              h('p', `授权Key：${res.authorizeKey || fileFlow.key}`),
              h('p', `授权相机数量：${count.length}`),
            ]),
            okText: '复制授权Key',
            onOk: async () => {
              // 双击复制
              copyTextToClipboard(res.authorizeKey || fileFlow.key);
              createMessage.success('复制成功');
            },
          });
          // 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>
