<template>
  <a-modal
    v-model:visible="visible"
    title="新增"
    @ok="handleOk"
    @cancel="handleCancel"
    class="myModal"
    width="1200px"
    :confirm-loading="okLoading"
  >
    <div class="wrap">
      <a-form
        :model="formData"
        name="basic"
        ref="formRef"
        layout="inline"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        class="ant-row"
      >
        <a-form-item label="经销商" name="changeDistributorId">
          <a-select
            ref="select"
            v-model:value="formData.changeDistributorId"
            style="width: 200px"
            @change="handleChangeDistributor"
          >
            <a-select-option :value="item.id" v-for="item in distributorList">{{ item.name }}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="订单" name="changeOrderId">
          <a-select
            ref="select"
            v-model:value="formData.changeOrderId"
            style="width: 200px"
            @change="handleChangeOrder"
          >
            <a-select-option :value="item.id" v-for="item in orderList">{{ item.orderSn }}</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
    <a-table
      :dataSource="productList"
      :columns="detailColumns"
      :pagination="false"
      childrenColumnName="batchOrderDetailProductDetailList"
      rowKey="uuid"
      :scroll="{ y: 450 }"
      :loading="tableLoading"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'total'">
          {{ record.goodsId ? '' : record.price * record.quantity }}
        </template>
        <template v-if="column.key === 'price'">
          {{ record.goodsId ? '' : record.price }}
        </template>
        <template v-if="column.key === 'ordered'">
          {{ record.goodsId ? '' : record.ordered }}
        </template>
        <template v-if="column.key === 'quantity'">
          <a-input-number v-model:value="record.quantity" :min="0" v-if="!record.goodsId" />
          <span v-else></span>
        </template>
        <template v-if="column.key === 'goodsType'">
          <span v-if="record.goodsType === 'PRODUCT'">产品</span>
          <span v-else-if="record.goodsType === 'KIT'">套件</span>
        </template>
      </template>
    </a-table>
  </a-modal>
</template>

<script lang="ts" setup>
  import { defineExpose, ref, reactive, defineEmits, watch, defineProps, onMounted } from 'vue';
  import { detailColumns } from '/@/views/order/batch-work-order/schema';
  import * as BatchOrderApi from '/@/api/order/batchOrderApi';
  import * as DistributorApi from '/@/api/system/distributorApi';
  import * as BatchWorkOrderApi from '/@/api/order/batchWorkOrderApi';
  import lodash from 'lodash';
  import { message } from 'ant-design-vue';

  import { BatchOrder } from '/@/api/model/batchOrder';
  import { Distributor } from '/@/api/model/distributor';
  import { BatchOrderDetail } from '/@/api/model/batchOrderDetail';

  const emits = defineEmits(['handleSuccess']);
  const visible = ref<boolean>(false);

  const okLoading = ref(false);
  const tableLoading = ref(false);

  const handleOk = () => {
    const orderClone = lodash.cloneDeep(order.value);
    if (orderClone) {
      orderClone.batchWorkOrderDetailList = orderClone.batchOrderDetailList;
      orderClone.batchOrderId = orderClone.id;
      orderClone.status = 'DELIVERED';

      delete orderClone.batchOrderDetailList;
      delete orderClone.id;

      orderClone.batchWorkOrderDetailList?.forEach((item) => {
        item.batchWorkOrderDetailProductDetailList = item.batchOrderDetailProductDetailList;

        delete item.batchOrderDetailProductDetailList;

        item.batchWorkOrderDetailProductDetailList.forEach((el) => {
          el.batchWorkOrderDetailId = el.batchOrderDetailId;

          delete el.batchOrderDetailId;
        });
      });

      okLoading.value = true;
      BatchWorkOrderApi.addInvoice(orderClone)
        .then(() => {
          message.success('新建成功');
          emits('handleSuccess');
          handleCancel();
        })
        .finally(() => {
          okLoading.value = false;
        });
    } else {
      message.warning('请选择订单');
    }
  };

  const handleCancel = () => {
    distributorList.value = [];
    orderList.value = [];
    productList.value = [];
    formData.changeDistributorId = formData.changeOrderId = '';
    visible.value = false;
  };

  const open = () => {
    visible.value = true;
    getDistributorList();
  };

  const distributorList = ref<Distributor[] | []>([]);
  const orderList = ref<BatchOrder[] | []>([]);
  const productList = ref<BatchOrderDetail[] | undefined>();
  const order = ref<BatchOrder>();

  const formData = reactive({
    changeDistributorId: '',
    changeOrderId: '',
  });

  const getDistributorList = () => {
    DistributorApi.all().then((res) => {
      distributorList.value = res;
    });
  };

  const handleChangeDistributor = (id: number) => {
    BatchOrderApi.search({ pageNum: 1, pageSize: 99, distributorId: id, status: 'PASSED' }).then((res) => {
      orderList.value = res.records;
    });
  };

  const handleChangeOrder = (id: number) => {
    tableLoading.value = true;
    BatchOrderApi.getById(id)
      .then((res: BatchOrder) => {
        res.batchOrderDetailList?.forEach((item) => {
          item.uuid = item.goodsId + '';
          item.batchOrderDetailProductDetailList.forEach((el) => {
            el.uuid = item.goodsId + '-' + el.id;
            el.ordered = el.quantity;
            el.goodsType = item.goodsType;
          });
        });
        order.value = res;
        productList.value = res.batchOrderDetailList;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  };

  defineExpose({ open });
</script>

<style lang="less" scoped>
  .wrap {
    margin-bottom: 10px;
  }
</style>
