<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="operationOrderDetailProductDetailList"
      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 * as OperationOrderApi from '/@/api/order/operationOrderApi';
  import * as DistributorApi from '/@/api/system/distributorApi';
  import * as OperationWorkOrderApi from '/@/api/order/operationWorkOrderApi';
  import lodash from 'lodash';
  import { message } from 'ant-design-vue';

  import {OperationOrder } from '/@/api/model/operationOrder';
  import { Distributor } from '/@/api/model/distributor';
  import { OperationOrderDetail } from '/@/api/model/operationOrderDetail';

  const detailColumns = [
    {
      title: '产品编号',
      dataIndex: 'thirdProductId',
      key: 'thirdProductId',
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '类型',
      dataIndex: 'goodsType',
      key: 'goodsType',
    },
    {
      title: '订购数量',
      key: 'ordered',
    },
    {
      title: '单价',
      dataIndex: 'price',
      key: 'price',
    },
    {
      title: '总价',
      key: 'total',
    },
    {
      title: '返货数量',
      dataIndex: 'quantity',
      key: 'quantity',
    },
  ];

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

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

  const handleOk = () => {
    const orderClone :any = lodash.cloneDeep(order.value);
    if (orderClone) {
      orderClone.operationWorkOrderDetailList = orderClone.operationOrderDetailList;
      orderClone.operationOrderId = orderClone.id;
      orderClone.status = 'DELIVERED';

      delete orderClone.operationOrderDetailList;
      delete orderClone.id;

      orderClone.operationWorkOrderDetailList?.forEach((item) => {
        item.operationWorkOrderProductDetailList = item.operationOrderDetailProductDetailList;

        delete item.operationOrderDetailProductDetailList;

        item.operationWorkOrderProductDetailList.forEach((el) => {
          el.operationWorkOrderDetailId = el.operationOrderDetailId;

          delete el.operationOrderDetailId;
        });
      });

      okLoading.value = true;
     OperationWorkOrderApi.createBackOrder(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<OperationOrder[] | []>([]);
  const productList = ref<OperationOrderDetail[] | undefined>();
  const order = ref<OperationOrder>();

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

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

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

  const handleChangeOrder = (id: number) => {
    tableLoading.value = true;
    OperationOrderApi.getById(id)
      .then((res: OperationOrder) => {
        res.operationOrderDetailList?.forEach((item) => {
          // @ts-ignore
          item.uuid = item.goodsId + '';
          // @ts-ignore
          item.operationOrderDetailProductDetailList.forEach((el) => {
            el.uuid = item.goodsId + '-' + el.id;
            el.ordered = el.quantity;
            el.goodsType = item.goodsType;
          });
        });
        order.value = res;
        productList.value = res.operationOrderDetailList;
      })
      .finally(() => {
        tableLoading.value = false;
      });
  };

  defineExpose({ open });
</script>

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