<template>
  <div class="borderless" v-loading="pageLoading">
    <div class="customer-head">
      <div class="customer-back">
        <!--        <i class="back-icon el-icon-arrow-left"></i><i style="font-style:normal">返回管理列表</i>-->
        <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left"
                   @click="backToList">返回列表
        </el-button>
      </div>
      <div class="add-customer-btn">
        <el-button
          v-if="detailData.seeDisabled"
          size="small"
          @click="detailData.seeDisabled = false"
          type="primary"
        >编辑</el-button>
        <el-button
          class="el-button--small-yh"
          type="warning"
          :disabled="detailData.seeDisabled"
          size="small"
          @click="applySettlement"
        >生成账单</el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          :disabled="detailData.seeDisabled"
          size="small"
          @click="saveSell"
        >生成采购单</el-button>
        <el-button
          class="el-button--small-yh"
          type="success" @click="copyOrder"
          size="small"
          :disabled="detailData.seeDisabled || !this.form.id">
          复制新单
        </el-button>
        <el-button
          class="el-button--small-yh"
          type="primary"
          :disabled="disabled || detailData.seeDisabled"
          :loading="saveLoading"
          size="small"
          @click="editCustomer(false)"
        >{{ form.id ? '确认修改' : '确认新增' }}
        </el-button>
      </div>
    </div>
    <div class="customer-main">
      <el-form :model="form" ref="form" label-width="130px" class="demo-ruleForm">
        <containerTitle title="基础资料"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <el-row>
            <el-col v-for="(item,index) in basicData.column" :key="index" :span="item.span?item.span:8">
              <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" :disabled="detailData.seeDisabled"/>
                <el-date-picker v-else-if="item.type === 'date'" style="width: 100%;" v-model="form[item.prop]"
                                size="small" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :disabled="detailData.seeDisabled"/>
                <selectComponent v-else-if="item.prop === 'corpId'" v-model="form[item.prop]"
                                 :configuration="configuration" style="width: 100%" :disabled="detailData.seeDisabled"
                                 @getRow="getCorpRow"
                />
<!--                所属公司带出银行信息-->
                <selectComponent v-else-if="item.prop === 'belongToCorpId'"
                                 v-model="form[item.prop]" :configuration="companyConfiguration"
                                 style="width: 100%"
                                 :disabled="detailData.seeDisabled"
                                 @returnBack="returnBack"/>
