<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="orderNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.orderNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="外协单位"
            prop="contactName"
            style="margin-bottom: 22px"
          >
            <el-input v-model="form.supplierName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="订单类型"
            prop="sourceTypeName"
            style="margin-bottom: 22px"
          >
            <el-input v-model="form.sourceTypeName" disabled></el-input>
          </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-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="linkPhone"
            style="margin-bottom: 22px"
          >
            <el-input clearable v-model="form.linkPhone" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item
            label="发货日期"
            prop="sendDate"
            style="margin-bottom: 22px">
            <el-date-picker
              v-model="form.sendDate"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="发货单号"
            prop="sendNoteNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.sendNoteNo"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="车辆号" prop="carNo" style="margin-bottom: 22px">
            <el-input clearable v-model="form.carNo" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="files" label="附件">
            <fileMain v-model="form.files"></fileMain>
<!--            <fileUpload-->
<!--              v-model="form.files"-->
<!--              module="main"-->
<!--              :showLib="false"-->
<!--              :limit="10"-->
<!--            />-->
          </el-form-item>
        </el-col>
        <el-col :span="12">

        </el-col>
      </el-row>

    </el-form>

    <headerTitle title="物品清单" style="margin-top: 30px"></headerTitle>
    <inventoryTable
      :pricingWay="form.pricingWay"
      ref="inventoryTableref"
      :orderId="form.orderId"
    ></inventoryTable>
    <!--  采购订单  -->
    <orderListDialog
      :searchParams="orderSearchParams"
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></orderListDialog>
  </div>
</template>

<script>

import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {
  savePurchaseOutSourceSendAPI,
  updatePurchaseOutSourceSendAPI,
  getPurchaseOutSourceSendDetailAPI,
  submit
} from '@/api/bpm/components/purchasingManage/outSourceSend';
// import {getcontactlink} from '@/api/saleManage/businessFollow';
import inventoryTable from './inventoryTable.vue';
import orderListDialog from '../invoice/orderListDialog.vue';
import {copyObj} from '@/utils/util';
import {getpurchaseorderDetail} from "@/api/bpm/components/purchasingManage/purchaseOrder";
import fileMain from "@/components/addDoc/index.vue";

export default {
  mixins: [dictMixins],
  components: {
    fileMain,
    fileUpload,
    inventoryTable,
    orderListDialog
  },
  props: {
    businessId: {
      default: ''
    }
  },
  data() {
    return {
      orderSearchParams: {
        sourceType: '3,4',
      },
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      title: '',
      row: {},
      form: {
        id: '',
        carNo: '',
        files: [],
        linkName: '',
        linkPhone: '',
        orderId: '',
        orderNo: '',
        pricingWay: '',
        productList: [],
        sendNoteNo: '',
        sourceType: '',
        sourceTypeName: '',
        supplierId: '',
        supplierName: '',

      },
      rules: {
        partaName: [
          {required: true, message: '请选择客户名称', trigger: 'change'}
        ],
        linkName: [
          {required: true, message: '请输入', trigger: ['blur', 'change']}
        ],
        linkPhone: [
          {required: true, message: '请输入', trigger: ['blur', 'change']}
        ],
        orderNo: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
        receiveAddress: [
          {required: true, message: '请输入', trigger: 'change'}
        ],
      },

      // 提交状态
      loading: false,
    };
  },
  async created() {
    await this.getSendSaleOrderDetail(this.businessId);
  },
  methods: {
    //选择订单弹框
    handleOrderBtn(e) {
      if (e.target.nodeName == 'I') {
        this.form = Object.assign({}, this.form, {
          supplierId: '',
          supplierName: '',
          linkName: '',
          linkPhone: '',
          orderNo: '',
          orderId: '',
          sourceTypeName: '',
          sourceType: '',
          productList: [],
          pricingWay: ''
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
        return
      }
      this.$refs.orderListDialogRef.open();
    },
    //选择订单回调
    changeOrder(obj) {
      this.getPurchaseOrderDetail(obj.id);
    },
    //获取订单详情
    async getPurchaseOrderDetail(id) {
      this.loading = true;
      const data = await getpurchaseorderDetail(id);
      this.loading = false;
      if (data) {
        this.$nextTick(() => {
          let {
            partbId,
            partbName,
            partbTel,
            orderNo,
            id,
            partbLinkName,
            productList,
            sourceTypeName,
            sourceType,
            pricingWay
          } = data;
          if (productList && productList.length > 0) {
            productList.forEach((v) => {
              v.orderTotalCount = v.orderTotalCount || v.totalCount;
            });
          }
          this.form = Object.assign({}, this.form, {
            supplierId: partbId,
            supplierName: partbName,
            linkName: partbLinkName,
            linkPhone: partbTel,
            orderNo,
            orderId: id,
            sourceTypeName,
            sourceType,
            productList,
            pricingWay
          });
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(productList);
        });
      }
    },

    //发货单详情
    async getSendSaleOrderDetail(id) {
      this.businessId = id;

      this.loading = true;
      const data = await getPurchaseOutSourceSendDetailAPI(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() {
      return new Promise(async (resolve, reject) => {
        try {
          await this.getValidate();
          this.form.files = this.form.files || [];
          let commitData = Object.assign({}, this.form, {
            productList: this.$refs.inventoryTableref.getTableValue()
          });
          await updatePurchaseOutSourceSendAPI(commitData)
          resolve(true)

        } catch (error) {
          reject(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>
