<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>
      <el-button type="primary"
                 class="el-button--small-yh add-customer-btn-three"
                 :disabled="true"
                 @click.stop="">请核
      </el-button>
      <el-button type="success"
                 class="el-button--small-yh add-customer-btn-two"
                 :disabled="true"
                 @click.stop="">复制新单
      </el-button>
      <el-button
        class="el-button--small-yh add-customer-btn"
        type="primary"
        :disabled="disabled"
        @click="editCustomer"
      >{{form.id?'确认修改':'确认新增'}}
      </el-button>
    </div>
    <div style="margin-top: 60px">
      <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="datetime" 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"/>
                <port-info  v-else-if="(item.prop === 'portOfDestination' || item.prop === 'portOfLoad'  )"  v-model="form[item.prop]"></port-info>
                <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 style="margin-bottom: 10px">
          <avue-crud
            :option="importInventory"
            v-model="importInventoryForm"
            :data="importInventoryData"
            ref="importInventory"
            @row-save="rowSaveList"
            @row-update="rowUpdateList"
            @row-del="rowDelList"
            @selection-change="productSelection"
          >
            <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 }">
              <el-input
                v-if="row.$cellEdit"
                v-model="row.price"
                placeholder="请输入"
                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")'
                @input="quantityChange(row)"
              ></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>
              <el-input
                v-if="row.$cellEdit"
                v-model="row.priceCategoryNames"
                size="small"
                placeholder="请点击右侧按钮选择"
                :disabled="true"
                style="width: 63%"
              ></el-input>
              <el-button v-if="row.$cellEdit" size="small" icon="el-icon-search" @click="choice(row)"></el-button>
              <span v-else>{{ row.priceCategoryNames }}</span>
            </template>
            <template slot="invoiceWeight" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model="row.invoiceWeight"
                placeholder="请输入"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
                @input="totalChange(row.invoiceWeight)"
              ></el-input>
              <span v-else>{{ row.invoiceWeight }}</span>
            </template>
            <template slot="billWeight" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model="row.billWeight"
                placeholder="请输入"
                size="small"
                oninput='this.value=this.value.replace(/[^(\d.)]/g,"").replace(/^(\d+)\.(\d\d\d\d\d\d).*$/, "$1.$2")'
                @input="totalChange(row.billWeight)"
              ></el-input>
              <span v-else>{{ row.billWeight }}</span>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="newDetails"
              >录入明细</el-button>
              <el-button type="primary"
                         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>
            </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="dialogVisible"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false">
      <el-row style="height: 0;">
        <el-col :span="5">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwo"
                       :table-loading="loading"
                       :data="data"
                       ref="crud"
                       @refresh-change="refreshChange"
                       @selection-change="selectionChange"
                       :page.sync="page"
                       @on-load="onLoad">

            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
           <el-button type="primary" @click="commodityConfirm" v-if="selectKind != -1"  :disabled="tableData.length !== 1">确定</el-button>
          <el-button type="primary" @click="importGoods" v-if="commodityData !== true  && selectKind == -1" :disabled="tableData.length !== 1" >导入</el-button>
          <el-button type="primary" @click="importChoice" v-if="commodityData === true  && selectKind == -1"
                     :disabled="tableData.length !== 1">导入</el-button>
        </span>
    </el-dialog>
    <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>
  </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,
  goodsListRemove,
  feesListRemove,
  updateListRemove,
  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";

