<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="确认报价"
    width="600px"
    @cancel="clearInfo"
    :confirmLoading="loading"
    @ok="handleApi"
  >
    <!-- <template #footer>
      <div style="text-align: center">
        <a-button type="primary" danger @click="handleCancel">取消维修</a-button>
        <a-button type="primary" @click="handleSubmit">确认维修</a-button>
      </div>
    </template> -->
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
      </BasicForm>
      <div class="priceCount">
        <span>合计：</span>
        <div class="label">{{ fileFlow.priceCount || 0 }}元 </div>
      </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 { getPriceList, confirmRepair, allList } from '/@/api/spares';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { RedoOutlined } from '@ant-design/icons-vue';
  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, RedoOutlined },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const n = ref(1);
      const fileFlow = reactive({
        file: null,
        type: 2, //2-普通发票，3-专用发票
        count: 1, //第一次报价
        priceCount: 0, //总价
        priceLists: [],
        priceListsPrice: {},
      });
      const loading = ref(false);
      const { createMessage, createConfirm } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          show: false,
          label: '发票编号',
        },
        {
          field: 'repairId',
          component: 'Input',
          label: '维修单号',
          slot: 'text',
          colProps: {
            span: 24,
          },
        },
        {
          field: 'warrantyExpirationDateText',
          component: 'Input',
          slot: 'text',
          label: '保修届满日期',
        },
        {
          field: 'deviceInfo',
          component: 'Input',
          label: '设备信息',
          slot: 'text',
          colProps: {
            span: 18,
          },
        },
        {
          field: 'checkResult',
          component: 'Input',
          label: '检测结果',
          slot: 'text',
          colProps: {
            span: 18,
          },
        },
        {
          field: 'confirm',
          component: 'RadioGroup',
          label: '维修意向',
          defaultValue: 0,
          componentProps: {
            options: [
              {
                label: '确认维修',
                value: 0,
              },
              {
                label: '取消维修',
                value: 1,
              },
            ],
            onChange: (val) => {
              console.log('ifShow',val)
              updateSchema({
                field: 'remark',
                required: val.target.value == 1,
                ifShow: val.target.value == 1,
              })
            },
          },
          colProps: {
            span: 22,
          },
        },
        {
          field: 'remark',
          component: 'InputTextArea',
          ifShow: false,
          required: false,
          label: '取消原因',
          componentProps: {
            maxLength: 500,
            rows: 4,
            placeholder: '请填写取消原因',
          },
          colProps: {
            span: 18,
          },
        },
      ];

      const [
        registerForm,
        {
          validate,
          getFieldsValue,
          resetFields,
          setFieldsValue,
          removeSchemaByFiled,
          appendSchemaByField,
          updateSchema,
        },
      ] = useForm({
        labelWidth: 100,
        labelAlign: 'left',
        schemas: schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(async () => {
        let allListOption = await allList(); //获取价格
        fileFlow.priceListsPrice;
        allListOption.map((ele) => {
          fileFlow.priceListsPrice[ele.laborCostId] = ele.price;
        });
      });
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      async function updataRepairInfo() {
        let { repairId } = getFieldsValue();
        console.log('20230228171427939', repairId);
        const { priceLists } = await getPriceList({ repairId }); //
        addPriceItem(priceLists);
        clearInfo(true);
        setTimeout(() => {
          updataCount();
        }, 100);
      }
      async function onDataReceive(data) {
        const { priceLists } = await getPriceList({ repairId: data.repairId }); //
        addPriceItem(priceLists);
        resetFields();
        fileFlow.type = data.type;
        updateSchema({
          field: 'remark',
          required: false,
          ifShow: false,
        })
        setFieldsValue({
          ...data,
          remark: '',
          warrantyExpirationDateText: data.warrantyDate + '(' + t(`routes.spares.warrantyType.${data.warrantyType}`) + ')',
          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 addPriceItem(list) {
        fileFlow.priceLists = list.reverse();
        let priceSchema = [],
          valueObj = {},
          count = 0;
        list.map((ele) => {
          if (ele.count == 0) {
            return;
          }
          let price = ele.discount == 1 ? ele.priceDiscount : ele.price;
          valueObj[`priceList${ele.priceListId}`] = ele.count || 0;
          valueObj[`remark${ele.priceListId}`] = ele.remark || 0;
          valueObj[`priceListText${ele.priceListId}`] = `${ele.name} ${price} 元${
            ele.type == 0 ? '/' + ele.partUnit : ''
          }`;
          count = count + ele.count * price;
          priceSchema.unshift(
            {
              field: 'priceListText' + ele.priceListId,
              component: 'InputNumber',
              label: ele.type == 0 ? '备件' : ele.type == 2 ? '明细' : ele.type == 3 ? '减免' : '人工',
              slot: 'text',
              // labelWidth:300,
              // subLabel:"数量",
              colProps: {
                span: 18,
              },
            },
            {
              field: 'priceList' + ele.priceListId,
              label: '数量', //`${ele.type == 0?'备件':'人工'}：  ${ele.name} ${ele.price} 元/次`,
              // suffix:'数量',
              component: 'InputNumber',
              slot: 'text',
              defaultValue: ele.count || 0,
              // labelWidth:300,
              // subLabel:"数量",
              colProps: {
                span: 6,
              },
              required: true,
              componentProps: {
                disabled: ele.status == 1,
                min: 0,
                max: 999,
                maxLength: 15,
                onChange: (_) => {
                  setTimeout(() => {
                    updataCount();
                  }, 100);
                },
              },
            },
            {
              field: 'remark' + ele.priceListId,
              label: '备注',
              component: 'InputNumber',
              ifShow: ele.type == 2 || ele.type == 3,
              slot: 'text',
              colProps: {
                span: 18,
              },
            },
          );
        });
        fileFlow.priceCount = count.toFixed(2);
        priceSchema.map((item) => {
          console.log('priceSchema', item);
          appendSchemaByField(item, '');
        });
        console.log('addPriceItem', valueObj);
        setTimeout(() => {
          setFieldsValue(valueObj);
        }, 10);
      }
      function addSchemas(number) {
        let parentList: FormSchema[] = [
          {
            field: 'deviceType' + number,
            label: '人工',
            component: 'ApiSelect',
            colProps: {
              span: 12,
            },
            required: true,
            componentProps: {
              api: allList,
              labelField: 'name',
              valueField: 'laborCostId',
              showSearch: true,
              onChange: (value) => {
                console.log('onchange', value, arguments);
              },
            },
          },
          {
            field: 'device_' + 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 handleCancel = async (val) => {
        console.log('handleCancel', val, arguments);
        handleApi(true);
      };

      const handleApi = async () => {
        const params = await validate();
        let val = params.confirm == 1;
        try {
          createConfirm({
            iconType: 'warning',
            title: () => h('span', '温馨提示'),
            content: val ? '确定取消维修吗' : '确定报价并开始维修吗?',
            onOk: async () => {
              loading.value = true;
              let res = await confirmRepair({
                repairId: params.repairId,
                remark: params.remark,
                confirm: val ? 1 : 0,
              });
              console.log('res', res);
              createMessage.success(t('common.optSuccess'));
              closeModal();
              emit('update');
              loading.value = false;
              clearInfo(false);
            },
            onCancel: () => {
              loading.value = false;
            },
          });
        } catch (error) {
          loading.value = false;
          console.log('not passing', error);
        }
      };

      const handleSubmit = async () => {
        handleApi(false);
      };
      function updataCount() {
        let fromData = getFieldsValue(),
          count = 0;
        // fileFlow.priceListsPrice
        console.log('fromData', fromData);
        fileFlow.priceLists.map((ele) => {
          count = count + fromData[`priceList${ele.priceListId}`] * ele.price;
        });
        for (let index = 1; index < n.value; index++) {
          if (fromData[`deviceType${index}`] && fromData[`device_${index}`]) {
            let priceId = fromData[`deviceType${index}`];
            let fromPrice = fromData[`device_${index}`] * fileFlow.priceListsPrice[priceId];
            count = count + fromPrice;
          }
        }
        fileFlow.priceCount = count.toFixed(2);
      }

      function clearInfo(val) {
        fileFlow.priceCount = 0;
        if (!val) {
          resetFields();
        }
        let clearFiled = [];
        fileFlow.priceLists.map((ele) => {
          clearFiled.push(`priceList${ele.priceListId}`, `priceListText${ele.priceListId}`,`remark${ele.priceListId}`);
        });
        removeSchemaByFiled(clearFiled);
        n.value = 1;
      }

      return {
        register,
        registerForm,
        fileFlow,
        handleSubmit,
        handleCancel,
        addListFunc,
        resetFields,
        loading,
        clearInfo,
        updataCount,
        handleApi,
        t,
        del,
        add,
        updataRepairInfo,
      };
    },
  });
</script>

<style lang="less" scoped>
  .priceCount {
    line-height: 32px;
    .label {
      display: inline-block;
    }
  }
</style>
