<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" class="el-form-box" label-width="120px">
      <headerTitle title="退货信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="退货类型"
            prop="returnSourceType"
           >
            <el-select v-model="form.returnSourceType" @change="handleSetReturnSourceType" 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
            v-if="form.returnSourceType==2"
            label="受托收货单"
            prop="sendNo"

          >
            <el-input
              clearable
              v-model="form.entrustedReceiveCode"
              @click.native="handleEntrustedReceive"
              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-row>
      <el-row>
        <el-col :span="12">
          <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-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-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="returnFiles" label="退货附件">
            <fileUpload
              v-model="form.returnFiles"
              module="main"
              :showLib="false"
              :limit="10"
            />
          </el-form-item>

          <!-- <el-form-item
            label="退货类型"
            prop="sendNo"

          >
            <el-select
              style="width: 100%"
              v-model="form.returnType"
              placeholder="请选择"
              @change="onchangeLink"
            >
              <el-option
                v-for="item in returnList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="赔偿金额"
            prop="aa"

            v-show="['3','5'].includes(form.returnType)"
          >
            <el-input
              clearable
              v-model="aa"
              placeholder="请输入"
            />
          </el-form-item> -->
        </el-col>

        <el-col :span="12">


          <el-form-item prop="repliedFiles" label="回执附件">
            <fileUpload
              v-model="form.repliedFiles"
              module="main"
              :showLib="false"
              :limit="10"
            />
          </el-form-item>
          <!-- <el-form-item
            label="总金额"
            prop="bb"

            v-show="!['4'].includes(form.returnType)"

          >
          {{+aa+form.totalAmount}}元
          </el-form-item> -->
        </el-col>
      </el-row>

      <headerTitle title="原货产品清单" style="margin-top: 30px"></headerTitle>
      <inventoryTable
        :returnType="form.returnType"
        :returnSourceType="form.returnSourceType"
        :pricingWay="form.pricingWay"
        :entrustedCode="form.entrustedCode"
        ref="inventoryTableref"
        :sendId="form.sendId"
        :sendNo="form.sendNo"
      ></inventoryTable>
      <!-- <headerTitle
        title="实物赔偿清单"
        v-show="['2', '4'].includes(form.returnType)"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable1
      v-show="['2', '4'].includes(form.returnType)"

        ref="inventoryTableref1"
        :sendId="form.sendId"
      ></inventoryTable1> -->
      <!-- <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>
    <!--  受托发货单  -->
    <entrusted-receive-dialog :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
                              v-if="entrustedReceiveDialogFlag"
                              @changeParent="getInfo"
                              ref="entrustedReceiveDialogRef"></entrusted-receive-dialog>
  </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,
  submit,
  UpdateReturnInformation
} from '@/api/saleManage/returnGoods';
import {getSendSaleOrderrecordDetail} from '@/api/saleManage/saleordersendrecord';
import inventoryTable from './inventoryTable.vue';
import sendListDialog from './sendListDialog.vue';
import {copyObj} from '@/utils/util';
import inventoryTable1 from '@/views/contractManage/contractBook/components/inventoryTable.vue';
import entrustedReceiveDialog from "@/views/saleManage/saleOrder/invoice/components/entrustedReceiveDialog.vue";
import {getPSaleEntrustedReceiveDetailAPI} from "@/api/saleManage/entrustedReceive";
import {getWarehouseListByIds} from "@/api/purchasingManage/returnGoods";

