<template>
  <div>
    <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"
            style="margin-bottom: 22px">
            <el-select v-model="form.returnSourceType" style="width: 100%" disabled>
              <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="entrustedReceiveCode"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.entrustedReceiveCode"
              @click.native="handleEntrustedReceive"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            v-else
            label="发货单"
            prop="sendNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.sendNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <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-col>
        <el-col :span="12">
          <el-form-item
            label="客户名称"
            prop="contactName"
            style="margin-bottom: 22px">
            <el-input v-model="form.contactName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item
            label="退货备注"
            prop="remark"
            style="margin-bottom: 22px">
            <el-input clearable v-model="form.remark" type="textarea" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <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-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"
            style="margin-bottom: 22px"
            v-show="!['4'].includes(form.returnType)"

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

      <headerTitle
        title="产品清单"
        style="margin-top: 30px"
      ></headerTitle>
      <inventoryTable
        ref="inventoryTableref"
        :pricingWay="form.pricingWay"
        :returnSourceType="form.returnSourceType"
        :entrustedCode="form.entrustedCode"
        :sendId="form.sendId"
        :type="form.type"
        @payAmountChange="payAmountChange"
      ></inventoryTable>


    </el-form>
    <!--  受托发货单  -->
    <entrusted-receive-dialog :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
                              v-if="entrustedReceiveDialogFlag"
                              @changeParent="getInfo"
                              ref="entrustedReceiveDialogRef"></entrusted-receive-dialog>
  </div>
</template>

<script>
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {getReturnSaleOrderrecordDetail} from '@/api/bpm/components/saleManage/saleorder';
import inventoryTable from './inventoryTable.vue';
import {copyObj} from '@/utils/util';
import EntrustedReceiveDialog from "@/views/bpm/handleTask/components/saleOrder/invoice/entrustedReceiveDialog.vue";
import {getPSaleEntrustedReceiveDetailAPI} from "@/api/bpm/components/saleManage/entrustedReceive";

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

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

    return {
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      visible: false,
      entrustedReceiveDialogFlag: false,
      payAmount1: '',
      title: '',
      row: {},
      activeName: 'base',
      formDef,
      form: copyObj(formDef),
      tableBankData: [],
      tableLinkData: [],
      // 组织机构树形结构数据
      groupTreeData: [],
      groupData: [],
      rules: {
        entrustedReceiveCode: [
          {required: true, message: '请选择受托收货单', trigger: 'change'}
        ],
      },

      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },

  created() {
    this.getDetail(this.businessId);
  },
  methods: {
    //选择受托收货单弹框
    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);
        });
      }

    },
    //删除产品
    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;
    },

    //获取退货单详情
    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);
        });
      }
    },

    getValidate() {
      let arr = [];
      arr.push(
        new Promise((resolve, reject) => {
          this.$refs.inventoryTableref.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
      ]);
    },
    async getTableValue() {
      try {
        await this.getValidate();
        // 表单验证通过，执行保存操作
        this.loading = true;
        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;
        return Object.assign({}, this.form, {
          totalAmount: Number(this.$refs.inventoryTableref.payAmount),
          productList: data.productList
        });
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    },
  }
};
</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>
