<template>
    <BasicModal 
      v-bind="$attrs"
      @register="register"
      title="检测登记"
      width="700px"
      @cancel="clearInfo"
      :confirmLoading="loading"
      @ok="handleSubmit"
    >
      <div class="pt-2px pr-3px myRadioGroup">
        <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>
        <div class="tips" style="padding:0 100px">
          <p>说明</p>
          <p>1、保内维修，直接进入待备料或维修中</p>
          <p>2、保外维修，由售后人员进行报价确认后再备料维修</p>
        </div>
      </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 } from '/@/api/spares';
import { useI18n } from '/@/hooks/web/useI18n';
import { uploadApi } from '/@/api/product/index';

const { t } = useI18n();
export default defineComponent({
  components: { BasicModal, BasicForm },
  props: {
    userData: { type: Object },
  },
  emits: ['update', 'register'],
  setup(props, { emit }) {
    const n = ref(1);
    const fileFlow = reactive({
      file: 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: 'warrantyExpirationDateText',
        component: 'Input',
        slot: 'text',
        label: '保修届满日期',
      },
      {
        field: 'faultIds',
        component: 'CheckboxGroup',
        label: '故障类型',
        required: true,
        componentProps: {
          options: fileFlow.faultList,
          maxLength: 50,
        },
        colProps: {
          span: 18,
        },
      },        
      {
        field: 'defineDamage',
        component: 'RadioGroup',
        label: '定损结论',
        helpMessage:'保修期内人为损坏将转为保修外',
        defaultValue: 0,
        componentProps: {
          options: [
            {
              label: '非人为损坏',
              value: 0,
            },
            {
              label: '人为损坏',
              value: 1,
            },
          ],
        },
        colProps: {
          span: 22,
        },
      },
      {
        field: 'checkResult',
        component: 'InputTextArea',
        label: '检测结果',
        required: true,
        componentProps: {
          maxLength: 500,
          rows: 3,
          placeholder: '请描述检测后的具体故障情况。',
        },
        colProps: {
          span: 18,
        },
      },
      {
        field: 'checkImg',
        component: 'Upload',
        label: '相关图片',
        rules: [{ required: false, message: t('common.uploadMessge') }],
        itemProps: {
          validateTrigger: 'blur',
        },
        componentProps: {
          api: uploadApi,
          maxNumber: 5,
          maxSize: 1000,
          accept: ['jpeg', 'jpg', 'png'],
        },

        colProps: {
          span: 12,
        },
      },
      {
        field: '0',
        component: 'Input',
        label: '所需备件',
        colProps: {
          span: 18,
        },
        slot: 'add',
      },
    ];

    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) => {
      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) {
      resetFields();
      updateSchema([{
        field: 'faultIds',
        componentProps: {
          options: fileFlow.faultList,
        },
      },{
        field: 'damage',
        ifShow: data.warrantyType == 0,
      }]);
      fileFlow.type = data.type;
      fileFlow.cameraType = data.cameraType;
      setFieldsValue({
        ...data,
        warrantyExpirationDateText: `${data.warrantyDate} (${data.warrantyType==0?'保内维修':data.warrantyType==1?'保内转保外':'保外维修'})`,
        deviceInfo: t(`routes.scene.tableType.${data.cameraType}`) + data.cameraSnCode,
      });
    }
    function del(field) {
      removeSchemaByFiled([`partId${field}`, `partCount${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,
            style:'width: 220px',
            api: partAllList,
            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;
    }
    function clearInfo(val){
        if(!val){
          resetFields()
        }
        let clearFiled = []
        for (let index = 1; index < n.value; index++) {
          clearFiled.push(`partId${index}`,`partCount${index}`,`${index}`)
        }
        removeSchemaByFiled(clearFiled);
        n.value = 1
      }
    const handleSubmit = async () => {
      loading.value = true;
      try {
        // createConfirm({
        //   iconType: 'warning',
        //   title: () => h('span', '温馨提示'),
        //   content: '确定要提交检测报告吗?',
        //   onOk: async () => {
        const params = await validate();
        let partList = [];
        for (let s = 1; s <= n.value; s++) {
          console.log('params', params, partList);
          if (params[`partId${s}`]) {
            partList.push({
              partId: params[`partId${s}`],
              partCount: params[`partCount${s}`],
              type:0,
            });
          }
        }
        console.log('params', params, partList);
        await checkRegister({
          ...params,
          partList,
        })
        clearInfo(false)
        loading.value = false;
        createMessage.success(t('common.optSuccess'));
        closeModal();
        emit('update');
      } catch (error) {
        loading.value = false;
        console.log('not passing', error);
      }
    };
    return {
      register,
      registerForm,
      fileFlow,
      handleSubmit,
      addListFunc,
      resetFields,
      loading,
      clearInfo,
      t,
      del,
      add,
    };
  },
});
</script>
<style lang="less">
.myRadioGroup{
  .ant-checkbox-group{
    overflow-y: auto;
    height: 90px;
  }
}
</style>
