<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
    :height="800"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, ref, 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 { companyList } from '/@/api/customer';
// import { sceneMove } from '/@/api/operate';
import { downTemplate } from '/@/api/customer';
import { cameraParam, cameraUpdate, cameraOut } from '/@/api/device';
import { CameraList } from '/@/api/order';
import { useI18n } from '/@/hooks/web/useI18n';
const { t } = useI18n();
interface Option {
  value: string;
}

export default defineComponent({
  components: { BasicModal, BasicForm },
  props: {
    userData: { type: Object },
  },
  emits: ['reload'],
  setup(_, { emit }) {
    const modelRef = ref({
      isUpdate:false,
    });
    const title = ref('设备出库');
    const optionsOrderSn = ref<Option[]>([]);
    const optionsName = ref<Option[]>([]);
    const fileFlow = reactive({
      file: null,
    });
    const { createMessage } = useMessage();
    const schemas: FormSchema[] = [
      {
        field: 'id',
        component: 'Input',
        label: 'id',
        show: false,
      },
      {
        field: 'outType',
        component: 'Select',
        label: '出库类型',
        colProps: {
          span: 18,
        },
        componentProps: {
          options: [
            {
              label: t('routes.product.outType.0'),
              value: '0',
              key: '0',
            },
            {
              label: t('routes.product.outType.1'),
              value: '1',
              key: '1',
            },
            {
              label: t('routes.product.outType.2'),
              value: 2,
              key: '2',
            },
            {
              label: t('routes.product.outType.3'),
              value: '3',
              key: '3',
            },
          ],
        },
      },
      {
        field: 'companyName',
        component: 'AutoComplete',
        label: '客户名称',
        colProps: {
          span: 18,
        },
        componentProps: {
          filterOption: onFilterOption,
          onSearch: async (searchText: string) => {
            const {list} = await companyList({ companyName: searchText });
            let optionsList = list.map((ele) => { return { ...ele,value: ele.companyName }; }) || []
            console.log('paramList',optionsList)
            optionsName.value = optionsList || [];
            updateSchema({
              field: 'companyName',
              componentProps:{
                options: optionsName.value,
              },
            })
          },
          onChange: (data) => {
            console.log('data', data);
          },
        },
      },
      {
        field: 'orderSn',
        component: 'AutoComplete',
        label: '订单号',
        colProps: {
          span: 18,
        },
        componentProps: {
          options: optionsOrderSn.value,
          filterOption: onFilterOption,
          onSearch: async (searchText: string) => {
            const { list } = await CameraList({ orderSn: searchText });
            optionsOrderSn.value = !searchText ? [] : list.map((ele) => { return { value: ele.orderSn }; });
            updateSchema({
              field: 'orderSn',
              componentProps:{
                options: optionsOrderSn.value,
              },
            })
          },
          onChange: (data) => {
            console.log('data', data);
          },
        },
      },
    ];
    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;
      title.value = data.isUpdate?'编辑':'设备出库'
      console.log('onDataReceive', data);
      const { outType } = data;
      let obj = t('routes.product.outType')
      resetFields();
      setFieldsValue({
        type: obj[outType],
        ...data,
      });
    }

    const handleSubmit = async () => {
      const apiUrl = modelRef.value.isUpdate?cameraUpdate:cameraOut
      try {
        const params = await validate();
        console.log('params', params);
        const res = await apiUrl(params);
        console.log('res', res);
        closeModal();
        resetFields();
        createMessage.success(t('common.optSuccess'));
        emit('reload');
      } catch (error) {
        console.log('not passing', error);
      }
    };
    function onFilterOption(inputText: string, option: Option) {
      return option.value.toUpperCase().indexOf(inputText.toUpperCase()) >= 0;
    }

    function handleVisibleChange(v) {
      // console.log(v);
      // v && props.userData && nextTick(() => onDataReceive(props.userData));
    }

    async function getTemplate() {
      try {
        const res = await downTemplate({ type: 2 });
        console.log('res', res);
      } catch (error) {
        console.log('not passing', error);
      }
    }
    return {
      register,
      schemas,
      registerForm,
      model: modelRef,
      title,
      fileFlow,
      handleVisibleChange,
      onFilterOption,
      handleSubmit,
      addListFunc,
      resetFields,
      t,
      getTemplate,
    };
  },
});
</script>