export default {
  mixins: [dictMixins],
  components: {
    entrustedReceiveDialog,
    fileUpload,
    deptSelect,
    sendListDialog,
    inventoryTable,
    inventoryTable1,
    parentList,
    personSelect
  },
  data() {
    let formDef = {
      id: '',
      payAmount: '',
      returnFiles: [],
      repliedFiles: [],
      remark: '',
      sendId: '',
      sendNo: '',
      totalAmount: '',
      returnType: '',
      pricingWay: '',
      returnSourceType: 3,
      entrustedCode: '',
      entrustedId: '',
      entrustedReceiveId: '',
      entrustedReceiveCode: '',
    };

    return {
      aa: '',
      returnList: [
        {label: '原货退回', value: '1'},
        {label: '部分原货+实物赔偿', value: '2'},
        {label: '部分原货+现金赔偿', value: '3'},
        {label: '全部实物赔偿', value: '4'},
        {label: '全部现金赔偿', value: '5'}
      ],
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      acceptUnpackoptions,
      visible: 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: ''
    };
  },
  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);
      }
    },
    onchangeLink() {
      this.getSendSaleOrderDetail(this.form.sendId);
    },
    //设置退货类型
    handleSetReturnSourceType(val) {
      this.$nextTick(() => {
        this.form = Object.assign({}, this.form, {
          orderId: '',
          sendNo: '',
          sendId: '',
          contactName: '',
          contactId: '',
          pricingWay: '',
          entrustedCode: '',
          entrustedId: '',
          entrustedReceiveId: '',
          entrustedReceiveCode: '',
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.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) {
      const data = await getPSaleEntrustedReceiveDetailAPI(row.id);
      if(data){
        data.productList.forEach((item) => {
          item.sendProductId = item.id;
          item.id = '';
        });
        this.$nextTick(() => {
          let {
            code,
            id,
            productList,
            contactId,
            contactName,
            pricingWay = data?.saleOrder?.pricingWay
          } = data;
          if (productList && productList.length > 0) {
            productList.forEach((v) => {
              v.orderTotalCount = v.orderTotalCount || v.totalCount;
            });
          }
          this.form = Object.assign({}, this.form, {
            orderId: data.orderId,
            sendNo: '',
            sendId: '',
            contactName,
            pricingWay,
            contactId,
            entrustedCode: code,
            entrustedId: id,
            entrustedReceiveId: id,
            entrustedReceiveCode: code,
          });
          productList.forEach(item => {
            item.id = ''
          })
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(productList, code);
        });
      }

    },
    //选择订单回调
    changeOrder(obj) {
      // this.orderId=obj.id
      // this.form = Object.assign({},this.form,{
      //   orderId: obj.orderId,
      //   sendNo: obj.docNo,
      //   sendId:obj.id
      // })
      this.getSendSaleOrderDetail(obj.id);
    },

    //发货单详情
    async getSendSaleOrderDetail(id) {
      this.loading = true;
      const data = await getSendSaleOrderrecordDetail(id);
      this.loading = false;
      if (data) {
        data.productList.forEach((item) => {
          item.sendProductId = item.id;
          item.id = '';
        });
        // console.log(data.productList)
        // return
        this.$nextTick(() => {
          this.form = Object.assign({}, this.form, {
            orderId: data.orderId,
            sendNo: data.docNo,
            sendId: data.id,
            contactName: data.contactName,
            contactId: data.contactId,
            pricingWay: data?.saleOrder?.pricingWay,
            entrustedCode:data.entrustedCode,
            entrustedId: data.entrustedCode,
            entrustedReceiveId: '',
            entrustedReceiveCode: '',
          });
          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.form.pricingWay = data?.saleOrder?.pricingWay
          this.form.entrustedCode = data?.entrustedReceiveCode;
          this.form.entrustedId = data?.entrustedReceiveId;
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(data.productList);
        });
      }
    },

    //选择订单弹框
    handleOrderBtn() {

      let item = {
        id: this.form.sendId
      };
      this.$refs.sendListDialogRef.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() {
      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 data = this.$refs.inventoryTableref.getTableValue();
        if (data.productList.length === 0) {
          return this.$message.error('至少选择一个退货产品');
        }
        this.form.repliedFiles = this.form.repliedFiles || [];
        this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
        let commitData = Object.assign({}, this.form, {
          totalAmount: Number(this.$refs.inventoryTableref.payAmount),
          productList: data.productList,
          redressProductList: []
        });
        commitData.payAmount = data.payAmount;
        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);
                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());
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        }
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    },
    returnSubmit(res,storemanIds) {
      submit({
        businessId: this.businessId || res,
        returnSourceType: this.form.returnSourceType,
        variables: {
          storemanIds
        }
        // productionSupervisorId
      }).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>
