<template>
  <div class="borderless">
    <div class="customer-head">
      <div class="customer-back">
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList">返回列表
        </el-button>
      </div>
      <div class="upper_right_button">
        <el-button type="primary"
                   size="small"
                   class="el-button--small-yh"
                   :disabled="true"
                   :loading="buttonLoading"
                   @click.stop="">请核
        </el-button>
        <el-button type="warning"
                   size="small"
                   class="el-button--small-yh"
                   :disabled="!form.id"
                   :loading="buttonLoading"
                   @click.stop="applySettlement('收费')">生成账单
        </el-button>
        <el-button type="warning"
                   size="small"
                   class="el-button--small-yh"
                   :disabled="!form.id"
                   :loading="buttonLoading"
                   @click.stop="applySettlement('申请')">退款
        </el-button>
        <el-button type="success"
                   size="small"
                   class="el-button--small-yh"
                   :disabled="true"
                   :loading="buttonLoading"
                   @click.stop="">复制新单
        </el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          size="small"
          :disabled="disabled"
          :loading="buttonLoading"
          @click="editCustomer"
        >{{form.id?'确认修改':'确认新增'}}
        </el-button>
      </div>
    </div>
    <div class="customer-main">
      <el-form :model="form" ref="form" label-width="130px">
        <containerTitle title="基础信息"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <el-row>
            <el-col v-for="(item, index) in basicData.column" :span="item.span?item.span:8" :key="index">
              <el-form-item :label="item.label" :prop="item.prop" :rules="item.rules">
                <el-date-picker v-if="item.type === 'datetime'" style="width: 100%;" v-model="form[item.prop]" size="small" type="date" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss"/>
                <el-select v-else-if="item.type === 'select'" style="width: 100%" v-model="form[item.prop]" size="small" placeholder="请选择" clearable filterable>
                  <el-option
                    v-for="(data, index) in item.dicData"
                    :key="index"
                    :label="data.label"
                    :value="data.value"
                  ></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'currency'" style="width: 100%"   v-model="form[item.prop]" size="small" placeholder="请选择" @change="currencyChange" clearable filterable>
                  <el-option v-for="(item,index) in currencyDic" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <selectComponent v-else-if="item.prop === 'corpId'" v-model="form[item.prop]" :configuration="configuration"/>
                <selectComponent v-else-if="item.prop === 'belongToCorpId'" v-model="form[item.prop]" :configuration="bConfiguration"/>
                <el-input type="age" v-else-if="item.type === 'unit'" v-model="form[item.prop]"  @change="downPaymentChange"  :disabled="item.disabled?true:false" size="small" autocomplete="off" placeholder="请输入">
                  <template slot="append">%</template>
                </el-input>
                <el-input type="textarea" v-else-if="(item.prop === 'orderRemark')" v-model="form[item.prop]"   size="small" autocomplete="off" placeholder="请输入"></el-input>
                <el-input type="age" v-else v-model="form[item.prop]" size="small" :disabled="item.disabled?true:false" autocomplete="off" placeholder="请输入"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
