<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    width="70%"
    @close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="退货信息"></headerTitle>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="退货类型"
            prop="returnSourceType"
            >
            <el-select v-model="form.returnSourceType" @change="handleSetReturnSourceType" style="width: 100%">
              <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
            v-if="form.returnSourceType==2"
            label="委外发货单"
            prop="outsourceSendCode"

          >
            <el-input
              clearable
              v-model="form.outsourceSendCode"
              @click.native="handleOutsourceSend"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="收货单"
            v-else
            prop="receiveNo"

          >
            <el-input
              clearable
              v-model="form.receiveNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="供应商收货地址"
            prop="receiveAddress"

          >
            <el-input
              clearable
              v-model="form.receiveAddress"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="订单类型"

          >
            <el-input v-model="form.sourceTypeName" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark" >
            <el-input
              clearable
              v-model="form.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item prop="returnFiles" label="附件">
            <fileUpload
              v-model="form.returnFiles"
              module="main"
              :showLib="false"
              :limit="10"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="供应商联系人"
            prop="linkName"

          >
            <el-input clearable v-model="form.linkName" placeholder="请输入"/>
          </el-form-item>
          <el-form-item
            label="供应商联系电话"
            prop="linkPhone"

          >
            <el-input clearable v-model="form.linkPhone" placeholder="请输入"/>
            <!-- {{ form.linkPhone }} -->
          </el-form-item>
          <el-form-item
            label="计价方式"
            >
            <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-row>
      <headerTitle title="产品清单" style="margin-top: 30px"></headerTitle>
      <inventoryTable
        :pricingWay="form.pricingWay"
        :returnSourceType="form.returnSourceType"
        :sourceType="form.sourceType"
        :outsourceSendCode="form.outsourceSendCode"
        :receiveNo="form.receiveNo"
        :payAmount.sync="form.payAmount"
        ref="inventoryTableref"
        :receiveId="form.receiveId"
      ></inventoryTable>
<!--      <el-row style="margin-top: 20px">-->
<!--        <el-col :span="12">-->
<!--          <el-form-item-->
<!--            label="总金额"-->
<!--            prop="totalPrice"-->
<!--            -->
<!--          >-->
<!--            {{ totalAmount }}元-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--        <el-col :span="12">-->
<!--          <el-form-item-->
<!--            label="金额"-->
<!--            prop="payAmount"-->
<!--            >-->
<!--            <el-input clearable v-model="form.payAmount" placeholder="请输入"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
<!--      </el-row>-->
    </el-form>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="save('sub')">提交</el-button>

      <el-button @click="cancel">返回</el-button>
    </div>
    <sendListDialog
      ref="sendListDialogRef"
      @changeParent="changeOrder"
    ></sendListDialog>
    <!-- 委外发货单   -->
    <out-source-send-dialog :out-source-send-dialog-flag.sync="outSourceSendDialogFlag" v-if="outSourceSendDialogFlag"
                            ref="outSourceSendDialogRef"
                            @changeParent="getOutSourceInfo"></out-source-send-dialog>
  </ele-modal>
</template>

<script>
import {contactDetail} from '@/api/saleManage/contact';
import {numberReg} from 'ele-admin';
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {
  addReturnInformation,
  getReturnSaleOrderrecordDetail,
  getWarehouseListByIds,
  submit,
  UpdateReturnInformation
} from '@/api/purchasingManage/returnGoods';
import {getReceiveSaleOrderrecordDetail} from '@/api/purchasingManage/purchaseorderreceive';
import inventoryTable from './inventoryTable.vue';
import sendListDialog from './sendListDialog.vue';
import {copyObj} from '@/utils/util';
import outSourceSendDialog from "@/views/purchasingManage/purchaseOrder/invoice/components/outSourceSendDialog.vue";
import {getPurchaseOutSourceSendDetailAPI} from "@/api/purchasingManage/outSourceSend";

