<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :append-to-body="true"
    :close-on-click-modal="false"
    width="70%"
    :maxable="true"
    :resizable="true"
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="160px"
    >
      <headerTitle title="退货信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item label="退货类型" prop="returnSourceType">
            <el-select
              v-model="form.returnSourceType"
              @change="onchangeLink"
              style="width: 100%"
            >
              <el-option :value="3" label="销售发货退货"></el-option>
              <el-option :value="1" label="售后退货"></el-option>
              <el-option :value="2" label="受托收货退货"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="退货方式"
            v-if="form.returnSourceType == 1"
            prop="type"
            style="margin-bottom: 22px"
          >
            <DictSelection
              dictName="退货类型"
              clearable
              v-model="form.type"
              @change="handleSetReturnSourceType"
            >
            </DictSelection>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            v-if="form.returnSourceType == 2"
            label="受托收货单"
            prop="entrustedReceiveCode"
          >
            <el-input
              clearable
              v-model="form.entrustedReceiveCode"
              @click.native="handleEntrustedReceive"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            v-else-if="form.returnSourceType == 4"
            label="销售订单"
            prop="orderId"
          >
            <el-input
              clearable
              v-model="form.orderNo"
              @click.native="handleSaleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item v-else label="发货单/发货确认单" prop="sendNo">
            <el-input
              clearable
              v-model="form.sendNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="计价方式" v-if="title != '新增'">
            <el-select v-model="form.pricingWay" disabled style="width: 100%">
              <el-option label="按数量计费" :value="1"></el-option>
              <el-option label="按重量计费" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="总金额：" prop="totalAmount">
            <el-input v-model="totalAmount" disabled>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="赔偿金额"
            prop="redressAmount"
            style="margin-bottom: 22px"
            :rules="{
              required:
                ['30', '50'].includes(form.type) && form.returnSourceType == 1
            }"
            v-show="
              ['30', '50'].includes(form.type) && form.returnSourceType == 1
            "
          >
            <el-input
              clearable
              v-model="form.redressAmount"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="contactName">
            <el-input v-model="form.contactName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="退货备注" prop="remark">
            <el-input
              clearable
              v-model="form.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="returnFiles" label="退货附件">
            <fileMain v-model="form.returnFiles"></fileMain>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="repliedFiles" label="回执附件">
            <fileMain v-model="form.repliedFiles"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>
      <headerTitle title="原物品清单" style="margin-top: 30px"></headerTitle>
      <inventoryTableDetails
        ref="inventoryTableDetailsRef"
      ></inventoryTableDetails>
      <headerTitle
        title="退货物品明细"
        style="margin-top: 30px"
        v-show="!['40', '50'].includes(form.type) || form.returnSourceType != 1"
      ></headerTitle>
      <inventoryTable
        v-show="!['40', '50'].includes(form.type) || form.returnSourceType != 1"
        :returnType="form.returnType"
        :returnSourceType="form.returnSourceType"
        :entrustedCode="form.entrustedCode"
        ref="inventoryTableref"
        :sendId="form.sendId"
        :sendNo="form.sendNo"
        :type="form.type"
        @handleSelectGoods="handleSelectGoods"
        :orderOption="orderOption"
      ></inventoryTable>
      <headerTitle
        title="实物赔偿清单"
        v-show="['20', '40'].includes(form.type) && form.returnSourceType == 1"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable1
        v-show="['20', '40'].includes(form.type) && form.returnSourceType == 1"
        ref="inventoryTableref1"
        :customerMark="customerMark"
        cacheKeyUrl="eos-saleManage-returnGoods-redressProductList"
        :isOrderNo="true"
        :orderOption="orderOption"
      ></inventoryTable1>
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button
        type="primary"
        v-if="isNeed_process_is_close"
        @click="save('sub')"
        v-click-once
        >提交</el-button
      >
      <el-button @click="cancel">返回</el-button>
    </div>
    <!--  销售发货单  -->
    <sendListDialog
      ref="sendListDialogRef"
      @changeParent="changeOrder"
      :contactData="contactData"
      :saleOrderData="saleOrderData"
    ></sendListDialog>
    <!--  受托发货单  -->
    <entrusted-receive-dialog
      :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
      :contactData="contactData"
      :saleOrderData="saleOrderData"
      v-if="entrustedReceiveDialogFlag"
      @changeParent="getInfo"
      ref="entrustedReceiveDialogRef"
    ></entrusted-receive-dialog>
    <!--    销售订单-->
    <!-- <orderListDialog
      ref="orderListDialogRef"
      @changeParent="changeSaleOrder"
      :contactData="contactData"
    ></orderListDialog> -->
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <!--出库详情-->
    <outbound-details-dialog
      v-if="outboundDetailsDialogFlag && form.returnType != 2"
      ref="outboundDetailsDialogRef"
      :outboundDetailsDialogFlag.sync="outboundDetailsDialogFlag"
      @saveDate="saveDate"
    ></outbound-details-dialog>
    <!--入库详情-->
    <outbound-details-dialog1
      v-if="outboundDetailsDialogFlag1"
      ref="outboundDetailsDialogRef1"
      :outboundDetailsDialogFlag.sync="outboundDetailsDialogFlag1"
      @saveDate="saveDate"
    ></outbound-details-dialog1>
  </ele-modal>