<!--        销售明细-->
        <containerTitle title="销售明细"></containerTitle>
        <basic-container >
          <avue-crud
            :option="importInventory"
            v-model="importInventoryForm"
            :data="importInventoryData"
            ref="importInventory"
            @row-save="rowSaveList"
            @row-update="rowUpdateList"
            @row-del="rowDelList"
            @selection-change="productSelection"
            @saveColumn="saveColumn"
          >
            <template slot-scope="{row}" slot="billNo">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.billNo"
                style="width: 90%"
                placeholder=" "
                size="small"
                @change="bingOut(row)"
              ></el-input>
              <span v-else>{{ row.billNo }}</span>
            </template>
            <template slot-scope="{row}" slot="orgOrderNo">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-select
                v-if="row.$cellEdit"
                style="width:90% !important;"
                v-model="row.orgOrderNo"
                placeholder=" "
                size="small"
                clearable
                filterable
              >
                <el-option
                  v-for="(item,index) in contractDic"
                  :key="index"
                  :label="item.orderNo"
                  :value="item.orderNo"
                ></el-option>
              </el-select>
              <span v-else>{{ row.orgOrderNo }}</span>
            </template>
            <template slot="price" slot-scope="{ row }">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.price"
                placeholder="请输入"
                style="width: 90%"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
                @input="priceChange(row)"
              ></el-input>
              <span v-else>{{ row.price }}</span>
            </template>
            <template slot="orderQuantity" slot-scope="{ row }">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.orderQuantity"
                style="width: 90%"
                placeholder="请输入"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              ></el-input>
              <span v-else>{{ row.orderQuantity }}</span>
            </template>
            <template slot="priceCategory" slot-scope="{row,index}">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <goods-select
                style="width:90% !important;"
                v-if="row.$cellEdit"
                v-model="row.priceCategoryNames"
                @valueName="(value) => valueName(value,row)"
                :configuration="itemConfiguration"
              >
              </goods-select>
              <span v-else>{{ row.priceCategoryNames }}</span>
            </template>
            <template slot="invoiceWeight" slot-scope="{ row }">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.invoiceWeight"
                style="width: 90%"
                placeholder="请输入"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
                @change="totalChange(row.invoiceWeight)"
              ></el-input>
              <span v-else>{{ row.invoiceWeight }}</span>
            </template>
            <template slot="billWeight" slot-scope="{ row }">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.billWeight"
                placeholder="请输入"
                style="width: 90%"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
                @input="billWeightChange(row)"
                @change="totalChange(row.billWeight)"
              ></el-input>
              <span v-else>{{ row.billWeight }}</span>
            </template>
            <template slot="amount" slot-scope="{ row }">
              <span v-if="row.$cellEdit" class="required_fields">*</span>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.amount"
                placeholder="请输入"
                style="width: 90%"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d).*$/, "$1.$2")'
              ></el-input>
              <span v-else>{{ row.amount }}</span>
            </template>
            <template slot="menuLeft" slot-scope="{ row }">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="newDetails"
              >录入明细</el-button>
              <el-button type="warning"
                         size="small"
                         :disabled="selection.length < 1"
                         @click="generateShipmentD"
              >生成发货单
              </el-button>
<!--              <el-button type="info"
                         size="small"
                         :disabled="importInventoryData.length < 1"
                         @click="payeeDialog = true"
              >收款记录
              </el-button>-->
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                type="text"
                size="small"
                @click="rowCell(row,index)"
              >{{ row.$cellEdit ? '修改完成' : '修改' }}
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="rowDelList(row,index)"
              >删除
              </el-button>
            </template>
          </avue-crud>
        </basic-container>
        <fee-info
          ref="feeInfo"
          :orderFeesList="orderFeesList"
          feeUrl=""
        />
        <upload-file
          ref="uploadFile"
          title="合同附件"
          :orderFilesList="orderFilesList"
          delUrl=""
        />
      </el-form>
    </div>
    <el-dialog
      title="收款记录"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="payeeDialog"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag>
      <basic-container>
        <avue-crud :option="importInventory"
                   :table-loading="payeeLoading"
                   :data="payeeData"
                   ref="applicationCrud"
                   @refresh-change="payeeRefreshChange"
                   :page.sync="payeePage"
                   @on-load="payeeOnLoad"></avue-crud>
      </basic-container>
      <span slot="footer" class="dialog-footer">
          <el-button @click="payeeDialog = false ">关 闭</el-button>
        </span>
    </el-dialog>
    <el-dialog
      append-to-body
      class="el-dialogDeep"
      :visible.sync="applySettlementDialog"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <apply-payment
        :billType="billType"
        :billData="billData"
        @choceFun="choceFun"
      >
      </apply-payment>
    </el-dialog>
  </div>
</template>

<script>
import importInventory from './config/importInventory.json';
import uploadList from './config/uploadList.json';
import advantageProject from "./config/advantageProject.json";
import optionTwoCost from "./config/mainListCost.json";
import {getDeptLazyTree,getDeptLazyTreeTwo, customerList} from "@/api/basicData/basicFeesDesc";
import commodity from "./config/commodity.json"
import { getList } from "@/api/basicData/configuration"
import {detailSaleList,
  submitData,
  generatePurchase,
  goodsListRemove,
  getOrgOrderNo,
  generateShipment} from "@/api/importTrade/salesContract"
import feeInfo from "@/components/fee-info/main";
import {getSysNo} from "@/api/importTrade/purchase";
import uploadFile from "@/components/upload-file/main";
import { contrastObj,contrastList } from "@/util/contrastData";
import _ from "lodash";
import option from "./config/mainList.json";
//账单组件
import ApplyPayment from "../../../components/finance/applyPayment";

