<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="fileFlow.title"
    width="700px"
    @cancel="resetFields"
    :confirmLoading="loading"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #add>
          <Button @click="add">添加备件</Button>
        </template>
        <template #del="{ field }">
          <Button @click="del(field)">删除</Button>
        </template>
      </BasicForm>
      <BasicTable @register="registerTable"></BasicTable>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { defineComponent, h, onMounted, reactive, ref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
import { useMessage } from '/@/hooks/web/useMessage';
import {
  partAllList,
  faultAllList,
  checkRegister,
  partInfo,
  partInfo,
  checkRegisterInfo,
  repairOver,
} from '/@/api/spares';
import { useI18n } from '/@/hooks/web/useI18n';
import { uploadApi } from '/@/api/product/index';
import { BasicTable, useTable } from '/@/components/Table';
const { t } = useI18n();
export default defineComponent({
  components: { BasicModal, BasicForm, BasicTable },
  props: {
    userData: { type: Object },
  },
  emits: ['update', 'register'],
  setup(props, { emit }) {
    const n = ref(1);
    const repairId = ref('');
    const fileFlow = reactive({
      file: null,
      title: '完成维修',
      repairId: null,
      cameraType: 0,
      type: 2, //2-普通发票，3-专用发票
      faultList: [],
    });
    const loading = ref(false);
    const { createMessage, createConfirm } = useMessage();
    let schemas: FormSchema[] = [
      {
        field: 'repairId',
        component: 'Input',
        label: '维修单号',
        slot: 'text',
        colProps: {
          span: 24,
        },
      },
      {
        field: 'deviceInfo',
        component: 'Input',
        label: '设备信息',
        slot: 'text',
        colProps: {
          span: 18,
        },
      },
      // {
      //   field: 'faultIds',
      //   component: 'CheckboxGroup',
      //   label: '维修登记',
      //   required: true,
      //   componentProps: {
      //     options: fileFlow.faultList,
      //     maxLength: 50,
      //   },
      //   colProps: {
      //     span: 18,
      //   },
      // },
      {
        field: 'remark',
        component: 'InputTextArea',
        label: '维修记录',
        required: true,
        componentProps: {
          maxLength: 500,
          rows: 3,
          placeholder: '请填写维修记录',
        },
        colProps: {
          span: 18,
        },
      },
    ];
    const columns = [
      {
        title: '备件编号',
        dataIndex: 'partNum',
        width: 50,
      },
      {
        title: '备件名称',
        dataIndex: 'partName',
        width: 150,
      },
      {
        title: '数量',
        dataIndex: 'partCount',
        width: 50,
      },
    ];
    const [registerTable, { reload }] = useTable({
      api:partInfo,
      columns: columns,
      searchInfo: { repairId: repairId, type:'2' },
      showTableSetting: true,
      showIndexColumn: false,
      afterFetch: (T) => {
        console.log(T);
        return T;
      },
      immediate: false,
      pagination: false,
      fetchSetting: {
        listField: 'partList',
      },
      canResize: false,
    });
    const [
      registerForm,
      {
        validate,
        resetFields,
        setFieldsValue,
        removeSchemaByFiled,
        appendSchemaByField,
        updateSchema,
      },
    ] = useForm({
      labelWidth: 100,
      schemas: schemas,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 24,
      },
    });
    onMounted(() => {});
    // getFaultList();
    let addListFunc = () => {};
    const [register, { closeModal }] = useModalInner((data) => {
      repairId.value = data?.repairId;
      data && onDataReceive(data);
    });
    async function getFaultList() {
      const res = await faultAllList({});
      fileFlow.faultList = res.map((item) => {
        return {
          ...item,
          label: item.faultMsg,
          value: item.faultId,
        };
      });
    }

    function onDataReceive(data) {
      console.log('openOutModal', repairId.value);
      resetFields();
      if (repairId.value) {
        reload();
      }
      // updateSchema({
      //   field: 'faultIds',
      //   componentProps: {
      //     options: fileFlow.faultList,
      //   },
      // });
      fileFlow.type = data.type;
      fileFlow.cameraType = data.cameraType;
      setFieldsValue({
        ...data,
        remark:'',
        deviceInfo: t(`routes.scene.tableType.${data.cameraType}`) + data.cameraSnCode,
      });
    }
    function del(field) {
      removeSchemaByFiled([`deviceType${field}`, `device_${field}`, `${field}`]);
      n.value--;
    }
    function add() {
      let list = addSchemas(n.value);
      list.map((ele) => {
        appendSchemaByField(ele, '');
      });
      n.value++;
    }
    function addSchemas(number) {
      let parentList: FormSchema[] = [
        {
          field: 'partId' + number,
          label: '备件' + number,
          component: 'ApiSelect',
          colProps: {
            span: 12,
          },
          required: true,
          componentProps: {
            maxLength: 15,
            api: partAllList,
            style:'width: 220px',
            labelField: 'partName',
            valueField: 'partId',
            params: {
              cameraType: fileFlow.cameraType,
            },
            showSearch: true,
            optionFilterProp: 'label',
          },
        },
        {
          field: 'partCount' + number,
          label: '数量',
          component: 'InputNumber',
          required: true,
          defaultValue: 1,
          labelWidth: 50,
          componentProps: {
            max: 999,
            min: 1,
          },
          colProps: {
            span: 6,
          },
        },
        {
          field: number.toString(),
          component: 'Input',
          label: '',
          labelWidth: 0,
          colProps: {
            span: 6,
          },
          slot: 'del',
        },
      ];
      return parentList;
    }
    const handleSubmit = async () => {
      const params = await validate();
      try {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '温馨提示'),
          content: '确定要完成维修吗?',
          onOk: async () => {
            loading.value = true;
            await repairOver(params);
            loading.value = false;
            createMessage.success(t('common.optSuccess'));
            closeModal();
            emit('update');
          },
          onCancel: () => {
            loading.value = false
          }
        });
      } catch (error) {
        loading.value = false;
        console.log('not passing', error);
      }
    };
    return {
      register,
      registerForm,
      fileFlow,
      handleSubmit,
      addListFunc,
      resetFields,
      registerTable,
      loading,
      t,
      del,
      add,
    };
  },
});
</script>