export default {
  name: "detailsPage",
  props: {
    detailData: {
      type: Object
    }
  },
  data() {
    return {
      disabled: false,
      dialogCommodity: false,
      dialogVisible: false,
      form: {},
      orderFeesList:[],
      orderFilesList:[],
      currencyDic:[],
      contractDic:[],
      selectKind:-1,
      configuration:{
        multipleChoices:false,
        multiple:false,
        disabled:false,
        searchShow:true,
        collapseTags:false,
        placeholder:'请点击右边按钮选择',
        dicData:[]
      },
      bConfiguration:{
        multipleChoices:false,
        multiple:false,
        disabled:false,
        searchShow:false,
        collapseTags:false,
        placeholder:'请点击右边按钮选择',
        dicData:[]
      },
      //  基础信息
      basicData: {
        column: [
          {
            label: '系统号',
            prop: 'sysNo',
            disabled:true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '订单号',
            prop: 'orderNo',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '订单日期',
            prop: 'businesDate',
            type:'datetime',
            data: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '业务员',
            prop: 'salesName',
            // type:'select',
            dicData: [],
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '客户名称',
            prop: 'corpId',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '发票号（PI）',
            prop: 'proformInvoice',
            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: 'settlmentAmount',
            rules: [
              {
                pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '起运港',
            prop: 'portOfLoad',
          },
          {
            label: '目的港',
            prop: 'portOfDestination',
          },
          {
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户首付日期',
            prop: 'advanceCollectionDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '首付比例',
            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: 'plannedDeliveryDate',
            type: 'datetime',
            rules: [
              {
                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: 'salesPrice',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '币别',
            prop: 'currency',
          }, {
            label: '汇率',
            prop: 'exchangeRate',
            disabled: true,
            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: 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'
        }
      },
      treeOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          getDeptLazyTreeTwo(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: {},

      optionTwo: commodity,
      loading: false,
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      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) {
      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)
        }
      })
    }
  },
  components: {
    feeInfo,
    uploadFile
  },
  methods: {
    //合计
    totalChange(){
      let invoiceList =  this.importInventoryData.map(item => {
        if(!item.invoiceWeight){
          item.invoiceWeight = 0
        }
        return parseFloat(item.invoiceWeight);
      });
      let billList =  this.importInventoryData.map(item => {
        if(!item.billWeight){
          item.billWeight = 0
        }
        return parseFloat(item.billWeight);
      });
      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.orderAmount){
        if(value === "人民币"){
          this.form.exchangeRate = 1
          // this.form.rmbAmount = this.form.orderAmount
        }else{
          this.form.exchangeRate = 6.3843
          // this.form.rmbAmount =  _.multiply(this.form.orderAmount, 6.3843)
        }
      }
    },
    //单价
    priceChange(row) {
      if (!row.price) {
        row.price = "";
        row.amount = 0
      } else {
        row.amount = _.multiply(row.orderQuantity, row.price).toFixed(2);
      }
    },
    //件数
    quantityChange(row) {
      if (!row.orderQuantity) {
        row.orderQuantity = "";
        row.amount = 0
      } else {
        row.amount =_.multiply(row.orderQuantity,row.price).toFixed(2);
      }
    },
    editCustomer(status) {
      this.$refs["form"].validate((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 === "") {
            return this.$message.error(`请输入销售明细第${j + 1}行的提单号`);
          }
          if (this.importInventoryData[j].orgOrderNo === "") {
            return this.$message.error(`请输入销售明细第${j + 1}行的合同号`);
          }
          if (this.importInventoryData[j].priceCategory === "") {
            return this.$message.error(`请输入销售明细第${j + 1}行的货品物种`);
          }
          if (this.importInventoryData[j].orderQuantity === "") {
            return this.$message.error(`请输入销售明细第${j + 1}行的件数`);
          }
          if (this.importInventoryData[j].orderQuantity == 0) {
            return this.$message.error(`销售明细第${j + 1}行的件数不能为0`);
          }
        }
        if (valid) {
          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)
                }
              })
            }
          })
          if(status === true){
            this.$emit("goBack");
          }
        } else {
          return 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{
            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){
          this.contractDic = res.data;
          row.orgOrderNo =  res.data[0].orderNo
          row.cntrNo =  res.data[0].cntrNo
        }
      }).catch(()=>{
        row.orgOrderNo = ''
      })
    },
    //商品明细导入
    newDetails(){
      const params ={
        billWeight:0,
        invoiceWeight:0,
        price:0,
        orderQuantity:0,
      }
      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;
      });
    },
    //商品列表查询
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        if (this.page.total) {
          this.option.height = window.innerHeight - 350;
        } else {
          this.option.height = window.innerHeight - 305;
        }
      }).finally(()=>{
        this.loading = 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;
    },
    //选择货品
    commodityConfirm(){
      if(this.tableData){
        this.importInventoryData[this.selectKind].priceCategory = this.tableData[0].id;
        this.importInventoryData[this.selectKind].itemId = this.tableData[0].id;
        this.$set(this.importInventoryData[this.selectKind],'priceCategoryNames',this.tableData[0].cname)
        this.dialogVisible = !this.dialogVisible
        this.selectKind = -1
      }
    },
    //刷新触发
    refreshChange() {
      this.treeDeptId = '';
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //选中触发
    selectionChange(list) {
      this.tableData = list
    },
    //确认导入触发
    importGoods() {
      if (this.tableData.length > 0) {
        for (let item in this.tableData) {
          const params ={
            priceCategory:this.tableData[item].code,
            priceCategoryNames:this.tableData[item].cname,
            itemId:this.tableData[item].id,
            cname:this.tableData[item].cname,
            orderQuantity:0,
            price:0,
            amount:0.00,
          }
          this.$refs.importInventory.rowCellAdd(params);
          this.$refs.importInventory.rowCell(params,this.importInventoryData.length - 1)
        }
      }
      this.tableData = []
      this.dialogVisible = false
    },
    //导入页左商品类型查询
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //导入商品触发
    importChoice() {
      if (this.tableData.length === 1) {
        this.importInventoryData[this.choiceIndexT].cname = this.tableData[0].cname
        this.importInventoryData[this.choiceIndexT].code = this.tableData[0].code
        this.importInventoryData[this.choiceIndexT].typeno = this.tableData[0].typeno
        this.importInventoryData[this.choiceIndexT].specificationAndModel = this.tableData[0].specificationAndModel
        this.importInventoryData[this.choiceIndexT].itemId = this.tableData[0].id
        this.importInventoryData[this.choiceIndexT].priceCategory = this.tableData[0].goodsTypeName
      }
      this.dialogVisible = !this.dialogVisible
      this.commodityData = false
    },
    //新增明细保存触发
    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);
        }
      })
    },
    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.crud.$refs.dialogColumn.columnBox = false;
      }
    },
  },
}
</script>

<style scoped lang="scss">
.customer-head {
  position: fixed;
  top: 105px;
  width: 100%;
  margin-left: -10px;
  height: 62px;
  background: #ffffff;
  box-shadow: 0 4px 12px 0px rgba(232, 232, 235, 1);
  z-index: 999;
  /* display: flex;
  justify-content: left; */
}
.add-customer-btn-two {
  position: fixed;
  right: 150px;
  top: 115px;
}
.customer-back {
  cursor: pointer;
  line-height: 62px;
  font-size: 16px;
  color: #323233;
  font-weight: 400;
}
.required_fields{
  color: #F56C6C;
  display:inline-block;
  width: 7%
}
.add-customer-btn-three {
  position: fixed;
  right: 266px;
  top: 115px;
}

.add-customer-btn {
  position: fixed;
  right: 36px;
  top: 115px;
}

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

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