export default {
  name: "detailsPage",
  props: {
    detailData: {
      type: Object
    }
  },
  data() {
    return {
      disabled: false,
      buttonLoading:false,
      dialogCommodity: false,
      applySettlementDialog:false,
      form: {},
      orderFeesList:[],
      orderFilesList:[],
      currencyDic:[],
      contractDic:[],
      selectKind:-1,
      billType:"",
      billData:{},
      configuration:{
        multipleChoices:false,
        multiple:false,
        disabled:false,
        searchShow:true,
        collapseTags:false,
        placeholder:'请点击右边按钮选择',
        dicData:[]
      },
      bConfiguration:{
        multipleChoices:false,
        multiple:false,
        disabled:false,
        searchShow:true,
        collapseTags:false,
        placeholder:'请点击右边按钮选择',
        dicData:[]
      },
      itemConfiguration:{
        multipleChoices:false,
        multiple:false,
        disabled:false,
        searchShow:true,
        collapseTags:false,
        placeholder:'请点击右边按钮选择',
        dicData:[]
      },
      //  基础信息
      basicData: {
        column: [
          {
            label: '系统号',
            prop: 'sysNo',
            disabled:true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户名称',
            span:16,
            prop: 'corpId',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '合同号',
            prop: 'orderNo',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '所属公司',
            prop: 'belongToCorpId',
            span: 16,
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '合同日期',
            prop: 'businesDate',
            type:'datetime',
            data: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '合同金额',
            prop: 'orderAmount',
            rules: [
              {
                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '业务员',
            prop: 'salesName',
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '销售单价',
            prop: 'salesPrice',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '币别',
            prop: 'currency',
          }, {
            label: '汇率',
            prop: 'exchangeRate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户首付日期',
            prop: 'advanceCollectionDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '首付比例',
            type:"unit",
            prop: 'downPayment',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '首付金额',
            prop: 'advancePayment',
            rules: [
              {
                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '已收金额',
            prop: 'settlmentAmount',
            disabled: true,
            rules: [
              {
                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                message: ' ',
                trigger: 'blur'
              },
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '发票重量',
            prop: 'invoiceWeight',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '码单重量',
            prop: 'billWeight',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '计划交期',
            prop: 'plannedDeliveryDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '提成标准',
            prop: 'commissionRate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: "备注",
            span: 24,
            prop: "orderRemark",
            mock: {
              type: 'county'
            }
          }
        ],
      },
      //收款记录
      payeeDialog:false,
      payeeLoading:false,
      payeeData:[],
      payeePage:{
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      // 导入库存配置
      importInventory: {},
      importInventoryForm: {},
      importInventoryData: [],
      dialogStock: false,
      // 其他费用
      advantageProject: advantageProject,
      advantageProjectData: [],
      advantageProjectForm: {},
      dialogCost: false,
      choiceData: false,
      treeOptionCost:{
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTree(parentId).then(res => {
            resolve(res.data.data.map(item => {
              return {
                ...item,
                leaf: !item.hasChildren
              }
            }))
          });
        },
        addBtn: false,
        menu: false,
        size: 'small',
        props: {
          labelText: '标题',
          label: 'title',
          value: 'value',
          children: 'children'
        }
      },
      // 导入商品配置
      optionGoods: [],
      loadingGoods: false,
      dataGoods:[],
      pageGoods:{
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      // 导入其他费用配置
      optionTwoCost: optionTwoCost,
      loadingCost: false,
      dataCost:[],
      pageCost:{
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      tableDataCost: [],
      treeDeptId: '',
      treeDeptIdCost: '',
      choiceIndex: '',
      // 合同上传数据
      uploadList: uploadList,
      // 合同数据
      bankOfDepositForm: {},
      tableData: [],
      commodityData: false,
      selection: [],
      //新旧数据对比
      oldForm:{},
      oldInventoryData:[],
      oldFeesList:[],
      oldFilesList:[],
    }
  },
  async created() {
    this.importInventory = await this.getColumnData(this.getColumnName(39), importInventory);
    //币别
    this.getWorkDicts("currency").then(res =>{
      this.currencyDic = res.data.data
    })
    if (this.detailData.id) {
      this.buttonLoading = true;
      let id = this.detailData.id.replace(/\"/g, "")
      detailSaleList(id).then(res => {
        this.form = res.data.data;
        this.oldForm = Object.assign({},res.data.data);
        this.configuration.dicData = this.form.corpName
        // this.bConfiguration.dicData = this.form.belongToCorpList
        if(this.form.orderItemsList){
          this.importInventoryData = this.form.orderItemsList
          this.oldInventoryData = this.deepClone(this.form.orderItemsList)
        }
        if(this.form.orderFeesList){
          this.orderFeesList = this.form.orderFeesList
          this.oldFeesList = this.deepClone(this.form.orderFeesList)
        }
        if(this.form.orderFilesList){
          this.orderFilesList = this.form.orderFilesList
          this.oldFilesList = this.deepClone(this.form.orderFilesList)
        }
      }).finally(()=>{
        this.buttonLoading = false
      })
    }else{
      this.$set(this.form,"currency","USD")
      this.$set(this.form,"exchangeRate",6.3686)
      //采购日期默认当天
      let date = new Date();
      let strDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
      this.$set(this.form,"businesDate",strDate)
    }
  },
  components: {
    ApplyPayment,
    feeInfo,
    uploadFile
  },
  methods: {
    valueName(value,row){
      this.$set(row,"priceCategory",value)
    },
    //首付比例  带出金额
    downPaymentChange(){
      if(this.form.orderAmount){
        this.$set(this.form,"advancePayment",_.multiply(this.form.orderAmount,(this.form.downPayment*0.01)).toFixed(2))
      }
    },
    //合计
    totalChange(){
      let invoiceList =  this.importInventoryData.map(item => {
        if(item.invoiceWeight){
          return parseFloat(item.invoiceWeight);
        }else return 0
      });
      let billList =  this.importInventoryData.map(item => {
        if(item.billWeight){
          return parseFloat(item.billWeight);
        }else return 0
      });
      this.$set(this.form,"invoiceWeight", invoiceList.reduce((n,m) => n + m))
      this.$set(this.form,"billWeight", billList.reduce((n,m) => n + m))
    },
    //汇率
    currencyChange(value){
      if(this.form.exchangeRate == 1 || this.form.exchangeRate == 6.368600 || this.form.exchangeRate == 7.174900){
        if(value == "CNY"){
          this.$set(this.form,"exchangeRate",1)
        }else if(value == "USD"){
          this.$set(this.form,"exchangeRate",6.368600)
        }else if(value == "EUR"){
          this.$set(this.form,"exchangeRate",7.174900)
        }
      }
    },
    //单价
    priceChange(row) {
      if (!row.price) {
        row.price = "";
        row.amount = 0
      } else {
        row.amount = _.multiply(row.billWeight, row.price).toFixed(2);
      }
    },
    //数量
    billWeightChange(row) {
      if (!row.billWeight) {
        row.billWeight = "";
        row.amount = 0
      } else {
        row.amount =_.multiply(row.billWeight,row.price).toFixed(2);
      }
    },
    beforeBillData(bool,type){
      this.billType = type
      this.billData = {
        srcOrderno:this.form.orderNo,
        itemType:"销售",
        billNoList: this.importInventoryData.map(item =>{return item.billNo}),
        corpsName:this.form.corpName,
        corpId:this.form.corpId,
        accDate:this.form.businesDate,
        currency:this.form.currency,
        exchangeRate:this.form.exchangeRate,
        srcParentId:this.form.id,
      }
      if(type){ //申请货款
        this.billData.srcId = -1
      }
    },
    //申请结算
    applySettlement(type){
      if(contrastObj(this.form,this.oldForm) || contrastList(this.importInventoryData,this.oldInventoryData)
        || contrastList(this.orderFeesList,this.oldFeesList) || contrastList(this.orderFilesList,this.oldFilesList)
      ){
        this.$confirm("您已改动数据,是否先保存在进行操作!", {
          confirmButtonText: "保存",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer();
        })
      }else{
        this.beforeBillData(true,type)
        this.applySettlementDialog = true;
        // this.$confirm("是否确认申请结算!", {
        //   confirmButtonText: "确定",
        //   cancelButtonText: "取消",
        //   type: "warning"
        // }).then(() => {
        //   if(this.$store.getters.takeStatus){
        //     this.$alert("结算页面已存在,请关闭收货单再进行操作", "温馨提示", {
        //       confirmButtonText: "确定",
        //       type: 'warning',
        //       callback: action => {
        //       }
        //     });
        //   }else{
        //     //关闭一下存在的列表页  跳转
        //     this.$router.$avueRouter.closeTag('/receipt_settle');
        //     this.$router.push({
        //       path: "/receipt_settle",
        //       query: {params: this.form.id},
        //     });
        //   }
        // })
      }
    },
    //修改
    editCustomer(status) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let orderFeesList = this.$refs.feeInfo.submitData();
          for (let i = 0; i < orderFeesList.length; i++) {
            if (orderFeesList[i].corpId == null) {
              return this.$message.error(`请输入第${i + 1}行的结算中心`);
            }
            if (orderFeesList[i].price == 0) {
              return this.$message.error(`请正确输入第${i + 1}行的价格`);
            }
            if (orderFeesList[i].orderQuantity == 0) {
              return this.$message.error(`请正确输入第${i + 1}行的件数`);
            }
          }
          let orderUpLoadList = this.$refs.uploadFile.submitData();

          for (let j = 0; j < this.importInventoryData.length; j++) {
            if (this.importInventoryData[j].billNo === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的提单号`);
            }
            if (this.importInventoryData[j].orgOrderNo === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的合同号`);
            }
            if (this.importInventoryData[j].priceCategory === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的货品物种`);
            }
            if (this.importInventoryData[j].orderQuantity === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的件数`);
            }
            if (this.importInventoryData[j].invoiceWeight === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的发票重量`);
            }
            if (this.importInventoryData[j].billWeight === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的码单重量`);
            }
            if (this.importInventoryData[j].price === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的单价`);
            }
            if (this.importInventoryData[j].amount === (null || "")) {
              return this.$message.error(`请输入销售明细第${j + 1}行的发票金额`);
            }
          }
          this.buttonLoading = true;

          if(this.importInventoryData.length !== 0){
            //提单号
            this.form.billNo = this.importInventoryData.map(item =>{return item.billNo}).join(",")

            //发票金额合计  存入主表
            let invoiceList =  this.importInventoryData.map(item => {
              if(item.amount){
                return parseFloat(item.amount);
              }else return 0
            });
            this.form.invoiceAmount = invoiceList.reduce((n,m) => n + m)
          }


          let submitDto = {
            ...this.form,
            orderItemsList: this.importInventoryData,
            orderFeesList: orderFeesList,
            orderUpLoadList:orderUpLoadList,
          };

          submitData(submitDto).then(res => {
            if(res.data.success){
              this.$message.success("操作成功！")
              detailSaleList(res.data.data.id).then(res => {
                this.form = res.data.data;
                this.oldForm = Object.assign({},res.data.data);
                this.configuration.dicData = this.form.corpName
                // this.bConfiguration.dicData = this.form.belongToCorpList
                this.importInventoryData = this.form.orderItemsList
                if(this.form.orderItemsList){
                  this.importInventoryData = this.form.orderItemsList
                  this.oldInventoryData = this.deepClone(this.form.orderItemsList)
                }
                if(this.form.orderFeesList){
                  this.orderFeesList = this.form.orderFeesList
                  this.oldFeesList = this.deepClone(this.form.orderFeesList)
                }
                if(this.form.orderFilesList){
                  this.orderFilesList = this.form.orderFilesList
                  this.oldFilesList = this.deepClone(this.form.orderFilesList)
                }
              }).finally(()=>{
                this.buttonLoading = false
              })
            }
          })
          if(status === true){
            this.$emit("goBack");
          }
        } else {
          return false;
        }
      });
    },
    choceFun(){
      this.applySettlementDialog  = false
    },
    //刷新
    payeeRefreshChange(){

    },
    //申请记录
    payeeOnLoad(){

    },
    //商品选中触发
    productSelection(selection){
      this.selection = selection
    },
    //生成发货单
    generateShipmentD(){
      let id =   this.selection.map(item=>{
        return  item.id ? true : false
      })
      if(id.findIndex(item => item != true) == -1){
        const params = {
          id:this.form.id,
          orderItemIds:this.selection.map(i=>{return i.id})
        }
        if(contrastObj(this.form,this.oldForm) || contrastList(this.importInventoryData,this.oldInventoryData)
          || contrastList(this.orderFeesList,this.oldFeesList) || contrastList(this.orderFilesList,this.oldFilesList)
        ){
          this.$confirm("您已改动数据,是否先保存在进行操作!", {
            confirmButtonText: "保存",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            this.editCustomer();
          })
        }else{
          if(this.$store.getters.goStatus){
            this.$alert("发货单已存在,请保存发货单再进行操作", "温馨提示", {
              confirmButtonText: "确定",
              type: 'warning',
              callback: action => {
              }
            });
          }else{
            this.$router.push({
              path: "/importTrade/invoice/index",
              query: {form: params},
            });
            // generateShipment(params).then(res=>{
            //   this.$router.push({
            //     path: "/importTrade/invoice/index",
            //     query: {form: JSON.stringify(res.data.data)},
            //   });
            // })
          }
        }
      }else{
        this.$confirm("列表内存在新录入数据,是否先保存此数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer();
        })
      }
    },
    //提单号带出合同号
    bingOut(row){
      getOrgOrderNo(row.billNo).then(res =>{
        if(res.data.length != 0){
          this.contractDic = res.data;
          row.orgOrderNo =  res.data[0].orderNo
          row.itemId = res.data[0].itemId;
          row.priceCategoryNames  = res.data[0].itemName[0].cname
          row.priceCategory  = res.data[0].itemName[0].id
        }else{
          this.$message.warning("无此提单号记录！");
          this.contractDic  = [];
          row.orgOrderNo =  ''
          row.itemId = ''
            row.priceCategoryNames  = ''
          row.priceCategory  = ''
        }
      }).catch(()=>{
        row.orgOrderNo = ''
      })
    },
    //商品明细导入
    newDetails(){
      const params = {
        price:this.form.salesPrice
      }
      this.$refs.importInventory.rowCellAdd(params);
    },
    //商品编辑
    rowCell(row, index) {
      // row.$cellEdit = !row.$cellEdit
      this.$refs.importInventory.rowCell(row, index)
    },
    //其他费用编辑
    rowCellTwo(row, index) {
      this.$refs.crudProject.rowCell(row, index)
    },
    //其他费用新增触发
    costIncrease(){
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //费用查询
    onLoadCost(page, params = {}) {
      this.loadingCost = true;
      let queryParams = Object.assign({}, params, {pageSize: page.pageSize, pageNum: page.currentPage,parentId:0,feesTypeId:this.treeDeptIdCost})
      customerList(queryParams).then(res => {
        const data = res.data.data;
        this.pageCost.total = data.total;
        this.dataCost = data.records;
        this.loadingCost = false;
      });
    },
    rateChange(row) {
      if (row >= 100) {
        this.$set(this.form,"exchangeRate", 0)
        this.$message.error("汇率不能超过100%");
      }
    },
    //选择货物品种
    choice(row){
      this.dialogVisible = true;
      this.selectKind = row.$index;
    },
    //新增明细保存触发
    rowSaveList(row, done, loading){
      // this.advantageProjectData.push(row)
      done()
    },
    //修改明细触发
    rowUpdateList(row, index, done, loading) {
      done(row);
    },
    //删除商品明细触发
    rowDelList(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id){
          goodsListRemove(row.id).then(res=>{
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.importInventoryData.splice(index, 1);
          })
        }else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.importInventoryData.splice(index, 1);
        }
      }).finally(()=>{
        this.totalChange()
      })
    },
    backToList() {
      if(contrastObj(this.form,this.oldForm) || contrastList(this.importInventoryData,this.oldInventoryData)
        || contrastList(this.orderFeesList,this.oldFeesList) || contrastList(this.orderFilesList,this.oldFilesList)
      ){
        this.$confirm("是否保存当前页面？", "提示", {
          confirmButtonText: "保存",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.editCustomer(true)
        }).catch(()=>{
          this.$emit("goBack");
        })
      }else{
        this.$emit("goBack");
      }
    },
    //列保存触发
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(39),
        this.importInventory
      );
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.importInventory.$refs.dialogColumn.columnBox = false;
      }
    },
  },
}
</script>

<style scoped lang="scss">
.required_fields{
  color: #F56C6C;
  display:inline-block;
  width: 7%
}

.upper_right_button{
  display: flex;
  position: fixed;
  right: 12px;
  top: 47px;
}

::v-deep .el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item__content{
  line-height: 32px;
}
</style>