<!--                生产工厂-->
                <selectComponent v-else-if="item.prop === 'productionPlant'"
                                 v-model="form[item.prop]" :configuration="plantConfiguration"
                                 style="width: 100%"
                                 :disabled="detailData.seeDisabled"
                                 @getRow="getPlantRow"/>
                <el-select v-else-if="item.prop === 'paymentType'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled">
                  <el-option v-for="(item,index) in paymentOption" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'banks'"
                           v-model="form[item.prop]" placeholder="请选择"
                           clearable
                           filterable
                           allow-create
                           default-first-option
                           size="small"
                           style="width: 100%;"
                           @change="banksChange"
                           :disabled="detailData.seeDisabled">
                  <el-option v-for="(item,index) in bankList" :key="index" :label="item.accountNo" :value="item.accountNo"></el-option>
                </el-select>
                <el-input
                  v-else-if="item.type == 'number'"
                  placeholder="请输入"
                  v-input-limit="2"
                  size="small"
                  :disabled="item.disabled || detailData.seeDisabled"
                  v-model="form[item.prop]"
                />
                <el-input type="textarea" v-else-if="item.type === 'textarea'" v-model="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled"></el-input>
                <el-input type="age" v-else v-model="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
        <containerTitle title="发货信息"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <el-row>
            <el-col v-for="(item,index) in contactInformation.column" :key="index" :span="item.span?item.span:8">
              <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" :disabled="item.disabled || detailData.seeDisabled"/>
                <el-date-picker v-else-if="item.type === 'date'" style="width: 100%;" v-model="form[item.prop]"
                                size="small" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :disabled="detailData.seeDisabled"/>
                <el-input
                  v-else-if="(item.prop === 'advancePayment') || (item.prop === 'settlmentAmount') || (item.prop === 'overPayment')"
                  v-model="form[item.prop]" size="small" autocomplete="off"
                  @change="computedCost"
                  :disabled="detailData.seeDisabled"
                  v-input-limit="2"
                ></el-input>
                <el-select v-else-if="item.prop === 'orderStatus'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled">
                  <el-option v-for="(item,index) in statusOption" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <el-input type="age" v-else-if="item.prop === 'grossProfitRate'" v-model="form[item.prop]" size="small" autocomplete="off" placeholder="请输入" :disabled="detailData.seeDisabled" v-input-limit="2">
                  <template   slot="append">%</template>
                </el-input>
                <el-input
                  v-else-if="item.type == 'number'"
                  placeholder="请输入"
                  v-input-limit="2"
                  size="small"
                  :disabled="item.disabled || detailData.seeDisabled"
                  v-model="form[item.prop]"
                />
                <el-input type="textarea" v-else-if="item.type === 'textarea'" v-model="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled"></el-input>
                <el-input v-else type="age" v-model="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
        <containerTitle title="商品信息"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <avue-crud
              :option="customerContact"
              v-model="contactsForm"
              :data="contactsData"
              ref="crudContact"
              @row-save="rowSave"
              @row-click="handleRowClick"
              @row-update="rowUpdate"
              @selection-change="productSelection"
              @row-del="rowDel"
              @saveColumn="saveColumn('goods')"
          >
            <template slot="corpId" slot-scope="{ row, index }">
              <customer-dialog
                v-if="row.$cellEdit"
                v-model="row.corpName"
                :cropIndex="index"
                @getcorpId="getcorpId"
              ></customer-dialog>
              <span v-else>{{ row.corpName }}</span>
            </template>
            <template slot="code" slot-scope="{row,index}">
              <el-button
                type="text"
                size="mini"
                style="padding:4px 10px;float:left"
                @click="commodityChoice(row)"
                :disabled="detailData.seeDisabled || !row.$cellEdit">选择</el-button>
              <span>{{ row.code }}</span>
            </template>
            <template slot="purchaseAmount" slot-scope="{ row }">
              <el-select
                v-if="row.$cellEdit"
                v-model="row.purchaseAmount"
                @focus="getPurchasePrice(row)"
                allow-create
                filterable
                v-input-limit="2"
              >
                <el-option
                  v-for="(item, index) in purchasePriceOption"
                  :key="index"
                  :label="item.purchasePrice"
                  :value="item.purchasePrice"></el-option>
              </el-select>
              <span v-else>{{ row.purchaseAmount }}</span>
            </template>
            <template slot="price" slot-scope="{ row }">
              <el-select
                v-if="row.$cellEdit"
                v-model="row.price"
                @focus="getMarketPrice(row)"
                @input="priceChange(row)"
                allow-create
                filterable
                v-input-limit="2"
              >
                <el-option
                  v-for="(item, index) in salesPriceOtion"
                  :key="index"
                  :label="item.salesPrice"
                  :value="item.salesPrice"></el-option>
              </el-select>
              <span v-else>{{ row.price }}</span>
            </template>
            <template slot="orderQuantity" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model="row.orderQuantity"
                oninput='this.value=this.value.replace(/[^\-?\d.]/g,"").replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3")'
                size="small"
                @input="quantityChange(row)"
              ></el-input>
              <span v-else>{{ row.orderQuantity }}</span>
            </template>
            <template slot="cname" slot-scope="{ row }">
              <goods-select v-if="row.$cellEdit" v-model="row.cname" @getRow="getGoodsRow($event, row)"
                               :configuration="goodsConfiguration" @receiveList="receiveGoodList" @returnRow="getRow($event, row)"/>
              <span v-else>
                <span v-for="item in goodsConfiguration.dicData" v-if="item.cname == row.cname">{{ item.cname }}</span>
              </span>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                  type="text"
                  size="small"
                  @click="rowCell(row,index)"
                  :disabled="detailData.seeDisabled"
              >{{ row.$cellEdit ? '保 存' : '修 改' }}
              </el-button>
              <el-button
                size="small"
                icon="el-icon-delete"
                type="text"
                @click="rowDel(row, index)"
                :disabled="detailData.seeDisabled"
                v-if="!row.$cellEdit"
              >删 除</el-button>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="commoditySelection"
                         :disabled="detailData.seeDisabled">录入明细
              </el-button>
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="policy"
                         :disabled="detailData.seeDisabled">政策
              </el-button>
              <el-button type="warning"
                         icon="el-icon-plus"
                         size="small"
                         :disabled="selection.length < 1 || detailData.seeDisabled"
                         @click="getShipmentD">生成发货单
              </el-button>
              <el-button type="info"
                         :size="size"
                         icon="el-icon-printer"
                         :disabled="detailData.seeDisabled"
                         @click.stop="openReport()"
              >报 表</el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-download"
                @click="downloadHandle"
              >下载模板</el-button>
              <el-upload
                :action="baseURL"
                :headers="headers"
                :disabled="detailData.seeDisabled"
                :on-progress="uploading"
                :show-file-list=false
                accept=".xls,.xlsx"
                multiple
                :on-success="importTemplate"
                style="float: right"
              >
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-upload"
                >导 入</el-button>
              </el-upload>
            </template>
          </avue-crud>
        </basic-container>
        <containerTitle title="费用明细"></containerTitle>
        <basic-container style="margin-bottom: 10px">
          <avue-crud
              :option="advantageProject"
              v-model="advantageProjectForm"
              :data="advantageProjectData"
              ref="crudProject"
              @row-save="rowSaveProject"
              @row-update="rowUpdateProject"
              @row-del="rowDelProject"
              @saveColumn="saveColumn('fees')"
          >
            <template slot="code" slot-scope="{row,index}">
              <el-button type="text" size="mini" style="padding:4px 10px;float:left" @click="choice(row)" :disabled="detailData.seeDisabled || !row.$cellEdit">选择</el-button>
              <span>{{ row.code }}</span>
            </template>
            <template slot="corpId" slot-scope="{ row }">
              <selectComponent v-if="row.$cellEdit" v-model="row.corpId"
                               :configuration="configuration" @receiveList="receiveList"/>
              <span v-else>
                <span v-for="item in configuration.dicData" v-if="item.id == row.corpId">{{ item.cname }}</span>
              </span>
            </template>
            <template slot="amount" slot-scope="{ row }">
              <el-input v-if="row.$cellEdit" v-model="row.amount"
                        size="small" v-input-limit="2"
              ></el-input>
              <span v-else>{{ row.amount }}</span>
            </template>
            <template slot="settlmentAmount" slot-scope="{ row }">
              <el-input v-if="row.$cellEdit" v-model="row.settlmentAmount"
                        size="small" v-input-limit="2"
              ></el-input>
              <span v-else>{{ row.settlmentAmount }}</span>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                  type="text"
                  size="small"
                  @click="rowCellTwo(row,index)"
                  :disabled="detailData.seeDisabled"
              >{{ row.$cellEdit ? '保 存' : '修 改 ' }}
              </el-button>
              <el-button
                size="small"
                icon="el-icon-delete"
                type="text"
                @click="rowDelProject(row, index)"
                :disabled="detailData.seeDisabled"
                v-if="!row.$cellEdit"
              >删 除</el-button>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="costIncrease"
                         :disabled="detailData.seeDisabled"
              >录入明细
              </el-button>
            </template>
          </avue-crud>
        </basic-container>
        <containerTitle title="附件上传"></containerTitle>
        <basic-container style="margin-bottom: 40px">
          <avue-crud
              :option="bankOfDeposit"
              v-model="bankOfDepositForm"
              :data="bankOfDepositData"
              @row-save="rowSaveBankOfDeposit"
              @row-update="rowUpdateBankOfDeposit"
              @row-del="rowDelBankOfDeposit"
              :upload-after="uploadAfter"
              ref="uploadCrud"
          >
            <template slot="menuLeft">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="small"
                @click.stop="$refs.uploadCrud.rowAdd()"
                :disabled="detailData.seeDisabled"
              >上传</el-button
              >
            </template>
            <template slot="menu" slot-scope="{ row, index }">
              <el-button
                size="small"
                icon="el-icon-edit"
                type="text"
                @click="$refs.uploadCrud.rowEdit(row, index)"
                :disabled="detailData.seeDisabled"
              >编 辑</el-button
              >
              <el-button
                size="small"
                icon="el-icon-delete"
                type="text"
                @click="rowDelBankOfDeposit(row, index)"
                :disabled="detailData.seeDisabled"
              >删 除</el-button
              >
            </template>
          </avue-crud>
        </basic-container>
      </el-form>
    </div>
    <el-dialog
        title="导入商品"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="dialogVisible"
        width="80%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        @close="closeGoods">
      <el-row :style="{height: rowHeight}">
        <el-col :span="5" style="height: 100%;overflow-y: auto">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOption" :data="treeDataGoods" @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"
                       @search-change="goodsSearch"
                       :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="importGoods" v-if="commodityData !== true">导入</el-button>
          <el-button type="primary" @click="importChoice" v-if="commodityData === true"
                     :disabled="tableData.length !== 1">导入</el-button>
        </span>
    </el-dialog>

    <el-dialog
        title="导入政策"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="policyDialog"
        width="80%"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        @close="closePolicy">
      <el-row :style="{height: rowHeight}">
        <el-col :span="5" style="height: 100%;overflow-y: auto">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="policyOption" :data="treeDataPolicy" @node-click="policyNodeClick"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <containerTitle title="特价促销"></containerTitle>
          <basic-container style="margin-bottom: 10px">
            <avue-crud :option="optionPolicy"
                       :table-loading="loadingPolicy"
                       :data="dataPolicy"
                       ref="crud"
                       @selection-change="selectionChangePolicy"
                       :page.sync="pagePolicy">
            </avue-crud>
          </basic-container>
          <containerTitle title="买赠促销"></containerTitle>
          <basic-container>
            <avue-crud
                :option="customerBuyFree"
                :data="contactsDataBuyFree"
                @selection-change="selectionChangePolicyTwo"
                ref="crudContactE">
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="policyDialog = false">取 消</el-button>
          <el-button type="primary" @click="importPolicy">导入</el-button>
        </span>
    </el-dialog>

    <el-dialog
        title="导入费用"
        append-to-body
        class="el-dialogDeep"
        :visible.sync="dialogCost"
        width="80%"
        top="8vh"
        :close-on-click-modal="false"
        :destroy-on-close="true"
        :close-on-press-escape="false"
        @close="closeFees">
      <el-row :style="{height: rowHeight}">
        <el-col :span="5" style="height: 100%;overflow-y: auto">
          <div>
            <el-scrollbar>
              <basic-container>
                <avue-tree :option="treeOptionCost" :data="treeData" @node-click="nodeClickCost"/>
              </basic-container>
            </el-scrollbar>
          </div>
        </el-col>
        <el-col :span="19">
          <basic-container>
            <avue-crud :option="optionTwoCost"
                       :table-loading="loadingCost"
                       :data="dataCost"
                       ref="crud"
                       @refresh-change="refreshChangeCost"
                       @selection-change="selectionChangeCost"
                       :page.sync="pageCost"
                       @search-change="feesSearch"
                       @on-load="onLoadCost">
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCost = false">取 消</el-button>
          <el-button type="primary" @click="importCost" v-if="choiceData !== true">导入</el-button>
          <el-button type="primary" @click="choiceCost" v-if="choiceData === true"
                     :disabled="tableDataCost.length !== 1">导入</el-button>
        </span>
    </el-dialog>

    <el-dialog
      title="账单"
      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>

    <report-dialog
      :switchDialog="switchDialog"
      @onClose="onClose()"
    ></report-dialog>
  </div>
