<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.retailer.device.title')"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
    :min-height="150"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <a v-if="!model.id" @click="getTemplate" style="padding: 20px 0 0 80px">{{t('routes.retailer.device.dowmTips')}}</a>
    </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 { cameraIn } from '/@/api/device';
  import { getSubAgent, downTemplate, giveCamera, giveCameraBatch } from '/@/api/retailer';
  import { companyUploadExcel } from '/@/api/customer';
  import { downloadByData } from '/@/utils/file/download'
  import { uploadApi } from '/@/api/product/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['reload'],
    setup(_, { emit }) {
      const modelRef = ref({});
      const fileFlow = reactive({
        file: null,
        title: '设备分发',
      });
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },
        {
          field: 'subAgentId',
          component: 'ApiSelect',
          label: t('routes.retailer.name'),
          required: true,
          colProps: {
            span: 18,
          },
          componentProps: {
            maxLength: 50,
            style: 'width: 240px',
            api: getSubAgent,
            // numberToString: true,
            labelField: 'name',
            valueField: 'id',
            immediate: true,
          },
          colProps: {
            xl: 18,
            xxl: 18,
          },
        },
        {
          field: 'file',
          component: 'Upload',
          label: t('routes.retailer.device.list'),
          required: true,
          rules: [{ required: true, message: t('common.uploadMessge') }],
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            maxSize: 1000,
            fileFlow:true,
            accept: ['xlsx', 'xls'],
            afterFetch: function (data) {
              // Reflect.set(data, 'url', data.file);
              fileFlow.file = data.file
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        // console.log(data);
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        modelRef.value = data;
        resetFields();
        updateSchema({
          field: 'file',
          show: data.id ? false : true,
        })
        setFieldsValue({
          id: data.id,
          subAgentId: data.subAgentId,
        });
      }
      async function getTemplate() {
        try {
          const res:BlobPart = await downTemplate({ type: 0, filename:  t('routes.retailer.device.filename')+'.xlsx' });
          console.log('downTemplate',res)
          downloadByData(res.data)
        } catch (error) {
          console.log('not passing', error);
        }
      }

      function handleVisibleChange() {}

      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('params', params);
          if (params.id) {
            await giveCamera(params);
            createMessage.success(t('common.optSuccess'));
          } else {
            const apiData = {
              file: fileFlow.file,
              data: {
                subAgentId: params.subAgentId,
              }
            };
            let num = await giveCameraBatch(apiData);
            createMessage.success(t('routes.retailer.exportText', { value: num }));
          }
          closeModal();
          resetFields();
          emit('reload');
        } catch (error) {
          console.log('not passing', error);
        }
      };
      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        getTemplate,
        t,
      };
    },
  });
</script>
