<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" disabled @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"
            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-form-item
            label="退货类型"
            prop="sendNo"
            style="margin-bottom: 22px"
          >
            <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"
            style="margin-bottom: 22px"
            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"
            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
        :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"
            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 {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 {
  getReturnSaleOrderrecordDetail,
  UpdateReturnInformation
} from '@/api/bpm/components/saleManage/saleorder';
import inventoryTable from './inventoryTable.vue';
import sendListDialog from './sendListDialog.vue';
import {copyObj} from '@/utils/util';
import inventoryTable1 from '@/views/bpm/handleTask/components/contractBook/inventoryTable.vue';

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

    return {
      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: {
        partaName: [
          {required: true, message: '请选择客户名称', trigger: 'change'}
        ],
        payAmount: [
          {
            required: true,
            pattern: numberReg,
            message: '请输入数字',
            trigger: 'blur'
          }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      entrustedReceiveDialogFlag: false,
      orderId: ''
    };
  },
  computed: {
    totalAmount() {
      return this.$store.state.returnGoods.allcountAmount;
    }
  },
  created() {
    this.open()
  },
  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, {
          orderId: '',
          sendNo: '',
          sendId: '',
          contactName: '',
          contactId: '',
          pricingWay: '',
          entrustedCode: '',
          entrustedId: '',
          entrustedReceiveId: '',
          entrustedReceiveCode: '',
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
      });
    },

    //选择订单回调
    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.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() {
      this.title = '修改';
      await this.getReturnSaleOrderrecordDetail(this.businessId);
      this.isUpdate = true;
    },

    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 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;
        let commitData = Object.assign({}, this.form, {
          totalAmount: Number(this.$refs.inventoryTableref.payAmount),
          productList: data.productList,
          redressProductList: []
        });
        commitData.payAmount = data.payAmount;

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