</template>

<script>
import {
  typeSave, detail, deleteDetails,
  corpstypeTree,
  corpsattn,
  corpsbank,
  corpsfiles,
  corpsitem,
  getList,
  detailList,
  generateShipment,
  saveSell,
  getlistBankBy,
} from "@/api/basicData/configuration"
import {selectGoodsNum} from "@/api/basicData/inventoryAccount"
import customerContact from "./configuration/customerContact.json"
import advantageProject from "./configuration/advantageProject.json"
import bankOfDeposit from "./configuration/bankOfDeposit.json"
import commodity from "./configuration/commodity.json"
import optionTwoCost from "./configuration/mainListCost.json"
import optionPolicy from "./configuration/optionPolicy.json"
import BuyFree from "./configuration/BuyFree.json"
import {
  getDeptLazyTree,
  getDeptLazyTreeTwo,
  customerList,
  policyList,
  policyColumn
} from "@/api/basicData/basicFeesDesc";
import _ from "lodash";
import option from "./configuration/mainList.json";
import { contrastObj, contrastList } from "@/util/contrastData";
import { getMarketPrice, getPurchasePrice } from "@/api/basicData/fees"
import customerDialog from "@/components/customer-dialog/main";
//账单组件
import ApplyPayment from "../../../components/finance/applyPayment";
import reportDialog from "@/components/report-dialog/main";
import { getToken } from "@/util/auth";
import Cookies from 'js-cookie'

