<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="退货信息"></headerTitle>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="发货单"
            prop="sendNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.sendNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
            label="退货类型"
            prop="type"
            style="margin-bottom: 22px"
          >
            <DictSelection
              dictName="退货类型"
              clearable
              v-model="form.type"
              @change="onchangeLink"
              :disabled="taskDefinitionKey != 'QCLeader'"
            >
            </DictSelection>
          </el-form-item>
          <el-form-item
            label="计价方式"
            style="margin-bottom: 22px">
            <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-form-item
            label="赔偿金额"
            prop="redressAmount"
            style="margin-bottom: 22px"
            v-show="['30', '50'].includes(form.type)"
          >
            <el-input
              clearable
              v-model="form.redressAmount"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="赔偿总金额" style="margin-bottom: 22px">
            {{ totalAmount }}元
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item
            label="退货备注"
            prop="remark"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.remark"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
            label="客户名称"
            prop="contactName"
            style="margin-bottom: 22px"
          >
            {{ form.contactName }}
          </el-form-item>

          <el-form-item prop="returnFiles" label="退货附件">
            <fileUpload
              v-model="form.returnFiles"
              module="main"
              :showLib="false"
              :limit="10"
            />
          </el-form-item>
          <el-form-item prop="repliedFiles" label="回执附件">
            <fileUpload
              v-model="form.repliedFiles"
              module="main"
              :showLib="false"
              :limit="10"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <headerTitle
        v-if="['10', '20', '30'].includes(form.type)"
        title="产品清单"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable
        v-show="['10', '20', '30'].includes(form.type)"
        ref="inventoryTableref"
        :pricingWay="form.pricingWay"
        :entrustedCode="form.entrustedCode"
        :sendId="form.sendId"
        :type="form.type"
        @payAmountChange="payAmountChange"
      ></inventoryTable>
      <headerTitle
        title="实物赔偿清单"
        v-show="['20', '40'].includes(form.type)"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable1
        v-show="['20', '40'].includes(form.type)"
        ref="inventoryTableref1"
        :pricingWay="form.pricingWay"
        :entrustedCode="form.entrustedCode"
        :sendId="form.sendId"
        :isSinglePrice="false"
      ></inventoryTable1>

      <!-- <el-row style="margin-top: 20px">
        <el-col :span="12">
          <el-form-item
            label="总金额"
            prop="totalPrice"
            style="margin-bottom: 22px"
          >
            {{ totalAmount }}元
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="金额"
            prop="payAmount"
            style="margin-bottom: 22px"
          >
            <el-input clearable v-model="form.payAmount" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row> -->
    </el-form>
    <sendListDialog
      ref="sendListDialogRef"
      @changeParent="changeOrder"
    ></sendListDialog>
  </div>
</template>

<script>
  import { numberReg } from 'ele-admin';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import {
    getReturnSaleOrderrecordDetail,
    getSendSaleOrderrecordDetail
  } from '@/api/bpm/components/saleManage/saleorder';
  import inventoryTable from './inventoryTable.vue';
  import inventoryTable1 from '@/views/bpm/handleTask/components/contractBook/inventoryTable.vue';
  import sendListDialog from './sendListDialog.vue';
  import { copyObj } from '@/utils/util';

  export default {
    mixins: [dictMixins],
    components: {
      fileUpload,
      sendListDialog,
      inventoryTable,
      inventoryTable1
    },
    props: {
      businessId: {
        default: ''
      },
      taskDefinitionKey: {
        default: ''
      }
    },

    data() {
      let formDef = {
        id: '',
        payAmount: '',
        returnFiles: [],
        repliedFiles: [],
        remark: '',
        sendId: '',
        sendNo: '',
        totalAmount: '',
        type: '',
        pricingWay: '',
        entrustedCode: '',
        entrustedId: '',
        redressAmount: 0
      };

      return {
        detailData: {},
        payWayOptions: [],
        delDetailIds: [],
        linkNameOptions: [],
        visible: false,
        payAmount1: '',
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        tableBankData: [],
        tableLinkData: [],
        // 组织机构树形结构数据
        groupTreeData: [],
        groupData: [],
        rules: {
          sendNo: [
            { required: true, message: '请选择发货单', trigger: 'change' }
          ],
          type: [
            {
              required: this.taskDefinitionKey == 'QCLeader' ? true : false,
              message: '请选择退货类型',
              trigger: 'change'
            }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false
      };
    },
    computed: {
      totalAmount() {
        let allcountAmount = 0;
        if (this.form.type === '10' || this.form.type === '20') {
          allcountAmount = this.form.payAmount;
        }
        if (this.form.type === '30') {
          allcountAmount =
            Number(this.form.payAmount) + Number(this.form.redressAmount);
        }

        if (this.form.type === '50') {
          allcountAmount = Number(this.form.redressAmount);
        }
        return allcountAmount;
      }
    },
    created() {
      this.getDetail(this.businessId);
    },
    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);
        }
      },
      payAmountChange(val) {
        this.form.payAmount = val;
      },

      //选择订单回调
      changeOrder(obj) {
        // 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 = '';
          });
          this.$nextTick(() => {
            this.form = Object.assign({}, this.form, {
              orderId: data.orderId,
              sendNo: data.docNo,
              sendId: data.id,
              contactName: data.contactName,
              pricingWay: data?.saleOrder?.pricingWay,
              entrustedCode:'',
              entrustedId: '',
              entrustedReceiveId: '',
              entrustedReceiveCode: '',
            });
            // this.$refs.inventoryTableref &&
            //   this.$refs.inventoryTableref.putTableValue(data.productList);
          });
        }
      },

      //获取退货单详情
      async getDetail(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);
            this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.putTableValue(data);
          });
        }
      },

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

      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 arr = [];
        if (['10', '20', '30'].includes(this.form.type)) {
          arr.push(
            new Promise((resolve, reject) => {
              this.$refs.inventoryTableref.validateForm((valid) => {
                if (!valid) {
                  reject(false);
                } else {
                  resolve(true);
                }
              });
            })
          );
        }
        if (['20', '40'].includes(this.form.type)) {
          arr.push(
            new Promise((resolve, reject) => {
              this.$refs.inventoryTableref1.validateForm((valid) => {
                if (!valid) {
                  reject(false);
                } else {
                  resolve(true);
                }
              });
            })
          );
        }
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          ...arr
        ]);
      },
      onchangeLink() {
        this.getSendSaleOrderDetail(this.form.sendId);
      },

      async getTableValue() {

        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;
          let data = this.$refs.inventoryTableref.getTableValue();
          let redressProductList =
            (this.$refs.inventoryTableref1 &&
              this.$refs.inventoryTableref1.getTableValue()) ||
            [];
          if (data.productList.length === 0) {
            return this.$message.error('至少选择一个退货产品');
          }
          this.form.typeName = this.getDictValue('退货类型', this.form.type);
          this.form.repliedFiles = this.form.repliedFiles || [];
          this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
          let commitData = Object.assign({}, this.form, {
            totalAmount: this.totalAmount,
            productList: data.productList,
            redressProductList
          });
          console.log(commitData);

          return commitData;
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      returnSubmit(res) {
        submit({
          businessId: this.businessId || res
          // 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>