</template>

<script>
  import { numberReg } from 'ele-admin';
  import { acceptUnpackoptions } from '@/enum/dict';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import deptSelect from '@/components/CommomSelect/dept-select.vue';
  import personSelect from '@/components/CommomSelect/person-select.vue';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';
  import {
    addReturnInformation,
    getReturnSaleOrderrecordDetail,
    UpdateReturnInformation
  } from '@/api/saleManage/returnGoods';
  import {
    getSendSaleOrderCordList,
    getSendSaleOrderrecordDetailSplit
  } from '@/api/saleManage/saleordersendrecord';
  import inventoryTable from './inventoryTable.vue';
  import sendListDialog from './sendListMultipleDialog.vue';
  import { copyObj } from '@/utils/util';
  import entrustedReceiveDialog from '@/views/saleManage/saleOrder/invoice/components/entrustedReceiveDialog.vue';
  import { getPSaleEntrustedReceiveDetailAPI } from '@/api/saleManage/entrustedReceive';
  import { getWarehouseListByIds } from '@/api/purchasingManage/returnGoods';
  import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import orderListDialog from '@/views/saleManage/saleOrder/invoice/components/orderListDialog.vue';
  import outboundDetailsDialog from './outboundDetailsDialog.vue';
  import outboundDetailsDialog1 from '@/views/saleManage/saleOrder/entrustedReceive/components/outboundDetailsDialog.vue';
  import inventoryTable1 from '@/BIZComponents/inventoryTable.vue';
  import inventoryTableDetails from '@/views/saleManage/saleOrder/invoice/components/inventoryTableDetails.vue';
  import { getSendSaleOrderConfirmDetail } from '@/api/saleManage/invoiceConfirm';
  import { contactDetail } from '@/api/saleManage/contact';

  export default {
    mixins: [dictMixins],
    components: {
      orderListDialog,
      processSubmitDialog,
      fileMain,
      entrustedReceiveDialog,
      fileUpload,
      deptSelect,
      sendListDialog,
      inventoryTable,
      inventoryTable1,
      parentList,
      personSelect,
      outboundDetailsDialog,
      outboundDetailsDialog1,
      inventoryTableDetails
    },
    //客户管理数据
    props: {
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      let formDef = {
        id: '',
        payAmount: 0,
        returnFiles: [],
        repliedFiles: [],
        remark: '',
        sendId: '',
        sendNo: '',
        orderId: '',
        orderIds: '',
        orderNo: '',
        totalAmount: '',
        returnType: '',
        pricingWay: '',
        returnSourceType: 3,
        isOrderAll: 0,
        entrustedCode: '',
        entrustedId: '',
        entrustedReceiveId: '',
        entrustedReceiveCode: ''
      };

      return {
        orderOption: [],
        fullscreen: false, //全屏
        customerMark: '',
        oldProductList: [],
        detailData: {},
        payWayOptions: [],
        delDetailIds: [],
        linkNameOptions: [],
        acceptUnpackoptions,
        visible: false,
        processSubmitDialogFlag: false,
        outboundDetailsDialogFlag1: false,
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        tableBankData: [],
        tableLinkData: [],
        // 组织机构树形结构数据
        groupTreeData: [],
        groupData: [],
        rules: {
          returnSourceType: [
            { required: true, message: '请选择', trigger: 'change' }
          ],
          sendNo: [{ required: true, message: '请选择', trigger: 'change' }],
          payAmount: [
            {
              required: true,
              pattern: numberReg,
              message: '请输入数字',
              trigger: 'blur'
            }
          ]
        },
        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        entrustedReceiveDialogFlag: false,
        businessId: '',
        orderId: '',
        outboundDetailsDialogFlag: false,
        productList: []
      };
    },
    created() {
      this.requestDict('产地');
    },
    computed: {
      totalAmount() {
        let allcountAmount = 0;
        if (this.form.returnSourceType == 1) {
          if (this.form.type === '10') {
            allcountAmount =
              this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.totalAmount;
          }
          if (this.form.type === '20') {
            allcountAmount =
              (this.$refs.inventoryTableref &&
                this.$refs.inventoryTableref.totalAmount) +
              Number(
                this.$refs.inventoryTableref1 &&
                  this.$refs.inventoryTableref1.getPrice()[0]
              );
          }
          if (this.form.type === '30') {
            allcountAmount =
              (this.$refs.inventoryTableref &&
                this.$refs.inventoryTableref.totalAmount) +
              Number(this.form.redressAmount || 0);
          }
          if (this.form.type === '40') {
            allcountAmount =
              this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.getPrice()[0];
          }
          if (this.form.type === '50') {
            allcountAmount = Number(this.form.redressAmount || 0);
          }
        } else {
          allcountAmount =
            this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.totalAmount;
        }

        return allcountAmount;
      }
    },

    methods: {
      //删除产品
      remove(row) {
        if (this.form.productList.length === 1)
          return this.$message.error('必须要留一个产品');
        let index = this.form.productList.findIndex((n) => n.key == row.key);
        if (index !== -1) {
          this.form.productList.splice(index, 1);
        }
      },
      onchangeLink() {
        this.form.type = '';
        this.handleSetReturnSourceType();
      },
      async contactDetail(id) {
        const { base } = await contactDetail(id);
        this.customerMark = base.serialNo;
        this.$refs.inventoryTableref1.setCustomerMark(base.serialNo);
      },
      //设置退货类型
      handleSetReturnSourceType(val) {
        this.form = Object.assign({}, this.form, {
          orderId: '',
          orderIds: '',
          sendNo: '',
          orderNo: '',
          sendId: '',
          contactName: '',
          contactId: '',
          pricingWay: '',
          entrustedCode: '',
          entrustedId: '',
          entrustedReceiveId: '',
          entrustedReceiveCode: ''
        });
        this.$nextTick(() => {
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          this.$refs.inventoryTableDetailsRef &&
            this.$refs.inventoryTableDetailsRef.putTableValue([]);
        });
      },
      //选择受托收货单弹框
      handleEntrustedReceive(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            carNo: '',
            carId: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            contactId: '',
            contactName: '',
            entrustedCode: '',
            entrustedId: '',
            sendNoteNo: '',
            pricingWay: '',
            entrustedReceiveId: '',
            entrustedReceiveCode: ''
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          return;
        }
        this.entrustedReceiveDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.entrustedReceiveDialogRef.init();
        });
      },
      //获取受托收货单数据回调
      async getInfo(row, type) {
        if (!row.id) {
          return;
        }
        const data = await getPSaleEntrustedReceiveDetailAPI(row.id);
        if (data) {
          this.productList = data.productList;
          if (type) {
            return;
          }

          this.$nextTick(() => {
            let { code, id, productList, contactId, contactName } = data;
            if (productList && productList.length > 0) {
              productList.forEach((v) => {
                v.orderTotalCount = v.orderTotalCount || v.totalCount;
              });
            }
            this.form = Object.assign({}, this.form, {
              orderId: data.orderId,
              orderIds: data.orderIds,
              sendNo: '',
              sendId: '',
              contactName,
              pricingWay,
              contactId,
              entrustedCode: code,
              entrustedId: id,
              entrustedReceiveId: id,
              entrustedReceiveCode: code
            });
            this.handleSelectGoods();
            this.$refs.inventoryTableDetailsRef &&
              this.$refs.inventoryTableDetailsRef.putTableValue(
                data.productList
              );
          });
        }
      },
      //选择发货单回调
      changeOrder(obj = {}) {
        this.getSendSaleOrderMultipleDetail(obj);
      },
      //多发货单详情
      async getSendSaleOrderMultipleDetail(params) {
        this.loading = true;
        this.productList = [];
        let data = {},
          res = {};
        this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue([]);
        this.$refs.inventoryTableref1 &&
          this.$refs.inventoryTableref1.putTableValue({
            productList: []
          });
        if (params.activeName == 1) {
          data = await getSendSaleOrderrecordDetailSplit(params.id);
        } else {
          res = await getSendSaleOrderConfirmDetail(params.id);
          data = await getSendSaleOrderrecordDetailSplit(res.sendId);
        }
        this.loading = false;
        if (data) {
          this.getOrderOption(data);

          this.$nextTick(() => {
            this.setForm(data);
            if (params.activeName == 2) {
              this.productList = data.productList;
              res.productList.forEach((item) => {
                item['orderId'] = this.orderOption[0]?.orderId;
                item['orderNo'] = this.orderOption[0]?.orderNo;
              });

              this.$refs.inventoryTableref &&
                this.$refs.inventoryTableref.putTableValue(res.productList);
              this.$refs.inventoryTableDetailsRef &&
                this.$refs.inventoryTableDetailsRef.putTableValue(
                  data.productList
                );
              return;
            }
            this.productList = data.productList;
            if (
              !['40', '50'].includes(this.form.type) ||
              this.form.returnSourceType != 1
            ) {
              this.handleSelectGoods();
            }

            this.$refs.inventoryTableDetailsRef &&
              this.$refs.inventoryTableDetailsRef.putTableValue(
                data.productList
              );
          });
        }
      },
      setForm(data) {
        data.productList.forEach((item) => {
          item.sendProductId = item.id;
          item.id = '';
        });
        if (data.contactId) {
          this.contactDetail(data.contactId);
        }
        this.form = Object.assign({}, this.form, {
          orderIds: data.orderIds || data.orderId,
          sendNo: data.docNo,
          orderNo: data.orderNo,
          sendId: data.id,
          contactName: data.contactName,
          contactId: data.contactId,
          entrustedCode: data.entrustedCode,
          entrustedId: data.entrustedCode,
          entrustedReceiveId: '',
          entrustedReceiveCode: ''
        });
      },
      getOrderOption(data) {
        if (data.orderIds) {
          this.orderOption = data.orderIds.split(',').map((item, index) => {
            return {
              orderId: item,
              orderNo: data.orderNo.split(',')[index]
            };
          });
        } else {
          this.orderOption = [
            {
              orderId: data.orderId,
              orderNo: data.orderNo
            }
          ];
        }
      },
      //选择退货明细
      handleSelectGoods(list) {
        if (this.form.returnSourceType != 2) {
          this.outboundDetailsDialogFlag = true;
        } else {
          this.outboundDetailsDialogFlag1 = true;
        }
        this.$nextTick(() => {
          if (this.form.returnSourceType != 2) {
            this.$refs.outboundDetailsDialogRef.init(this.form, list);
          } else {
            this.$refs.outboundDetailsDialogRef1.init(this.form, list);
          }
        });
      },
      saveDate(data) {
        data.forEach((item, index) => {
          item['totalCount'] = item.measureQuantity;
          item['orderId'] = this.orderOption[0]?.orderId;
          item['orderNo'] = this.orderOption[0]?.orderNo;

          this.productList.forEach((val) => {
            if (item.productCode == val.productCode) {
              item['singlePrice'] = val.singlePrice;
              item['clientCode'] = item.clientCode || val.customerMark;
              item['pricingWay'] = val.pricingWay || 1;
              item['notaxSinglePrice'] = val.notaxSinglePrice;
              item['taxRate'] = val.taxRate;
              item['goodsLevel'] = val.goodsLevel;
              item['goodsId'] = val.goodsId;
              item['goodsPriceId'] = val.goodsPriceId;
              item['goodsPriceType'] = val.goodsPriceType;
            }
          });
        });
        this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(data);
      },
      //发货单详情
      async getSendSaleOrderDetail(id, type) {
        this.loading = true;
        const data = await getSendSaleOrderrecordDetailSplit(id);

        this.getOrderOption(data);

        this.productList = data.productList;
        this.$nextTick(() => {
          this.$refs.inventoryTableDetailsRef &&
            this.$refs.inventoryTableDetailsRef.putTableValue(data.productList);
        });

        if (type) return;
        if (data.entrustedCode) {
          await this.getInfo({ id: data.entrustedId });
          this.form.returnSourceType = 2;
          this.loading = false;
          return;
        }
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            this.setForm(data);
            this.handleSelectGoods();
          });
        }
      },

      //获取退货单详情
      async getReturnSaleOrderrecordDetail(id) {
        this.businessId = id;

        this.loading = true;
        const data = await getReturnSaleOrderrecordDetail(id);
        this.loading = false;
        if (data) {
          this.form = data;
          this.orderOption = data.returnOrderList;
          this.form.entrustedCode = data?.entrustedReceiveCode;
          this.form.entrustedId = data?.entrustedReceiveId;
          this.$nextTick(() => {
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(data.productList);
            this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.putTableValue({
                productList: data.redressProductList
              });
            if (this.form.returnSourceType != 2) {
              this.getSendSaleOrderDetail(data.sendId, 1);
            } else {
              this.getInfo(data.entrustedReceiveId, 1);
            }
          });
        }
      },

      //选择订单弹框
      handleOrderBtn() {
        let item = {
          id: this.form.sendId
        };
        this.$refs.sendListDialogRef.open(item);
      },
      handleSaleOrderBtn() {
        let item = {
          id: this.form.orderId
        };
        this.$refs.orderListDialogRef.open(item);
      },

      //打开新增编辑弹框
      async open(type, row, sendId) {
        this.title = type === 'add' ? '新增' : '修改';
        this.row = row;
        this.visible = true;
        this.$store.commit('returnGoods/clearUserData');
        if (type === 'add') {
          this.$store.commit('returnGoods/setIsDefaultPayableAmount', false); // 设置标志变量为 false，应付金额将跟随订单金额同步
        }
        if (row && row?.id) {
          await this.getReturnSaleOrderrecordDetail(row?.id);
        }
        if (sendId) {
          await this.getSendSaleOrderDetail(sendId);
        }
        this.isUpdate = type != 'add';
      },

      salesmanChange(val, info) {
        this.otherForm.salesmanName = info.name;
      },
      settlementModeChange(info) {
        this.form.settlementModeName = info.dictValue;
      },
      ifChiefChange(value, idx) {
        if (value === 1) {
          this.tableLinkData.forEach((e) => (e.ifChief = 0));
          this.tableLinkData[idx].ifChief = 1;
        }
      },

      getValidate() {
        let proAll = [
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ];
        if (
          !['40', '50'].includes(this.form.type) ||
          this.form.returnSourceType != 1
        ) {
          proAll.push(
            new Promise((resolve, reject) => {
              this.$refs.inventoryTableref.validateForm((valid) => {
                if (!valid) {
                  reject(false);
                } else {
                  resolve(true);
                }
              });
            })
          );
        }
        return Promise.all(proAll);
      },
      async save(type) {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (!this.isUpdate) {
            delete this.form.id;
          }
          let data = this.$refs.inventoryTableref.getTableValue();
          let redressProductList =
            (this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.getTableValue()) ||
            [];

          if (
            data.productList.length === 0 &&
            (!['40', '50'].includes(this.form.type) ||
              this.form.returnSourceType != 1)
          ) {
            return this.$message.error('至少选择一个退货产品');
          }
          let orderIds = [...data.productList, ...redressProductList].map(
            (item) => item.orderId
          );
          let orderNos = [...data.productList, ...redressProductList].map(
            (item) => item.orderNo
          );

          this.form.repliedFiles = this.form.repliedFiles || [];
          this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
          this.form.typeName = this.getDictValue('退货类型', this.form.type);
          let commitData = Object.assign({}, this.form, {
            totalAmount: this.totalAmount,
            productList: data.productList,
            payAmount: this.totalAmount,
            redressProductList,
            returnOrderList: this.orderOption
          });
          if (orderIds?.length) {
            commitData.orderIds = Array.from(new Set(orderIds)).toString();
          }
          if (orderNos?.length) {
            commitData.orderNo = Array.from(new Set(orderNos)).toString();
          }
          // return;
          if (this.isUpdate) {
            UpdateReturnInformation(commitData)
              .then(async (res) => {
                this.loading = false;

                this.$message.success('修改成功');
                if (type === 'sub') {
                  let storemanIds = '';
                  let ids = commitData.productList.map(
                    (item) => item.warehouseId
                  );
                  let warehouseList = await getWarehouseListByIds(ids || []);
                  storemanIds = warehouseList.map((item) => item.ownerId);
                  await this.returnSubmit(res, storemanIds.toString());
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            addReturnInformation(commitData)
              .then(async (res) => {
                this.loading = false;
                this.$message.success('新增成功');
                if (type === 'sub') {
                  let storemanIds = '';
                  let ids = commitData.productList.map(
                    (item) => item.warehouseId
                  );
                  let warehouseList = await getWarehouseListByIds(ids || []);
                  storemanIds = warehouseList.map((item) => item.ownerId);
                  this.returnSubmit(res, storemanIds.toString());
                  this.$emit('done');
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async returnSubmit(res, storemanIds) {
        const data = await getReturnSaleOrderrecordDetail(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
            businessId: this.businessId || res,
            businessKey:
              this.form.returnSourceType == 1
                ? 'sale_return_approve1'
                : this.form.returnSourceType == 2
                ? 'sale_entrusted_receive_return_approve'
                : 'sales_return_approve',
            formCreateUserId: data.createUserId,
            variables: {
              returnSourceType: data.returnSourceType,
              storemanIds: storemanIds.toString(),
              businessCode: data.returnNo,
              businessName: data.contactName,
              businessType:
                data.returnSourceType == 1
                  ? '售后退货'
                  : data.returnSourceType == 3
                  ? '销售发货退货'
                  : data.returnSourceType == 2
                  ? '受托收货退货'
                  : '销售订单退货'
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      cancel() {
        this.$nextTick(() => {
          this.activeName = 'base';
          // 关闭后，销毁所有的表单数据
          this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
          this.$refs['formRef'] && this.$refs['formRef'].resetFields();
          this.$store.commit('order/clearUserData');
          this.form = copyObj(this.formDef);
          this.visible = false;
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }

  .headbox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .amount {
      font-size: 14px;
      font-weight: bold;
      margin-right: 20px;
    }
  }
</style>