export default {
  name: "detailsPage",
  props: {
    detailData: {
      type: Object
    }
  },
  components:{
    customerDialog,
    ApplyPayment,
    reportDialog,
  },
  data() {
    return {
      saveLoading: false,
      disabled: false,
      form: {},
      billType:"销售",  //账单类型
      billData:{},     //账单需要数据
      applySettlementDialog:false,//生成账单组件
      configuration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      goodsConfiguration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      plantConfiguration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      companyConfiguration: {
        multipleChoices: false,
        multiple: false,
        collapseTags: false,
        placeholder: '请点击右边按钮选择',
        dicData: []
      },
      data: [],
      policyForm: {},
      dataPolicy: [],
      contactsDataBuyFree: [],
      loadingCost: false,
      customerDivide: '',
      choiceData: false,
      commodityData: false,
      dataCost: [],
      treeDataPolicy: [],
      treeDataGoods: [],
      choiceIndex: '',
      dialogCost: false,
      treeDeptId: '',
      treeDeptIdCost: '',
      treePolicyId: '',
      pageCost: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      pagePolicy: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      loading: false,
      loadingPolicy: false,
      contactsForm: {},
      optionPolicy: optionPolicy,
      optionTwo: commodity,
      optionTwoCost: optionTwoCost,
      customerBuyFree: BuyFree,
      policyOption: {
        nodeKey: 'id',
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          const newTime = new Date().toLocaleString('chinese',{hour12:false})
          policyColumn({newTime: newTime,parentId: 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'
        }
      },
      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'
        }
      },
      dialogVisible: false,
      policyDialog: false,
      advantageProjectForm: {},
      selection: [],
      bankOfDepositForm: {},
      contactsData: [],
      advantageProjectData: [],
      bankOfDepositData: [],
      tableDataCost: [],
      dic: [],
      tableData: [],
      policyData: [],
      policyDataTwo: [],
      customerContact: {},
      advantageProject: {},
      bankOfDeposit: bankOfDeposit,
      contactInformation: {
        column: [
          {
            label: '销售金额',
            prop: 'orderAmount',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '其他费用',
            prop: 'otherAmount',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },  {
            label: '溢付款',
            prop: 'overPayment',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '应收账款',
            prop: 'debitAmount',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '已收款',
            prop: 'settlmentAmount',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '应收未收款',
            prop: 'balanceAmount',//无
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '应收预付款',
          //   prop: 'advancePayment',
          //   rules: [
          //     {
          //       required: false,
          //       message: ' ',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '保证金',
            prop: 'deposit',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '逾期账款',
            prop: 'overDueAccounts',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '实际发货日期',
            prop: 'actualDeliveryDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '合同日期',
            prop: 'businesDate',
            type: 'date',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '毛利率',
            prop: 'grossProfitRate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '毛利额',
            prop: 'grossProfit',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '历史运费(元/条)',
            prop: 'freightAmountHistory',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '到货日期',
            prop: 'arrivalDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '预收款日期',
            type: 'datetime',
            prop: 'advanceCollectionDate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '积分倍数',
            prop: 'pointMutiple',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '单据状态',
            prop: 'orderStatus',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '制单日期',
            prop: 'createTime',
            type: 'datetime',
            disabled:true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '制单人',
            prop: 'createUserName',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '特别提醒',
            prop: 'specialRemarks',
            type: 'textarea',
            span: 24,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      basicData: {
        column: [
          {
            label: '客户全称',
            prop: 'corpId',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '到货地址',
            prop: 'arrivalAddress',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '生产工厂',
            prop: 'productionPlant',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '发货地址',
            prop: 'shippingAddress',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '所属公司',
            prop: 'belongToCorpId',
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '银行帐号',
            prop: 'banks',
            type: 'select',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '公司户头',
            prop: 'banksAccountName',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '开户银行',
            prop: 'accountBank',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '付款方式',
            prop: 'paymentType',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '销售订单号',
            prop: 'orgOrderNo',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '主订单号',
            prop: 'morderNo',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '预估运费',
            prop: 'oceanFreight',
            type: 'number',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '要求发货日期',
            prop: 'requiredDeliveryDate',
            type: 'date',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '要求到货日期',
            prop: 'requiredArrivalDate',
            type: 'date',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: "订单备注",
            type: 'textarea',
            span: 24,
            prop: "orderRemark",
            mock: {
              type: 'county'
            }
          }
        ]
      },
      // 银行账号下拉
      bankList: [],
      paymentOption: [],
      statusOption: [],
      // 费用信息排序的最大值
      maxFeeNum: 0,
      maxGoodsNum: 0,
      oldForm: {
        orderStatus: "录入"
      },
      oldGoodsList: [],
      oldFeesList: [],
      oldUploadList: [],
      // 采购价格
      purchasePriceOption: [],
      // 销售价格
      salesPriceOtion: [],
      // 弹窗高度
      rowHeight: '',
      // 查询时loading页面
      pageLoading: false,
      switchDialog: false,
      baseURL: '/api/blade-purchase-sales/orderitems/importPrice',
      headers: { "Blade-Auth": 'Bearer ' + getToken()},
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 监听浏览器高度变化，改变表格高度
      window.onresize = () => {
        this.rowHeight = (window.innerHeight - 130) + 'px'
      }
    })
  },
  //初始化查询
  async created() {
    this.rowHeight = (window.innerHeight - 130) + 'px'
    this.customerContact = customerContact
    // this.customerContact = await this.getColumnData(this.getColumnName(15), customerContact);
    this.advantageProject = await this.getColumnData(this.getColumnName(16), advantageProject);
    this.getWorkDicts("payment_term").then(res => {
      this.paymentOption = res.data.data
    })
    this.getWorkDicts("order_status").then(res => {
      this.statusOption = res.data.data
    })
    this.$set(this.form, 'orderStatus', '录入')
    this.$set(this.form, 'overPayment', 0)
    this.$set(this.form, 'orderAmount', 0)
    if (this.detailData.id) {
      this.queryData(this.detailData.id)
    }
    if (this.detailData.seeDisabled) {
      // this.bankOfDeposit.column.forEach(item => {
      //   item.editDisabled = true
      //   item.addDisabled = true
      // })
    }
    if (this.detailData.copyId) {
      this.queryData(this.detailData.copyId, true)
    }
  },
  watch: {
  },
  methods: {
    getGoodsRow(event,row) {
      row.priceCategory = event.goodsTypeName
      this.$set(row, 'priceType', '一般')
      row.code = event.code
      row.typeno = event.typeno
      row.itemType = event.typeno
      row.itemId = event.id
    },
    queryData(id, isCopy = false){
      this.pageLoading = true
      detail(id).then(res => {
        this.form = res.data.data;
        this.contactsData = this.form.orderItemsList
        this.advantageProjectData = this.form.orderFeesList
        this.bankOfDepositData = this.form.orderFilesList
        this.configuration.dicData = this.form.corpName
        if (this.form.belongToCorpList) {
          this.companyConfiguration.dicData = this.form.belongToCorpList
        }
        if (this.form.productionPlantList) {
          this.plantConfiguration.dicData = this.form.productionPlantList
        }
        let feesData = []
        this.form.orderFeesList.forEach(item => {
          let a = {
            cname: item.corpName,
            id: item.corpId
          }
          feesData.push(a)
        })
        this.configuration.dicData = this.configuration.dicData.concat(feesData)
        // 去重
        this.removeRepeat()
        let goodsData = []
        this.form.orderItemsList.forEach(item => {
          let a = {
            cname: item.cname,
          }
          goodsData.push(a)
        })
        this.goodsConfiguration.dicData = [].concat(goodsData)
        this.removeGoodsRepeat()
        delete this.form.orderItemsList
        delete this.form.orderFeesList
        delete this.form.orderFilesList
        // delete this.form.corpName
        delete this.form.belongToCorpList
        // 获取最大值
        let num = []
        this.advantageProjectData.forEach(item => {
          num.push(item.sort)
        })
        if (num.length == 0) {
          this.maxFeeNum = 0;
        } else {
          this.maxFeeNum = num.reduce((a, b) => {
            return b > a? b: a;
          })
        }
        let goodsNum = []
        let purchaseAmount = 0
        this.contactsData.forEach(item => {
          goodsNum.push(item.sort)
          purchaseAmount += Number(item.purchaseAmount)
        })
        if (goodsNum.length == 0) {
          this.maxGoodsNum = 0;
        } else {
          this.maxGoodsNum = goodsNum.reduce((a, b) => {
            return b > a? b: a;
          })
        }
        this.oldForm = Object.assign({}, this.form)
        this.oldGoodsList = []
        this.oldFeesList = []
        this.oldUploadList = []
        this.oldGoodsList = this.deepClone(this.contactsData)
        this.oldFeesList = this.deepClone(this.advantageProjectData)
        this.oldUploadList = this.deepClone(this.bankOfDepositData)
        if (isCopy) {
          this.$set(this.form, 'orderStatus', '录入')
          delete this.form.id
          delete this.form.orgOrderNo
          delete this.form.morderNo
          delete this.form.createUserName
          delete this.form.createTime
          this.contactsData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.advantageProjectData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.bankOfDepositData.forEach(item => {
            delete item.id
            delete item.pid
          })
        }
      }).finally(() => {
        this.saveLoading = false
        this.pageLoading = false
      });
    },
    // 复制新单
    copyOrder() {
      this.queryData(this.form.id, true)
    },
    getcorpId(row) {
      this.contactsData[row.index].corpId = row.id;
    },
    // 采购金额获取
    getPurchasePrice(row) {
      getPurchasePrice({code: row.code}).then(res => {
        this.purchasePriceOption = res.data.data
      })
    },
    // 销售金额获取
    getMarketPrice(row) {
      getMarketPrice({code: row.code}).then(res => {
        this.salesPriceOtion = res.data.data
      })
    },
    // 生成采购单
    saveSell() {
      // if (!this.form.id) {
      //   return this.$message.error("此单据没有提交记录，请先提交");
      // }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(this.contactsData, this.oldGoodsList) ||
        contrastList(this.advantageProjectData, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false)
        }).catch(() => {
          this.$message.info('已取消')
          // this.$confirm("是否生成采购单?", {
          //   confirmButtonText: "确定",
          //   cancelButtonText: "取消",
          //   type: "warning"
          // }).then(() => {
          //   saveSell(this.form.id).then(res => {
          //     if (res.data.code == 200) {
          //       this.$message.success("生成成功");
          //     }
          //   });
          // });
        })
      } else {
        this.$confirm("是否生成采购单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          saveSell(this.form.id).then(res => {
            if (res.data.code == 200) {
              this.$message.success("生成成功");
            }
          });
        });
      }
    },
    //点击行可编辑
    handleRowClick(row, event, column) {
    },
    //商品编辑
    rowCell(row, index) {
      if (row.$cellEdit) {
        if (Number(row.orderQuantity) < Number(row.actualQuantity)) {
          return this.$message.error('订货数量不能小于发货数量')
        }
      }
      this.$refs.crudContact.rowCell(row, index)
    },
    //费用编辑
    rowCellTwo(row, index) {
      console.log(row)
      this.$refs.crudProject.rowCell(row, index)
    },
    //费用新增触发
    costIncrease() {
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //商品新增触发
    commoditySelection() {
      this.dialogVisible = !this.dialogVisible
      this.tableData = []
      this.commodityData = false
    },
    //政策价格导入
    policy() {
      this.policyDialog = !this.policyDialog
    },
    // 报表
    openReport() {
      this.switchDialog =! this.switchDialog;
    },
    // 下载模板
    downloadHandle() {
      this.$confirm('是否下载模板文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-purchase-sales/orderitems/exportPrice?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      })
    },
    //文件上传时
    uploading(event, file, fileList) {
      this.pageLoading = true;
      // this.openFullScreen(false, '文件正在解析中');
    },
    importTemplate(res, file) {
      console.log(res)
      this.pageLoading = false
      let goodsData = []
      res.data.forEach(item => {
        this.$set(item, 'priceType', '一般')
        this.$set(item, 'actualQuantity', '0')
        this.$set(item, 'purchaseAmount', '0')
        this.$set(item, 'price', '0')
        this.$set(item, 'amount', '0')
        this.$set(item, 'sort', this.maxFeeNum + 1)
        this.maxFeeNum++
        let a = {
          cname: item.cname,
        }
        goodsData.push(a)
      })
      this.goodsConfiguration.dicData = this.goodsConfiguration.dicData.concat(goodsData)
      this.removeGoodsRepeat()
      this.contactsData = this.contactsData.concat(res.data)

    },
    //遮罩层
    openFullScreen(res, text) {
      const loading = this.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      if (res === true) loading.close();
    },
    onClose(val) {
      this.switchDialog = val;
    },
    getShipmentD() {
      if (this.$store.getters.inStatus) {
        this.$alert("发货单存在,请保存发货单再进行操作", "温馨提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: action => {
            console.log(action);
          }
        });
      } else {
        this.generateShipmentD();
      }
    },
    //生成发货单
    generateShipmentD() {
      let lsit = []
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(this.contactsData, this.oldGoodsList) ||
        contrastList(this.advantageProjectData, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
          // this.selection.forEach(item => {
          //   lsit.push(item.id)
          // })
          // let data = {
          //   id: this.form.id,
          //   orderItemIds: lsit
          // }
          // generateShipment(data).then(res => {
          //   this.$router.$avueRouter.closeTag("/businessManagement/deliveryNotice/index");
          //   this.$router.push({
          //     path: "/businessManagement/deliveryNotice/index",
          //     query: {form: JSON.stringify(res.data.data)},
          //   });
          // })
        })
      } else {
        // lsit.push(this.selection[item].id)
        this.selection.forEach(item => {
          lsit.push(item.id)
        })
        let data = {
          id: this.form.id,
          orderItemIds: lsit
        }
        generateShipment(data).then(res => {
          this.$router.$avueRouter.closeTag("/businessManagement/deliveryNotice/index");
          this.$router.push({
            path: "/businessManagement/deliveryNotice/index",
            query: {form: JSON.stringify(res.data.data)},
          });
        })
      }
    },
    // 生成结算
    applySettlement() {
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(this.contactsData, this.oldGoodsList) ||
        contrastList(this.advantageProjectData, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(true)
        }).catch(() => {
        })
      } else {
        this.beforeBillData(true)
        this.applySettlementDialog = true;
      }
    },
    //生成账单 拿到主表信息
    beforeBillData(type){
      this.billData = {
        srcOrderno:this.form.orgOrderNo,
        itemType:"销售",
        corpsName:this.form.corpName,
        corpId:this.form.corpId,
        srcParentId: this.form.id,
      }
      if(type){ //申请货款
        this.billData.srcId = -1
      }
    },
    //关闭账单
    choceFun(){
      this.applySettlementDialog  = false
    },
    //商品选中触发
    productSelection(selection) {
      this.selection = selection
    },
    //点击费用明细选择触发
    choice(row) {
      this.dialogCost = !this.dialogCost
      this.choiceData = true
      console.log(row)
      this.choiceIndex = row.$index
    },
    // 去重
    removeRepeat() {
      let obj = []
      this.configuration.dicData = this.configuration.dicData.reduce((current,next) => {
        obj[next.id] ? '': obj[next.id] = true && current.push(next)
        return current
      }, [])
    },
    removeGoodsRepeat() {
      let obj = []
      this.goodsConfiguration.dicData = this.goodsConfiguration.dicData.reduce((current,next) => {
        obj[next.cname] ? '': obj[next.cname] = true && current.push(next)
        return current
      }, [])
    },
    //
    receiveList(data){
      this.configuration.dicData = this.configuration.dicData.concat(data)
      this.removeRepeat()
    },
    receiveGoodList(data) {
      console.log(data)
      this.goodsConfiguration.dicData = this.goodsConfiguration.dicData.concat(data)
      this.removeGoodsRepeat()
    },
    getCorpRow(data) {
      this.$set(this.form, 'paymentType', data.paymentType)
      this.$set(this.form, 'packageRemarks', data.remarks)
      this.$set(this.form, 'arrivalAddress', data.storageAddr)
    },
    getPlantRow(data) {
      this.$set(this.form, 'shippingAddress', data.storageAddr)
    },
    getRow(event,row) {
      row.priceCategory = event[0].goodsTypeName
      this.$set(row, 'priceType', '一般')
      row.code = event[0].code
      row.typeno = event[0].typeno
      row.itemType = event[0].typeno
      row.itemId = event[0].id
    },
    //点击商品明细选择触发
    commodityChoice(row) {
      this.dialogVisible = !this.dialogVisible
      this.commodityData = true
      console.log(row)
      this.choiceIndexT = row.$index
    },
    //导入商品触发
    importChoice() {
      // this.contactsData = this.contactsData.concat(this.tableData)
      if (this.tableData.length === 1) {
        this.contactsData[this.choiceIndexT].cname = this.tableData[0].cname
        this.contactsData[this.choiceIndexT].code = this.tableData[0].code
        this.contactsData[this.choiceIndexT].typeno = this.tableData[0].typeno
        this.contactsData[this.choiceIndexT].itemType = this.tableData[0].typeno
        this.contactsData[this.choiceIndexT].itemId = this.tableData[0].id
        this.contactsData[this.choiceIndexT].priceCategory = this.tableData[0].goodsTypeName
        selectGoodsNum({
          goodsId: this.tableData[0].id,
          itemType: this.tableData[0].typeno
        }).then(res => {
          this.contactsData[this.choiceIndexT].storageQuantity =  res.data.data
        })
      }
      this.dialogVisible = !this.dialogVisible
      this.commodityData = false
    },
    //费用编辑导入触发
    choiceCost() {
      if (this.tableDataCost.length === 1) {
        this.advantageProjectData[this.choiceIndex].feeName = this.tableDataCost[0].cname
        this.advantageProjectData[this.choiceIndex].itemId = this.tableDataCost[0].id
        this.advantageProjectData[this.choiceIndex].code = this.tableDataCost[0].code
      }
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //费用导入触发
    importCost() {
      // this.advantageProjectForm = this.advantageProjectForm.concat(this.tableDataCost)
      if (this.tableDataCost.length > 0) {
        for (let item in this.tableDataCost) {
          console.log(this.tableDataCost[item])
          this.tableDataCost[item].itemId = this.tableDataCost[item].id
          this.tableDataCost[item].feeName = this.tableDataCost[item].cname
          this.$set(this.tableDataCost[item], 'amount', 0)
          this.$set(this.tableDataCost[item], 'settlmentAmount', 0)
          this.tableDataCost[item].sort = this.maxFeeNum + 1
          this.maxFeeNum++
          delete this.tableDataCost[item].id
          this.$refs.crudProject.rowCellAdd(this.tableDataCost[item]);
          this.$refs.crudProject.rowCell(this.tableDataCost[item], this.advantageProjectForm.length - 1)
        }
      }
      this.tableDataCost = []
      this.dialogCost = false
    },
    //确认导入触发
    importGoods() {
      // this.contactsData = this.contactsData.concat(this.tableData)
      if (this.tableData.length > 0) {
        for (let item in this.tableData) {
          // this.$set(this.tableData[item], 'storageQuantity', 0)
          selectGoodsNum({
            goodsId: this.tableData[item].id,
            itemType: this.tableData[item].typeno
          }).then(res => {
            this.tableData[item].priceCategory = this.tableData[item].goodsTypeName
            this.tableData[item].storageQuantity =  res.data.data
            delete this.tableData[item].goodsTypeName
            this.tableData[item].itemId = this.tableData[item].id
            this.$set(this.tableData[item], 'itemType', this.tableData[item].typeno)
            this.$set(this.tableData[item], 'priceType', '一般')
            this.$set(this.tableData[item], 'orderQuantity', 0)
            this.$set(this.tableData[item], 'actualQuantity', 0)
            this.$set(this.tableData[item], 'purchaseAmount', '0')
            this.tableData[item].price = '0'
            this.tableData[item].amount = 0
            this.tableData[item].sort = this.maxGoodsNum + 1
            delete this.tableData[item].id
            delete this.tableData[item].pid
            delete this.tableData[item].isDeleted
            delete this.tableData[item].status
            delete this.tableData[item].tenantId
            delete this.tableData[item].updateTime
            delete this.tableData[item].updateUser
            delete this.tableData[item].updateUserName
            this.maxGoodsNum++
            this.$refs.crudContact.rowCellAdd(this.tableData[item]);
            this.$refs.crudContact.rowCell(this.tableData[item], this.contactsData.length - 1)
          })
        }
        this.dialogVisible = false
      }
    },
    closeGoods() {
      this.treeDataGoods = [];
      this.treeDeptId = "";
    },
    closeFees() {
      this.treeDeptIdCost = "";
      this.treeData = [];
    },
    closePolicy() {
      this.treePolicyId = '';
      this.dataPolicy = [];
      this.policyForm = {};
      this.contactsDataBuyFree = [];
      this.policyData = []
      this.policyDataTwo = []
    },
    //选中触发
    selectionChange(list) {
      this.tableData = list
    },
    //费用选中触发
    selectionChangeCost(list) {
      this.tableDataCost = list
    },
    //导入页左商品类型查询
    nodeClick(data) {
      this.treeDeptId = data.id;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //导入页销售政策查询
    policyNodeClick(data) {
      this.treePolicyId = data.id
      // detailList(data.id).then(res => {
      //   //特价促销
      //   this.dataPolicy = res.data.data.specialItemList
      //   //买赠促销
      //   this.contactsDataBuyFree = res.data.data.presentItemList
      // })
      this.policyOnLoad()
    },
    //导入页左费用类型查询
    nodeClickCost(data) {
      this.treeDeptIdCost = data.id;
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //刷新触发
    refreshChange() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    //销售政策特价促销选中触发
    selectionChangePolicy(list) {
      this.policyData = list
      // this.policyData.forEach(item => {
      //   this.$set(item, 'price', item.specialOffer)
      // })
      if (this.policyData.length > 0) {
        this.customerBuyFree.selection = false
      } else {
        this.customerBuyFree.selection = true
      }
    },
    //销售政策买赠促销选中触发
    selectionChangePolicyTwo(list) {
      this.policyDataTwo = list
      // this.policyDataTwo.forEach(item => {
      //   this.$set(item, 'price', item.salesPrice)
      // })
      if (this.policyDataTwo.length > 0) {
        this.optionPolicy.selection = false
      } else {
        this.optionPolicy.selection = true
      }
    },
    //导入商品政策
    importPolicy() {
      let list = this.deepClone(this.policyData.concat(this.policyDataTwo))
      // 买赠额外加一条
      let buyFree = []
      if (this.policyDataTwo.length > 0) {
        buyFree = this.deepClone(this.policyDataTwo)
      }
      for (let item in list) {
        selectGoodsNum({
          goodsId: list[item].itemId,
          itemType: list[item].typeno
        }).then(res => {
          this.$set(list[item], 'storageQuantity', res.data.data)
          if (this.policyDataTwo.length > 0) {
            this.$set(buyFree[item], 'storageQuantity', res.data.data)
          }
        })
        if (this.policyData.length > 0) {
          this.$set(list[item], 'price', list[item].specialOffer)
        } else {
          this.$set(list[item], 'price', list[item].salesPrice)
          this.$set(buyFree[item], 'price', '0')
          this.$set(buyFree[item], 'orderQuantity',  list[item].salesVolume)
          this.$set(buyFree[item], 'itemType',  list[item].typeno)
        }
        this.$set(list[item], 'itemType',  list[item].typeno)
        this.$set(list[item], 'actualQuantity', 0)
        this.$set(list[item], 'orderQuantity', 0)
        this.$set(list[item], 'amount', 0)
        this.$set(list[item], 'priceCategory', list[item].productCategory)
        this.$set(list[item], 'priceType', this.policyForm.cname)
        this.$set(list[item], 'cname', list[item].productCategory)
        this.$set(list[item], 'sort', this.maxGoodsNum + 1)
        this.$set(list[item], 'purchaseAmount', list[item].purchasePrice)

        if (this.policyDataTwo.length > 0) {
          this.$set(buyFree[item], 'actualQuantity', 0)
          this.$set(buyFree[item], 'amount', 0)
          this.$set(buyFree[item], 'priceCategory', list[item].productCategory)
          this.$set(buyFree[item], 'priceType', this.policyForm.cname)
          this.$set(buyFree[item], 'cname', list[item].productCategory)
          this.$set(buyFree[item], 'sort', this.maxGoodsNum + 2)
          this.$set(buyFree[item], 'purchaseAmount', list[item].purchasePrice)
          this.maxGoodsNum++
        }
        delete list[item].id
        delete list[item].pid
        delete list[item].isDeleted
        delete list[item].status
        delete list[item].tenantId
        delete list[item].updateTime
        delete list[item].updateUser
        delete list[item].updateUserName
        this.maxGoodsNum++
        this.$refs.crudContact.rowCellAdd(list[item]);
        // this.$refs.crudContact.rowCell(list[item], this.contactsData.length - 1)
        if (this.policyDataTwo.length > 0) {
          this.$refs.crudContact.rowCellAdd(buyFree[item]);
        }
        // this.$refs.crudContact.rowCell(buyFree[item], this.contactsData.length - 1)
      }
      this.policyDialog = false
    },
    //费用刷新触发
    refreshChangeCost() {
      this.treeDeptIdCost = '';
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //新增商品信息保存触发
    rowSave(row, done, loading) {
      console.log(row)
      console.log(this.contactsData)
      // this.contactsData.push(row)
      done()
    },
    //修改商品信息触发
    rowUpdate(row, index, done, loading) {
      done(row);
    },
    //删除商品信息触发
    rowDel(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //商品判断是否需要调用删除接口
        if (row.id) {
          corpsattn(row.id).then(res => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.contactsData.splice(index, 1);
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.contactsData.splice(index, 1);
        }
      })
    },
    //新增费用明细保存触发
    rowSaveProject(row, done, loading) {
      // this.advantageProjectData.push(row)
      done()
    },
    //修改费用明细触发
    rowUpdateProject(row, index, done, loading) {
      done(row);
    },
    policyOnLoad(params = {}) {
      // this.policyLoading = true;
      detailList(this.treePolicyId).then(res => {
        this.policyForm = res.data.data
        //特价促销
        if(res.data.data.specialItemList) {
          this.dataPolicy = res.data.data.specialItemList
        } else {
          this.dataPolicy = []
        }
        //买赠促销
        if (res.data.data.presentItemList) {
          this.contactsDataBuyFree = res.data.data.presentItemList
        } else {
          this.contactsDataBuyFree = []
        }
      })
    },
    //
    goodsSearch(params, done) {
      this.onLoad(this.page, params);
      done()
    },
    //商品列表查询
    onLoad(page, params = {}) {
      console.log(params)
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId).then(res => {
        console.log(res)
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    // 费用查询按钮
    feesSearch(params, done) {
      this.onLoadCost(this.pageCost, params)
      done()
    },
    //费用查询
    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 => {
        console.log(res)
        const data = res.data.data;
        this.pageCost.total = data.total;
        this.dataCost = data.records;
        this.loadingCost = false;
      });
    },
    //删除费用明细触发
    rowDelProject(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //费用判断是否需要调用删除接口
        if (row.id) {
          corpsitem(row.id).then(res => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.advantageProjectData.splice(index, 1);
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.advantageProjectData.splice(index, 1);
        }
      })
    },
    //新增附件上传保存触发
    rowSaveBankOfDeposit(row, done, loading) {
      this.bankOfDepositData.push(row)
      done()
    },
    //修改附件上传触发
    rowUpdateBankOfDeposit(row, index, done, loading) {
      done(row);
    },
    //删除附件上传触发
    rowDelBankOfDeposit(row, index, donerowDel) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        //附件判断是否需要调用删除接口
        if (row.id) {
          corpsbank(row.id).then(res => {
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.bankOfDepositData.splice(index, 1);
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.bankOfDepositData.splice(index, 1);
        }
      })
    },
    uploadAfter(res, done) {
      if (res.originalName) {
        this.bankOfDepositForm.fileName = this.bankOfDepositForm.fileName
          ? this.bankOfDepositForm.fileName
          : res.originalName;
      }
      done();
    },
    //修改提交触发
    editCustomer(isBack = false) {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          for (let item in this.contactsData) {
            if (Number(this.contactsData[item].orderQuantity) < Number(this.contactsData[item].actualQuantity)) {
              return this.$message.error('商品信息第'+ (parseInt(item) + 1) + '行订货数量不能小于发货数量')
            }
          }
          // 计算毛利额
          // this.$set(this.form, 'grossProfit', 0)
          this.$set(this.form, 'orderAmount', 0)
          // 成本价
          let purchaseAmount = 0
          // 计算销售金额
          this.contactsData.forEach(item => {
            if (item.purchaseAmount) {
              purchaseAmount += (Number(item.purchaseAmount) * Number(item.orderQuantity)).toFixed(2)
            }
            // this.form.grossProfit += Number(item.amount)
            this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
          })
          // this.form.grossProfit = (Number(this.form.orderAmount) - Number(purchaseAmount)).toFixed(2)
          // if (this.form.orderAmount && this.form.overPayment) {
          //   this.form.debitAmount = Number(this.form.orderAmount) - Number(this.form.overPayment)
          // }
          if (this.form.orderAmount && this.form.settlmentAmount) {
            this.$set(this.form, "balanceAmount", (Number(this.form.orderAmount) - Number(this.form.settlmentAmount)).toFixed(2));
          }
          // 计算毛利率
          // if (this.form.orderAmount) {
          //   this.form.grossProfitRate = ((Number(this.form.grossProfit) / Number(this.form.orderAmount)) * 100).toFixed(2)
          // }
          // 计算应收账款
          // this.$set(this.form, 'debitAmount', 0)
          // this.contactsData.forEach(item => {
          //   this.form.debitAmount += Number(item.amount)
          // })
          //商品信息
          this.form.orderItemsList = this.contactsData
          this.form.orderFeesList = this.advantageProjectData
          this.form.orderFilesList = this.bankOfDepositData
          if (typeof this.form.corpsTypeId == 'object') {
            this.form.corpsTypeId = this.form.corpsTypeId.join(",")
          }
          this.form.billType = 'XS'
          this.saveLoading = true
          typeSave(this.form).then(res => {
            this.$message({type: "success", message: this.form.id ? "修改成功!" : "新增成功!"});
            if (isBack) {
              //成功关闭此页面回到列表页
              this.$emit("goBack");
            } else {
              this.queryData(res.data.data.id)
            }
          }).finally(() => {
            this.saveLoading = false
          })
        } else {
          return false;
        }
      });
    },
    // 计算应收未收款
    computedCost() {
      // 销售金额
      let orderAmount = 0;
      // 已收款
      let settlmentAmount = 0;
      // 溢付款
      let overPayment = 0
      if (this.form.orderAmount) {
        orderAmount = this.form.orderAmount
      }
      if (this.form.settlmentAmount) {
        settlmentAmount = this.form.settlmentAmount
      }
      if (this.form.overPayment) {
        overPayment = this.form.overPayment
      }
      this.$set(this.form, "balanceAmount", (Number(orderAmount) - Number(overPayment) - Number(settlmentAmount)).toFixed(2));
    },
    quantityChange(row) {
      if (!row.orderQuantity) {
        row.orderQuantity = 0;
      } else {
        // row.amount = _.multiply(row.price, row.orderQuantity).toFixed(2);
        row.amount = (row.price * row.orderQuantity).toFixed(2)
      }
    },
    priceChange(row) {
      console.log(row.price)
      if (!row.price) {
        row.price = 0;
      } else {
        row.amount = (row.price * row.orderQuantity).toFixed(2)
      }
    },
    //返回列表
    backToList() {
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(this.contactsData, this.oldGoodsList) ||
        contrastList(this.advantageProjectData, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(true)
        }).catch(() => {
          this.$emit("goBack");
        })
      } else {
        this.$emit("goBack");
      }
    },
    // 保存列设置
    async saveColumn(name) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      if (name == 'goods') {
        const inSave = await this.saveColumnData(
          this.getColumnName(15),
          this.customerContact
        );
        if (inSave) {
          this.$message.success("保存成功");
          //关闭窗口
          this.$refs.crudContact.$refs.dialogColumn.columnBox = false;
        }
      } else if (name === 'fees') {
        const inSave = await this.saveColumnData(
          this.getColumnName(16),
          this.advantageProject
        );
        if (inSave) {
          this.$message.success("保存成功");
          //关闭窗口
          this.$refs.crudProject.$refs.dialogColumn.columnBox = false;
        }
      }
    },
    returnBack(val) {
      getlistBankBy(val).then(res =>{
        this.$set(this.form, 'banks', null)
        this.$set(this.form, 'banksAccountName', null)
        this.$set(this.form, 'accountBank', null)
        this.bankList = res.data
        if (this.bankList.length > 0) {
          this.form.banks = this.bankList[0].accountNo
          this.form.banksAccountName = this.bankList[0].accountName
          this.form.accountBank = this.bankList[0].accountBank
        }
      })
    },
    // 银行账号变化
    banksChange(val) {
      let isTrue = false
      this.bankList.forEach(item => {
        if (val == item.accountNo) {
          this.$set(this.form, 'banksAccountName', item.accountName)
          this.$set(this.form, 'accountBank', item.accountBank)
          isTrue = true
        }
      })
      if (!isTrue) {
        this.$set(this.form, 'banksAccountName', null)
        this.$set(this.form, 'accountBank', null)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
//.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; */
//}
//
//.customer-back {
//  cursor: pointer;
//  line-height: 62px;
//  font-size: 16px;
//  color: #323233;
//  font-weight: 400;
//}

.back-icon {
  line-height: 64px;
  font-size: 20px;
  margin-right: 8px;
}

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

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

.el-dialogDeep {
  ::v-deep .el-dialog {
    margin: 1vh auto 0 !important;
    padding-bottom: 10px !important;

    .el-dialog__body, .el-dialog__footer {
      padding-bottom: 0 !important;
      padding-top: 0 !important;
    }
  }
}

.print-div {
  color: #000;
}

.print_table {
  table {
    border-right: 1px solid #000;
    border-bottom: 1px solid #000;
    font-size: 12px;
    margin-bottom: 5px;
  }

  table td {
    border-left: 1px solid #000;
    border-top: 1px solid #000;
    vertical-align: middle;
    padding: 2px;
    text-align: center;
  }
}

.table {
  border-collapse: collapse;
  border-spacing: 0;
  background-color: transparent;
  display: table;
  width: 99%;
  max-width: 100%;
  margin: 0 auto;
}

.table td {
  text-align: left;
  vertical-align: middle;
  font-size: 14px;
  color: #000000;
  padding: 10.5px 0 10.5px 30px;
  //border: 1px solid #000;
}
::v-deep .el-form-item {
  margin-bottom: 0;
}

::v-deep .el-form-item__content{
  line-height: 32px;
}
///deep/ .avue-tree {
//  display: flex;
//  flex-direction: column;
//  overflow-y: hidden;
//  height: 100%;
//}
///deep/ .avue-tree__filter {
//  flex-shrink: 1;
//}
///deep/ .avue-tree__content {
//  height: calc(100% - 32px);
//  overflow-y: auto;
//}
</style>