export default {
  mixins: [dictMixins],
  components: {
    outSourceSendDialog,
    fileUpload,
    sendListDialog,
    inventoryTable
  },
  data() {
    let formDef = {
      id: '',
      returnFiles: [],
      remark: '',
      receiveId: '',
      receiveNo: '',
      totalAmount: '',
      returnSourceType: 1,
      linkName: '',
      linkPhone: '',
      payAmount: '',
      pricingWay: '',
      sourceType: '',
      sourceTypeName: '',
      outsourceSendId: '',
      outsourceSendCode: '',
      receiveAddress: ''
    };

    return {
      visible: false,
      outSourceSendDialogFlag: false,
      title: '',
      row: {},
      activeName: 'base',
      formDef,
      form: copyObj(formDef),
      // 组织机构树形结构数据
      rules: {
        receiveNo: [
          {required: true, message: '请选择收货单', trigger: 'change'}
        ],
        outsourceSendCode: [
          {required: true, message: '请选择委外发货单', trigger: 'change'}
        ],
        receiveAddress: [
          {
            required: true,
            message: '请输入供应商收货地址',
            trigger: 'change'
          }
        ],
        linkPhone: [
          {
            required: true,
            message: '请输入供应商联系电话',
            trigger: 'change'
          }
        ],
        payAmount: [
          {
            required: true,
            pattern: numberReg,
            message: '请输入数字',
            trigger: 'blur'
          }
        ]
      },
      businessId: '',
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  computed: {
    totalAmount() {
      return this.$store.state.returnGoods.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);
      }
    },
    //设置退货类型
    handleSetReturnSourceType(val) {
      this.$nextTick(() => {
        this.form = Object.assign({}, this.form, {
          receiveId: '',
          receiveNo: '',
          totalAmount: '',
          linkName: '',
          linkPhone: '',
          payAmount: '',
          pricingWay: '',
          sourceType: '',
          sourceTypeName: '',
          receiveAddress: '',
          outsourceSendId: '',
          outsourceSendCode: '',
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
      });
    },
    //选择委外发货单弹框
    handleOutsourceSend(e) {
      if (e.target.nodeName == 'I') {
        this.form = Object.assign({}, this.form, {
          receiveId: '',
          receiveNo: '',
          totalAmount: '',
          linkName: '',
          linkPhone: '',
          payAmount: '',
          pricingWay: '',
          sourceType: '',
          sourceTypeName: '',
          receiveAddress: '',
          outsourceSendId: '',
          outsourceSendCode: '',
        })
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
        return
      }
      this.searchParams = {
        orderId: this.form.orderId
      }
      this.outSourceSendDialogFlag = true
      this.$nextTick(() => {
        this.$refs.outSourceSendDialogRef.init();
      })

    },
    //获取委外发货单数据回调
    async getOutSourceInfo(row) {
      const data = await getPurchaseOutSourceSendDetailAPI(row.id);
      this.$nextTick(async () => {
        let {
          carNo,
          code,
          id,
          linkName,
          linkPhone,
          orderId,
          orderNo,
          productList,
          sendNoteNo,
          supplierId,
          supplierName,
          sourceType,
          sourceTypeName,
          pricingWay
        } = data;
        if (productList && productList.length > 0) {
          productList.forEach((v) => {
            v.orderTotalCount = v.orderTotalCount || v.totalCount;
            v.receiveProductId = v.id
            v.id = ''
          });
        }
        const contactInfo = await contactDetail(data.supplierId);
        this.form = Object.assign({}, this.form, {
          supplierId,
          supplierName,
          linkName,
          linkPhone,
          orderNo,
          orderId,
          sourceTypeName,
          sourceType,
          productList,
          sendNoteNo,
          carNo,
          pricingWay,
          receiveAddress: contactInfo.other?.addressName + contactInfo.other?.address,
          reviewStatus: null,
          outsourceSendCode: code,
          outsourceSendId: id
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue(productList,code);
      });
    },

    //选择订单弹框
    handleOrderBtn(e) {
      if (e.target.nodeName == 'I') {
        this.form = Object.assign({}, this.form, {
          receiveId: '',
          receiveNo: '',
          totalAmount: '',
          linkName: '',
          linkPhone: '',
          payAmount: '',
          pricingWay: '',
          sourceType: '',
          sourceTypeName: '',
          receiveAddress: '',
          outsourceSendId: '',
          outsourceSendCode: '',
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
        return
      }
      let item = {
        id: this.form.sendId
      };
      this.$refs.sendListDialogRef.open(item);
    },
    //选择订单回调
    changeOrder(obj) {
      this.getSendSaleOrderDetail(obj.id);

    },

    //发货单详情
    async getSendSaleOrderDetail(id) {
      this.loading = true;
      const data = await getReceiveSaleOrderrecordDetail(id);
      this.loading = false;
      if (data) {
        this.$nextTick(async () => {
          const contactInfo = await contactDetail(data.supplierId);
          this.form = Object.assign({}, data, {
            id: this.businessId,
            receiveId: data.id,
            receiveAddress: contactInfo.other?.addressName + contactInfo.other?.address,
            reviewStatus: null,
            returnSourceType:this.form.returnSourceType
          });
          data.productList.forEach(item =>{
            item.receiveProductId = item.id
            item.id = ''
          } )
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(data.productList);
        });
      }
    },

    //获取退货单详情
    async getReturnSaleOrderrecordDetail(id) {
      this.businessId = id;
      this.loading = true;
      const data = await getReturnSaleOrderrecordDetail(id);
      this.loading = false;
      if (data) {
        this.$nextTick(() => {
          this.form = data;
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(data.productList);
        });
      }
    },


    //打开新增编辑弹框
    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);
      }
      if (type == 'add') {
        this.isUpdate = false;
      } else {
        this.isUpdate = true;
      }
    },

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

        if (!this.isUpdate) {
          delete this.form.id;
        }
        let productList = this.$refs.inventoryTableref.getTableValue();
        if (productList.length === 0) {
          return this.$message.error('至少选择一个退货产品');
        }
        let commitData = Object.assign({}, this.form, {
          totalAmount: Number(this.totalAmount),
          productList
        });
        commitData.returnFiles = commitData.returnFiles || [];
        if (this.isUpdate) {
          UpdateReturnInformation(commitData)
            .then((res) => {
              this.loading = false;
              this.$message.success('修改成功');
              if (type === 'sub') {
                this.sub(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } else {
          addReturnInformation(commitData)
            .then((res) => {
              this.loading = false;
              this.$message.success('新增成功');
              if (type === 'sub') {
                this.sub(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        }
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    },
    async sub(res) {
      let ids = this.$refs.inventoryTableref
        .getTableValue()
        .map((item) => item.warehouseId);
      let data = await getWarehouseListByIds(ids || []);
      let storemanIds = data.map((item) => item.ownerId);
      submit({
        businessId: this.businessId || res,
        returnSourceType: this.form.returnSourceType,
        variables: {
          storemanIds: storemanIds.toString(),
          pass: true
        }
      }).then((res) => {
        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>
