<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-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item
            label="委外发货单"
            prop="outsourceSendCode"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.outsourceSendCode"
              @click.native="handleOutsourceSend"
              placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
            label="供应商收货地址"
            prop="receiveAddress"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.receiveAddress"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item
            label="订单类型"
            style="margin-bottom: 22px"
          >
            <el-input v-model="form.sourceTypeName" disabled></el-input>
          </el-form-item>
          <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 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"
            style="margin-bottom: 22px"
          >
            <el-input clearable v-model="form.linkName" placeholder="请输入" />
          </el-form-item>
          <el-form-item
            label="供应商联系电话"
            prop="linkPhone"
            style="margin-bottom: 22px"
          >
            <el-input clearable v-model="form.linkPhone" placeholder="请输入" />
            <!-- {{ form.linkPhone }} -->
          </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-col>
      </el-row>
      <headerTitle title="产品清单" style="margin-top: 30px"></headerTitle>
      <inventoryTable
        :pricingWay="form.pricingWay"
        :sourceType="form.sourceType"
        :returnSourceType="2"
        :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"-->
<!--            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>
    <!-- 委外发货单   -->
    <out-source-send-dialog :out-source-send-dialog-flag.sync="outSourceSendDialogFlag" v-if="outSourceSendDialogFlag"
                            ref="outSourceSendDialogRef"
                            @changeParent="getOutSourceInfo"></out-source-send-dialog>

  </div>
</template>

<script>
import {numberReg} from 'ele-admin';
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {getReturnSaleOrderrecordDetail} from '@/api/bpm/components/purchasingManage/returnGoods';
import inventoryTable from './inventoryTable.vue';
import {copyObj} from '@/utils/util';
import {contactDetail} from "@/api/bpm/components/saleManage/contact";
import OutSourceSendDialog from "@/views/bpm/handleTask/components/purchaseOrder/invoice/outSourceSendDialog.vue";
import {getPurchaseOutSourceSendDetailAPI} from "@/api/bpm/components/purchasingManage/outSourceSend";

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

      return {
        row: {},
        formDef,
        form: copyObj(formDef),
        // 组织机构树形结构数据
        rules: {
          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'
            }
          ]
        },

        // 提交状态
        loading: false,
        outSourceSendDialogFlag: false
      };
    },
    computed: {
      totalAmount() {
        return this.$store.state.returnGoods.allcountAmount;
      }
    },
    created() {
      this.$store.commit('returnGoods/clearUserData');
      this.getReturnSaleOrderrecordDetail1(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);
        }
      },
//选择委外发货单弹框
      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
          });
          productList.forEach(item =>{
            item.receiveProductId = item.id
            item.id = ''
          } )
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(productList,code);
        });
      },


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

      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 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 || [];
          return commitData;
        } 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>
