<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="editHandle"
          type="primary"
          style="margin-right: 8px"
          :loading="saveLoading"
        >编 辑</el-button>
        <el-dropdown style="margin-right: 8px;">
          <el-button
            type="primary"
            size="small"
            :loading="saveLoading"
          >
            审核处理<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :disabled="browse || detailData.seeDisabled" @click.native="pleaseCheck">请核数据</el-dropdown-item>
            <el-dropdown-item v-if="form.status > 0" @click.native="checkScheduleDialog = true,checkId=form.id">审核进度</el-dropdown-item>
            <el-dropdown-item v-if="form.status == 1" @click.native="repealCancel">撤销请核</el-dropdown-item>
            <el-dropdown-item v-if="checkDisabled && form.status != 3" @click.native="changeApproveOpen">特殊审批</el-dropdown-item>
            <el-dropdown-item v-if="form.status == 3" :disabled="detailData.seeDisabled || form.specialCheckStatus > 0" @click.native="arrearsPleaseCheck">欠款发货审批</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown style="margin-right: 8px;">
          <el-button
            type="warning"
            size="small"
            :loading="saveLoading"
          >
            账单处理<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
<!--            <el-dropdown-item-->
<!--              :disabled="detailData.seeDisabled || form.status != 3"-->
<!--              @click.native="applySettlement('收费')">生成账单-->
<!--            </el-dropdown-item>-->
            <el-dropdown-item
              @click.native="openApplicationDialog"
              :disabled="!form.id"
            >查看账单
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown style="margin-right: 8px;">
          <el-button
            type="success"
            :loading="saveLoading"
            size="small"
          >
            业务处理<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              :disabled="detailData.seeDisabled || form.status != 3 || form.createPurchase == 1"
              @click.native="saveSell">生成采购
            </el-dropdown-item>
            <el-dropdown-item
              :disabled="detailData.seeDisabled || !this.form.id"
              @click.native="copyOrder"
            >复制单据</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          class="el-button--small-yh"
          type="primary"
          :disabled="disabled || detailData.seeDisabled"
          :loading="saveLoading"
          size="small"
          @click="editCustomer(false)"
        >保 存
        </el-button>
        <div v-if="checkDisabled" style="float: right;margin-left: 8px">
          <el-button type="primary"
                     size="small"
                     class="el-button--small-yh"
                     @click.stop="openCheckDialog">
            审批
          </el-button>
        </div>
      </div>
    </div>
    <div class="customer-main">
      <el-form :model="form" ref="form" label-width="130px" class="demo-ruleForm">
        <containerTitle title="基础资料"></containerTitle>
        <basic-container :showBtn="true">
          <el-row>
            <el-col v-for="(item,index) in basicData.column" :key="index" :span="item.span?item.span:8" :class="{isShow: item.display}">
              <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 || browse"/>
                <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 || browse"/>
                <crop-select
                  v-else-if="item.prop === 'corpId'"
                  v-model="form[item.prop]"
                  @getCorpData="getCorpRow"
                  corpType="KH"
                  :disabled="detailData.seeDisabled || browse || !form.belongToCorpId"
                  style="width: 100%"
                  ref="KHSelect"
                  :belongtocompany="form.belongToCorpId"
                ></crop-select>
                <crop-select
                  v-else-if="item.prop === 'belongToCorpId'"
                  v-model="form[item.prop]"
                  @getCorpData="returnBack"
                  corpType="GS"
                  :disabled="detailData.seeDisabled || browse"
                ></crop-select>
                <crop-select
                  v-else-if="item.prop === 'productionPlant'"
                  v-model="form[item.prop]"
                  @getCorpData="getPlantRow"
                  corpType="GYS"
                  :disabled="detailData.seeDisabled || browse"
                  style="width: 100%"
                ></crop-select>
                <el-select v-else-if="item.prop === 'paymentType'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled || browse">
                  <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 === 'packageRemarks'" v-model="form[item.prop]" placeholder="请选择" clearable filterable allow-create default-first-option style="width: 100%" size="small" :disabled="detailData.seeDisabled || browse">
                  <el-option v-for="(item,index) in packageOptions" :key="index" :label="item.dictValue" :value="item.dictValue"></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'arrivalAddress'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled || browse" allow-create default-first-option>
                  <el-option v-for="(item,index) in arrivalOptions" :key="index" :label="item.label" :value="item.label"></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'shippingAddress'" v-model="form[item.prop]" placeholder="请选择" clearable filterable style="width: 100%" size="small" :disabled="detailData.seeDisabled || browse" allow-create default-first-option>
                  <el-option v-for="(item,index) in shippingOptions" :key="index" :label="item.label" :value="item.label"></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 || browse">
                  <el-option v-for="(item,index) in bankList" :key="index" :label="item.accountNo" :value="item.accountNo"></el-option>
                </el-select>
                <el-select v-else-if="item.prop === 'corpAttn'"
                           v-model="form[item.prop]" placeholder="请选择"
                           clearable
                           filterable
                           allow-create
                           default-first-option
                           size="small"
                           style="width: 100%;"
                           @change="corpAttnChange"
                           :disabled="detailData.seeDisabled || browse">
                  <el-option v-for="(item,index) in khInfoList" :key="index" :label="item.cname" :value="item.id"></el-option>
                </el-select>
                <el-input
                  v-else-if="item.type == 'number'"
                  placeholder="请输入"
                  v-input-limit="2"
                  size="small"
                  :disabled="item.disabled || detailData.seeDisabled || browse"
                  v-model.trim="form[item.prop]"
                />
                <span v-else-if="item.type == 'radio'">
                  <el-radio
                    size="small"
                    :disabled="item.disabled || detailData.seeDisabled || browse"
                    v-model.trim="form[item.prop]"
                    :label="1"
                  >是</el-radio>
                  <el-radio
                    size="small"
                    :disabled="item.disabled || detailData.seeDisabled || browse"
                    v-model.trim="form[item.prop]"
                    :label="0"
                  >否</el-radio>
                </span>
                <el-select v-else-if="item.prop === 'chargeMember'"
                           v-model="form[item.prop]" placeholder="请选择"
                           filterable
                           size="small"
                           style="width: 100%;"
                           :disabled="detailData.seeDisabled || browse">
                  <el-option v-for="(item,index) in userList" :key="index" :label="item.cname" :value="item.cname"></el-option>
                </el-select>
                <el-input type="textarea" v-else-if="item.type === 'textarea'" v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || browse"></el-input>
                <el-input type="age" v-else v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || browse" clearable></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </basic-container>
        <containerTitle title="发货信息"></containerTitle>
        <basic-container :showBtn="true">
          <el-row>
            <el-col v-for="(item,index) in contactInformation.column" :key="index" :span="item.span?item.span:8" :class="{isShow: item.display == false}">
              <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 || browse"/>
                <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 || browse"/>
                <el-input
                  v-else-if="(item.prop === 'advancePayment') || (item.prop === 'orderAmount') ||
                  (item.prop === 'settlmentAmount') || (item.prop === 'caseOverPayment') || (item.prop === 'thisUsedProfit') ||
                  (item.prop === 'createProfit')"
                  v-model.trim="form[item.prop]" size="small" autocomplete="off"
                  @change="computedCost"
                  :disabled="detailData.seeDisabled || item.disabled || browse"
                  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 || item.disabled || browse">
                  <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.trim="form[item.prop]" size="small" autocomplete="off" placeholder="请输入" :disabled="detailData.seeDisabled || browse" v-input-limit="2">
                  <template slot="append">%</template>
                </el-input>
                <el-input type="age" v-else-if="item.prop === 'specialOfferOf'" v-model.trim="form[item.prop]" size="small" autocomplete="off" placeholder="请输入" :disabled="detailData.seeDisabled || browse" v-input-limit="2">
                  <template slot="append">%</template>
                </el-input>
                <el-input type="age" v-else-if="item.prop === 'largeScale'" v-model.trim="form[item.prop]" size="small" autocomplete="off" placeholder="请输入" :disabled="detailData.seeDisabled || browse" 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 || browse"
                  v-model.trim="form[item.prop]"
                />
                <el-input type="textarea" v-else-if="item.type === 'textarea'" v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || browse"></el-input>
                <el-input v-else type="age" v-model.trim="form[item.prop]" size="small" autocomplete="off" :disabled="item.disabled || detailData.seeDisabled || browse"></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="goodsShowData"
              ref="crudContact"
              @row-save="rowSave"
              @row-click="handleRowClick"
              @row-update="rowUpdate"
              @selection-change="productSelection"
              @row-del="rowDel"
              @saveColumn="saveColumn('goods')"
              @resetColumn="resetColumn"
              :summary-method="summaryMethod"
              :table-loading="goodsLoading"
              :key="index"
          >
            <template slot="headerSerial">
              <span class="order_number">序号</span>
              <el-button class="number_button" type="primary" icon="el-icon-circle-plus-outline" circle size="mini" @click="$refs.crudContact.rowCellAdd()"></el-button>
            </template>
<!--            <template slot="corpId" slot-scope="{ row, index }">-->
<!--              <crop-select-->
<!--                v-if="row.$cellEdit"-->
<!--                v-model="row.corpId"-->
<!--                :cropIndex="index"-->
<!--                corpType="GYS"-->
<!--                @getCorpData="getcorpId"-->
<!--                :disabled="detailData.seeDisabled || browse"-->
<!--              ></crop-select>-->
<!--              <span v-else>{{ row.corpName }}</span>-->
<!--            </template>-->
            <template slot="code" slot-scope="{row}">
              <el-button
                type="text"
                size="mini"
                style="padding:4px 10px;float:left"
                @click="commodityChoice(row)"
                :disabled="detailData.seeDisabled || !row.$cellEdit || browse">选择</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"
                default-first-option
              >
                <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="false"
                v-model="row.price"
                @focus="getMarketPrice(row)"
                @input="priceChange(row)"
                allow-create
                filterable
                v-input-limit="2"
                default-first-option
              >
                <el-option
                  v-for="(item, index) in salesPriceOtion"
                  :key="index"
                  :label="item.salePrice"
                  :value="item.salePrice"></el-option>
              </el-select>
              <span v-else>{{ row.price }}</span>
            </template>
            <template slot="amount" slot-scope="{ row }">
              <span>{{ row.amount | decimalFormat }}</span>
            </template>
            <template slot="actualQuantity" slot-scope="{ row }">
              <span>{{ row.actualQuantity | IntegerFormat }}</span>
            </template>
            <template slot="orderQuantity" slot-scope="{ row }">
              <el-input
                v-if="row.$cellEdit"
                v-model.trim="row.orderQuantity"
                oninput='this.value=this.value.replace(/[^(\d)]/g,"")'
                size="small"
                @input="quantityChange(row)"
              ></el-input>
              <span v-else>{{ row.orderQuantity | IntegerFormat }}</span>
            </template>
            <template slot="shopQuality" slot-scope="{ row }">
              <el-switch
                v-model="row.shopQuality"
                :disabled="!row.$cellEdit || shopQualityDisable"
                :active-value="1"
                :inactive-value="0"
                @change="(val) => shopQualityChange(val, row)"
              ></el-switch>
            </template>
            <template slot-scope="{row,index}" slot="menu">
              <el-button
                  type="text"
                  size="small"
                  @click="rowCell(row,index)"
                  :disabled="detailData.seeDisabled || browse"
              >{{ row.$cellEdit ? '保 存' : '修 改' }}
              </el-button>
              <el-button
                size="small"
                icon="el-icon-delete"
                type="text"
                @click="rowDel(row, index)"
                :disabled="detailData.seeDisabled || browse"
              >删 除</el-button>
            </template>
            <template slot="menuLeft" slot-scope="{size}">
              <el-tabs v-model="goodsActives" @tab-click="handleClick" :before-leave="beforeLeave">
                <el-tab-pane label="商品" name="goods" :key="'first'" :disabled="goodsDisabled">
                </el-tab-pane>
                <el-tab-pane label="赠品" name="gift" :key="'second'" :disabled="goodsDisabled">
                </el-tab-pane>
              </el-tabs>
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="commoditySelection"
                         :disabled="detailData.seeDisabled || browse">录入明细
              </el-button>
              <el-button type="primary"
                         icon="el-icon-plus"
                         size="small"
                         @click="policy"
                         :disabled="detailData.seeDisabled || !form.corpId || browse"
                         v-show="goodsActives == 'goods'"
              >政策
              </el-button>
<!--              禁用规则：未选择明细，未点击编辑按钮，未进行审批，已经生成过-->
              <el-button type="warning"
                         icon="el-icon-plus"
                         size="small"
                         :disabled="selection.length < 1 || detailData.seeDisabled || !form.status || form.status < 3 || form.createFreight == 1"
                         @click="getShipmentD"
                         v-show="goodsActives == 'goods'">生成客户收货
              </el-button>
              <el-button type="info"
                         :size="size"
                         icon="el-icon-printer"
                         @click.stop="openReport()"
                         v-show="goodsActives == 'goods'"
              >报表打印</el-button>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-download"
                @click="downloadHandle"
                v-show="goodsActives == 'goods'"
              >下载模板</el-button>
              <el-upload
                :action="baseURL"
                :headers="headers"
                :disabled="detailData.seeDisabled || browse"
                :on-progress="uploading"
                :show-file-list=false
                accept=".xls,.xlsx"
                multiple
                :on-success="importTemplate"
                :on-error="uploadError"
                style="float: right"
              >
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-upload"
                  v-show="goodsActives == 'goods'"
                  :disabled="detailData.seeDisabled || browse"
                >导 入</el-button>
              </el-upload>
              <el-button
                type="warning"
                icon="el-icon-refresh"
                size="small"
                @click="resetStock"
              >库存刷新</el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="small"
                @click="removeList"
                :disabled="(selection.length == 0) || detailData.seeDisabled || browse"
              >删除</el-button>
            </template>
          </avue-crud>
        </basic-container>
        <fee-info
          ref="feeInfo"
          :orderFeesList="advantageProjectData"
          :disabled="detailData.seeDisabled || form.status >= 3"
          feeUrl="/blade-purchase-sales/orderfees/update"
          optionType="GN"
          itemType="销售"
          @beforeFinance="beforeFinance"
          :corpId="form.corpId"
          :financeDisabled="false"
          :tabShow="2"
        />
        <containerTitle title="上传附件"></containerTitle>
        <c-upload
          :data="bankOfDepositData"
          deleteUrl="/api/blade-client/corpsbank/update"
          :enumerationValue="77"
          display
        />

      </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="goodsListShow"
                       ref="crud"
                       @refresh-change="refreshChange"
                       @selection-change="selectionChange"
                       @search-change="goodsSearch"
                       :page.sync="page"
                       @on-load="onLoad">
              <template slot="menuLeft">
                <el-tabs v-model="activeName" @tab-click="tabHandle">
                  <el-tab-pane label="查询结果" name="searchList"/>
                  <el-tab-pane label="已选定数据" name="importStaging"/>
                </el-tabs>
              </template>
              <template slot="orderQuantity" slot-scope="{row}">
                <el-input-number
                  v-model="row.orderQuantity"
                  size="small"
                  :controls="false"
                  :precision="0"
                  @input="amountChange(row)"
                  style="width: 100%"
                />
              </template>
              <template slot-scope="scope" slot="menu">
                <el-button
                  type="text"
                  icon="el-icon-edit"
                  size="small"
                  @click.stop="importStagList(scope.row,scope.index)"
                  v-if="activeName=='searchList'"
                  :disabled="goodsListSave.findIndex(item => item.id == scope.row.id) !== -1"
                >选择</el-button>
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  size="small"
                  @click.stop="removeStagList(scope.row,scope.index)"
                  v-else
                >移除</el-button>
              </template>
            </avue-crud>
          </basic-container>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" :loading="saveLoading">取 消</el-button>
          <el-button type="primary" @click="importGoods" v-if="commodityData !== true" :loading="saveLoading">导入</el-button>
          <el-button type="primary" @click="importChoice" v-if="commodityData === true" :loading="saveLoading" :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">
          <el-tabs v-model="activeName" @tab-click="tabHandleTwo">
            <el-tab-pane label="查询结果" name="searchList"/>
            <el-tab-pane label="已选定数据" name="importStaging"/>
          </el-tabs>
          <containerTitle title="特价促销"></containerTitle>
          <basic-container style="margin-bottom: 10px">
            <avue-crud :option="optionPolicy"
                       :table-loading="loadingPolicy"
                       :data="dataPolicy"
                       ref="crud"
                       :key="policyIndex"
                       @selection-change="selectionChangePolicy"
                       :page.sync="pagePolicy">
              <template slot-scope="scope" slot="menu">
                <el-button
                    type="text"
                    icon="el-icon-edit"
                    size="mini"
                    v-if="activeName=='searchList'"
                    @click.stop="importStagList(scope.row,scope.index,'policy')"
                    :disabled="goodsListPolicy.findIndex(item => item.id == scope.row.id) !== -1"
                >选择</el-button>
                <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="small"
                    @click.stop="removeStagList(scope.row,scope.index,'policy')"
                    v-else
                >移除</el-button>
              </template>
              <template slot="menuLeft">
                <el-button
                  type="info"
                  size="mini"
                  icon="el-icon-download"
                  @click="downLoadPolicy"
                >下载模板</el-button>
                <el-upload
                  :action="policyUrl+'?policyName=' + uploadPolicy.policyName + '&salesType=1'"
                  :headers="headers"
                  :disabled="uploadPolicy.policyName === '' || loadingPolicy"
                  :on-progress="uploading"
                  :show-file-list=false
                  accept=".xls,.xlsx"
                  multiple
                  :on-success="successPolicy"
                  :on-error="uploadError"
                  style="float: right"
                >
                  <el-button
                    type="warning"
                    size="mini"
                    icon="el-icon-upload"
                    :disabled="uploadPolicy.policyName === '' || loadingPolicy"
                    :loading="loadingPolicy"
                  >导 入</el-button>
                  <el-button
                    type="primary"
                    size="mini"
                    icon="el-icon-search"
                    @click="policyOnLoad"
                    :disabled="uploadPolicy.policyName === '' || loadingPolicy"
                    :loading="loadingPolicy"
                  >政策明细</el-button>
                </el-upload>
              </template>
              <template slot="orderQuantity" slot-scope="{row}">
                <el-input-number
                  v-model="row.orderQuantity"
                  size="small"
                  :controls="false"
                  :precision="0"
                  style="width: 100%"
                  placeholder="请输入"
                />
              </template>
            </avue-crud>
          </basic-container>
          <containerTitle title="买赠促销"></containerTitle>
          <basic-container>
            <avue-crud
                :option="customerBuyFree"
                :data="contactsDataBuyFree"
                @selection-change="selectionChangePolicyTwo"
                :table-loading="loadingPolicy"
                ref="crudContactE">
              <template slot-scope="scope" slot="menu">
                <el-button
                    type="text"
                    icon="el-icon-edit"
                    size="mini"
                    v-if="activeName=='searchList'"
                    @click.stop="importStagList(scope.row,scope.index,'policy_buyAndGive')"
                    :disabled="buyAndGiveList.findIndex(item => item.id == scope.row.id) !== -1"
                >选择</el-button>
                <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="small"
                    @click.stop="removeStagList(scope.row,scope.index,'policy_buyAndGive')"
                    v-else
                >移除</el-button>
              </template>
            </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"
            :disabled="policyData.length === 0 && policyDataTwo.length === 0 && goodsListPolicy.length === 0 && buyAndGiveList.length === 0"
            :loading="saveLoading">导入</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="{}"
        itemType="销售"
        :arrList="applyPaymentList"
        @choceFun="choceFun"
      >
      </apply-payment>
    </el-dialog>

    <report-dialog
      :switchDialog="switchDialog"
      :reportId="form.id"
      reportName="销售明细(N)"
      @onClose="onClose()"
    />

    <el-dialog
      append-to-body
      title="账单"
      class="el-dialogDeep"
      :visible.sync="financialAccountDialog"
      width="70%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <financial-account
        v-if="financialAccountDialog"
        :billType="billType"
        :billData="{}"
        :arrList="applyPaymentList"
        :belongCompany="form.belongCompany"
        @choceFun="choceFun"
        @submit="feeSubmit"
      >
      </financial-account>
    </el-dialog>

    <el-dialog
      title="申请记录"
      append-to-body
      class="el-dialogDeep"
      :visible.sync="applicationDialog"
      width="60%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <bill-application
        :billId="form.id"
        @choceApplication="choceApplication"
      >
      </bill-application>
    </el-dialog>
    <el-dialog
      append-to-body
      title="审批"
      class="el-dialogDeep"
      :visible.sync="checkDialog"
      width="50%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <check
        :checkData="checkData"
        :checkDetail="false"
        :idList="[]"
        @choceCheckFun="choceCheckFun"
      >
      </check>
    </el-dialog>
    <el-dialog
      append-to-body
      title="审批进度"
      class="el-dialogDeep"
      :visible.sync="checkScheduleDialog"
      width="40%"
      :close-on-click-modal="false"
      :destroy-on-close="true"
      :close-on-press-escape="false"
      v-dialog-drag
    >
      <check-schedule
        :checkId="checkId"
        :batchNo="batchNo"
        @choceScheduleFun="choceScheduleFun"
      >
      </check-schedule>
    </el-dialog>
    <messagePost
      v-if="messageVisble"
      ref="messagePost"
      @closeDialog="closeDialog"
    />
    <changeApprove
      v-if="changeApproveVis"
      ref="changeApprove"
      @closeDialog="closeChangeApprove"
      :auditId="detailData.auditId"
      url="/api/blade-check/auditproecess/changeAuditUser"
      :routerTag="routerTag"
    />
  </div>
</template>

<script>
import {
  typeSave, detail, deleteDetails,
  corpstypeTree,
  corpsattn,
  corpsbank,
  corpsfiles,
  corpsitem,
  // getList,
  detailList,
  generateShipment,
  saveSell,
  getlistBankBy,
  getProfit,
  pleaseCheck,
  repealCancel,
  removeList
} from "@/api/basicData/configuration"
import {getList} from "@/api/basicData/commodityType";
import {getCorpDetail} from "@/api/maintenance/overpayment"
import {integralDetail} from "@/api/maintenance/integral"
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'
import feeInfo from "@/components/fee-info/main";
import {corpsAddrSelect, customerList as getKHList, detail as khDetail}  from "@/api/basicData/customerInformation";
import  billApplication from "@/components/bill/billApplication";
import {
  isDiscount,
  isPercentage,
  micrometerFormat,
  IntegerFormat
} from "@/util/validate";
import financialAccount from "../../../components/finance/financialAccount";
import { gainUser, getCharge } from "@/api/basicData/customerInquiry";
import check from "@/components/check/check";
import checkSchedule from "@/components/check/checkSchedule";
import { customerList as feeList } from "@/api/basicData/basicFeesDesc";
import {mapGetters} from "vuex";

export default {
  name: "detailsPage",
  props: {
    detailData: {
      type: Object
    }
  },
  components:{
    customerDialog,
    ApplyPayment,
    reportDialog,
    feeInfo,
    billApplication,
    financialAccount,
    check,
    checkSchedule,
  },
  data() {
    return {
      saveLoading: false,
      disabled: false,
      form: {
        corpId: null,
      },
      billType:"收费",  //账单类型
      billData:{},     //账单需要数据
      applySettlementDialog:false,//生成账单组件
      financialAccountDialog: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,
        pageSizes: [10,50,100,300,500]
      },
      pageList: {
        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: (node, resolve)=> {
          const parentId = (node.level === 0) ? 0 : node.data.id;
          const newTime = new Date().toLocaleString('chinese',{hour12:false}).replaceAll('/', '-')
          policyColumn({newTime: newTime,parentId: parentId,corps: this.form.corpId}).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',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '返利余额',
            prop: 'profit',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '产生返利',
            prop: 'createProfit',
            disabled: false,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '本次使用返利',
            prop: 'thisUsedProfit',
            disabled: false,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '应收账款',
            prop: 'debitAmount',
            type: 'number',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '已收款',
            prop: 'settlmentAmount',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '应收未收款',
            prop: 'balanceAmount',//无
            disabled: true,
            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: 'arrivalDate',
            type: 'datetime',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '毛利率',
            prop: 'grossProfitRate',
            display: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '毛利额',
            prop: 'grossProfit',
            type: 'number',
            display: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '历史运费(元/条)',
            prop: 'freightAmountHistory',
            type: 'number',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '预收款日期',
            type: 'datetime',
            prop: 'advanceCollectionDate',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '特价占比',
            prop: 'specialOfferOf',
            disabled: false,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '大尺寸占比',
            prop: 'largeScale',
            disabled: false,
          }, {
            label: '单据状态',
            prop: 'orderStatus',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '积分余额',
            prop: 'pointMutiple',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '赠送积分',
            prop: 'presenterIntegral',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '兑换积分',
            prop: 'convertIntegral',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '重量合计',
            prop: 'cartonWeight',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '体积合计',
            prop: 'cntrVolumn',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '制单人',
            prop: 'createUserName',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '制单日期',
            prop: 'createTime',
            type: 'datetime',
            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: 'belongToCorpId',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '付款方式',
            prop: 'paymentType',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          },{
            label: '包装要求',
            prop: 'packageRemarks',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          },
          {
            label: '银行帐号',
            prop: 'banks',
            type: 'select',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '公司户头',
            prop: 'banksAccountName',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '开户银行',
            prop: 'accountBank',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '客户全称',
            prop: 'corpId',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '到货地址',
            prop: 'arrivalAddress',
            span:16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '生产工厂',
            prop: 'productionPlant',
            span: 8,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          },
          {
            label: '发货地址',
            prop: 'shippingAddress',
            disabled: false,
            span: 16,
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'change'
              }
            ]
          },  {
            label: '销售订单号',
            prop: 'orderNo',
            disabled: true,
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '主订单号',
            prop: 'morderNo',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '是否收取标签费',
            prop: 'isLabel',
            type: 'radio',
          },
          {
            label: '是否包运费',
            prop: 'isFreight',
            type: 'radio',
          },
          {
            label: '预估运费',
            prop: 'predictOceanFreight',
            type: 'number',
            rules: [
              {
                required: true,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '要求发货日期',
            prop: 'requiredDeliveryDate',
            type: 'date',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          }, {
            label: '要求到货日期',
            prop: 'requiredArrivalDate',
            type: 'date',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'blur'
              }
            ]
          },{
            label: '业务员',
            prop: 'chargeMember',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '联系人',
            prop: 'corpAttn',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: '联系电话',
            prop: 'corpTel',
            rules: [
              {
                required: false,
                message: ' ',
                trigger: 'change'
              }
            ]
          }, {
            label: "订单备注",
            type: 'textarea',
            span: 24,
            prop: "orderRemark",
            mock: {
              type: 'county'
            }
          }
        ]
      },
      // 银行账号下拉
      bankList: [],
      paymentOption: [],
      statusOption: [],
      // 费用信息排序的最大值
      maxFeeNum: 0,
      maxGoodsNum: 0,
      oldForm: {
        orderStatus: "录入"
      },
      oldGoodsList: [],
      oldGiftList: [],
      oldFeesList: [],
      oldUploadList: [],
      // 采购价格
      purchasePriceOption: [],
      // 销售价格
      salesPriceOtion: [],
      // 弹窗高度
      rowHeight: '',
      // 查询时loading页面
      pageLoading: false,
      switchDialog: false,
      // 商品信息表格loading
      goodsLoading: false,
      // 上传时带的参数
      uploadPolicy: {
        policyName: '',
        salesType: 1
      },
      baseURL: '/api/blade-purchase-sales/orderitems/importPrice', // 商品明细上传路径
      policyUrl: '/api/blade-purchase-sales/orderitems/importPolicy', // 导入政策上传路径
      headers: { "Blade-Auth": 'Bearer ' + getToken()},
      activeName: 'searchList',
      // 商品列表数据合计
      goodsListShow: [],
      dataTwo: [],
      dataThree: [],
      // 商品列表暂存
      goodsListSave: [],
      goodsListPolicy: [],
      buyAndGiveList: [],
      goodsListTotal: 0,
      goodsListSaveTotal: 0,
      goodsActives: 'goods',
      saveActives: '',
      goodsDisabled: false,
      // 赠品信息数据
      giftData: [],
      // 商品信息展示数据
      goodsShowData: [],
      arrivalOptions: [],
      shippingOptions: [],
      applicationDialog:false,
      itemType: '销售',
      packageOptions: [],
      // 请核状态禁用
      browse: false,
      roleName: '',
      userList: [],
      feesOption: [],
      checkDisabled: false,
      checkData: {},
      checkDialog: false,
      checkScheduleDialog: false,
      checkId: '',
      batchNo:'',
      applyPaymentList: [],
      khInfoList: [],
      messageVisble: false, //消息弹窗开关
      changeApproveVis: false, // 更换审批人弹窗
      arrearsCheck: false, // 是否欠款发货审批
      shopQualityDisable: false, //质量胎切换禁用
      index: 0,
      policyIndex: 0,
      routerTag: '',
    }
  },
  mounted() {
    this.$nextTick(() => {
      // 监听浏览器高度变化，改变表格高度
      window.onresize = () => {
        this.rowHeight = (window.innerHeight - 130) + 'px'
      }
      this.routerTag = window.location.hash.slice(1);
    })
  },
  filters: {
    IntegerFormat(num) {
      return IntegerFormat(num);
    },
    decimalFormat(num) {
      return num ? Number(num).toFixed(2) : "0.00";
    }
  },
  //初始化查询
  async created() {
    this.rowHeight = (window.innerHeight - 130) + 'px'
    this.customerContact = await this.getColumnData(this.getColumnName(15), customerContact);
    this.getWorkDicts("payment_term").then(res => {
      this.paymentOption = res.data.data
    })
    this.getWorkDicts("order_status").then(res => {
      this.statusOption = res.data.data
    })
    this.getWorkDicts("packageRemarks").then(res => {
      this.packageOptions = res.data.data;
    });
    // 获取角色
    this.roleName = localStorage.getItem('roleName')
    if (!this.roleName.includes('admin') && !this.roleName.includes('assistant')) {
      this.contactInformation.column.forEach(item => {
        if (item.prop == 'grossProfitRate' || item.prop == 'grossProfit') item.display = false
      })
    }
    this.judgeNew()
    if (this.roleName == 'salesman') {
      this.customerContact.column.forEach(item => {
        if (item.prop == 'purchaseAmount') {
          item.hide = true;
          item.showColumn = false;
        }
      })
    }
    this.getDefault()
    if (this.detailData.id) {
      this.queryData(this.detailData.id)
    }
    if (this.detailData.check) {
      this.checkDisabled = true
      this.batchNo = this.detailData.check.batchNo
    }
    // gainUser().then(res => {
    //   this.userList = res.data.data;
    // });
    feeList().then(res => {
      this.feesOption = res.data.data.records
    })
    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)
    }
    this.oldForm = Object.assign({}, this.form);
    this.customerBuyFree.height = (window.innerHeight - 330) / 2;
    this.optionPolicy.height = (window.innerHeight - 330) / 2;
    this.customerContact.height = window.innerHeight - 240;
    this.index++;
    if(localStorage.getItem("roleName")=='salesman'){
        this.findObject(this.customerContact.column, "purchaseAmount").hide=true;
        this.findObject(this.customerContact.column, "purchaseAmount").showColumn=false;
    }
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.crudContact.doLayout();
    })
  },
  methods: {
    judgeNew(){
      if (!this.roleName.includes('salesman')){
        // for (let item of this.customerContact.column) {
        //   if (item.prop === 'purchaseAmount') return false
        // }
        // this.customerContact.column.push()
        for (let item of this.optionPolicy.column) {
          if (item.prop === 'purchasePrice') return false
        }
        // this.optionPolicy.column.push({
        //   "label": "采购价（元）",
        //   "prop": "purchasePrice",
        //   "index": 5,
        //   "width":100,
        //   "cell": true,
        //   "rules": [
        //     {
        //       "required": false,
        //       "message": " ",
        //       "trigger": "blur"
        //     }
        //   ]
        // })
        for (let item of this.customerBuyFree.column) {
          if (item.prop === 'purchasePrice') return false
        }
        // this.customerBuyFree.column.push({
        //       "label": "采购价（元）",
        //       "prop": "purchasePrice",
        //       "index": 4,
        //       "width":100,
        //       "cell": true,
        //       "rules": [
        //         {
        //           "required": false,
        //           "message": " ",
        //           "trigger": "blur"
        //         }
        //       ]
        //     })
      }
    },
    getGoodsRow(event,row) {
      row.priceCategory = event.goodsTypeName
      row.code = event.code
      row.typeno = event.typeno
      row.itemType = event.typeno
      row.itemId = event.id
      row.corpId = event.corpId
      row.corpName = event.corpName
      selectGoodsNum({
        goodsId: event.id,
        itemType: event.typeno,
        tradeType: 'GN'
      }).then(res => {
        row.storageQuantity =  res.data.data
      })
      row.integralMultiples = event.integralMultiples
      this.quantityChange(row)
    },
    queryData(id, isCopy = false,other){
      this.pageLoading = true
      this.saveLoading = true
      detail(id).then(async res => {
        this.form = res.data.data;
        this.browse = this.form.status > 0? true: false;
        this.arrearsCheck = this.form.specialCheckStatus == 3? true: false;
        await getProfit({Id: this.form.corpId}).then(res => {
          this.$set(this.form, 'profit',res.data.data.surplusProfit? res.data.data.surplusProfit: '0.00')
        })
        this.contactsData = this.form.orderItemsList.filter(item => {
          return item.goodType == 0
        })
        this.giftData = this.form.orderItemsList.filter(item => {
          return item.goodType == 1
        })
        this.goodsShowData = this.giftData;
        this.goodsActives = 'goods';
        this.handleClick({name: this.goodsActives})
        // this.contactsData = this.form.orderItemsList
        this.advantageProjectData = this.form.orderFeesList
        this.bankOfDepositData = this.form.orderFilesList
        this.configuration.dicData = this.form.corpName
        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.createFreightUser
        delete this.form.createPurchaseUser
        delete this.form.createPurchaseTime
        delete this.form.createFreightTime
        delete this.form.createFreight
        delete this.form.createPurchase
        delete this.form.specialCheckTime
        delete this.form.specialCheckUser
        delete this.form.specialCheckStatus
        delete this.form.specialCheck
        // 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.oldGiftList = []
        this.oldFeesList = []
        this.oldUploadList = []
        this.oldGoodsList = this.deepClone(this.contactsData)
        this.oldGiftList = this.deepClone(this.giftData)
        this.oldFeesList = this.deepClone(this.advantageProjectData)
        this.oldUploadList = this.deepClone(this.bankOfDepositData)
        if (isCopy) {
          this.$set(this.form, 'orderStatus', '录入')
          this.form.status = 0
          this.browse = false
          delete this.form.id
          delete this.form.orgOrderNo
          delete this.form.orderNo
          delete this.form.morderNo
          delete this.form.createUserName
          delete this.form.createTime
          delete this.form.businesDate
          this.contactsData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.goodsShowData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.giftData.forEach(item => {
            delete item.id
            delete item.pid
          })
          this.advantageProjectData = []
          this.bankOfDepositData = []
          this.bankOfDepositData.forEach(item => {
            delete item.id
            delete item.pid
          })
        }
        if (other === 'check'){
          this.pleaseCheck()
        }
      }).finally(() => {
        this.saveLoading = false
        this.pageLoading = false
      });
    },
    getDefault() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      let nowDate = year + "-" + month + "-" + day + ' 00:00:00';
      this.$set(this.form, 'businesDate', nowDate)
      this.$set(this.form, 'orderStatus', '录入')
      this.$set(this.form, 'caseOverPayment', 0)
      this.$set(this.form, 'overPayment', 0)
      this.$set(this.form, 'orderAmount', 0)
      this.$set(this.form, 'predictOceanFreight', 0)
      this.$set(this.form, 'presenterIntegral' , 0)
      this.$set(this.form, 'convertIntegral' , 0)
      this.$set(this.form, 'profit' , 0)
      this.$set(this.form, 'paymentType', '预付')
      this.$set(this.form, 'thisUsedProfit' , 0)
      this.$set(this.form, 'createProfit' , 0)
      this.$set(this.form, 'isFreight' , 0)
      this.$set(this.form, 'isLabel' , 0)
    },
    // 复制新单
    copyOrder() {
      this.saveActives = ''
      this.queryData(this.form.id, true)
    },
    getcorpId(row) {
      this.goodsShowData[row.index].corpId = row.id;
      this.goodsShowData[row.index].corpName = row.cname;
    },
    // 采购金额获取
    getPurchasePrice(row) {
      getPurchasePrice({code: row.code}).then(res => {
        this.purchasePriceOption = res.data.data
      })
    },
    // 销售金额获取
    getMarketPrice(row) {
      getMarketPrice({code: row.code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(res => {
        this.salesPriceOtion = res.data.data
      })
    },
    // 生成采购单
    saveSell() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        // contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          await this.editCustomer(false, '采购')
        }).catch(() => {
          this.$message.info('已取消')
        })
      } else {
        if ((Number(this.form.settlmentAmount) < Number(this.form.debitAmount)) && !this.arrearsCheck) return this.$message.error('收款未收齐，禁止生成采购单');
        this.$confirm("是否生成采购单?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          saveSell(this.form.id).then(res => {
            if (res.data.code == 200) {
              this.$message.success("生成成功");
              this.messageVisble = true
              this.$nextTick(() => {
                this.$refs.messagePost.init()
              })
            }
          });
        });
      }
    },
    closeDialog() {
      this.messageVisble = false
    },
    //点击行可编辑
    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, row.$index)
    },
    //费用编辑
    rowCellTwo(row, index) {
      this.$refs.crudProject.rowCell(row, row.$index)
    },
    //费用新增触发
    costIncrease() {
      this.dialogCost = !this.dialogCost
      this.choiceData = false
    },
    //商品新增触发
    commoditySelection() {
      this.dialogVisible = !this.dialogVisible
      this.tableData = []
      this.commodityData = false
      this.goodsListSave = [];
    },
    //政策价格导入
    policy() {
      this.$set(this.customerBuyFree,'menu',true)
      this.$set(this.optionPolicy,'menu',true)
      this.customerBuyFree.selection = true
      this.optionPolicy.selection = true
      this.activeName = 'searchList'
      this.goodsListPolicy = []
      this.buyAndGiveList = []
      this.policyDialog = !this.policyDialog
    },
    // 报表
    openReport() {
      this.switchDialog =! this.switchDialog;
    },
    // 导出
    exportHandle() {
      this.$confirm('是否导出产品信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-client/goodsdesc/export-out-info?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      })
    },
    // 下载模板
    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.openFullScreen(false, '文件正在解析中');
    },
    // 商品明细上传成功钩子
    importTemplate(res, file) {
      this.openFullScreen(true)
      let goodsData = []
      if(res.data.lose.length>0){
         this.$message({
          showClose: true,
          message: '导入明细失败的大字有:'+res.data.lose.toString(),
          type: 'error',
          duration:10000,
        });
      }
      res.data.list.forEach(item => {
        getMarketPrice({code: item.code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(response => {
          if (response.data.data.length > 0) {
            this.$set(item, 'price', response.data.data[0].salePrice)
          } else {
            this.$set(item, 'price', '0')
          }
          this.priceChange(item)
          // this.$set(item, 'amount', (Number(item.price) * Number(item.orderQuantity)).toFixed(2))
        })
        getPurchasePrice({code: item.code}).then(response => {
          if (response.data.data.length > 0) {
            this.$set(item, 'purchaseAmount', response.data.data[0].purchasePrice)
          } else {
            this.$set(item, 'purchaseAmount', '0')
          }
        })
        this.$set(item, 'integral', Number(item.integralMultiples) * Number(item.orderQuantity))
        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 = {
          ...item,
        }
        goodsData.push(a)
      })
      this.goodsConfiguration.dicData = this.goodsConfiguration.dicData.concat(goodsData)
      this.removeGoodsRepeat()
      this.goodsShowData = this.goodsShowData.concat(res.data.list)

    },
    // 政策导入成功钩子
    successPolicy(res, file) {
      this.openFullScreen(true)
      if (res.data.message === "" && !res.data.message) {
        this.dataPolicy = res.data.list? res.data.list: [];
        this.dataPolicy.forEach(item=>{
          this.$set(item, 'priceType', res.data.cname)
        })
        this.policyIndex++;
      } else {
        this.dataPolicy = res.data.list? res.data.list: [];
        this.dataPolicy.forEach(item=>{
          this.$set(item, 'priceType', res.data.cname)
        })
        this.policyIndex++;
        this.$message({
          showClose: true,
          message:res.data.message,
          type: 'error',
          duration:100000,
        });
      }
    },
    uploadError(err, file, fileList) {
      this.openFullScreen(true)
      this.$message.error(JSON.parse(err.message).msg)
    },
    //遮罩层
    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() {
      for (let item in this.selection) {
        if (!this.selection[item].id) {
          return this.$message.error('选中数据有新数据，请先保存')
        }
      }
      if (this.$store.getters.inStatus) {
        this.$alert("客户收货存在,请保存客户收货再进行操作", "温馨提示", {
          confirmButtonText: "确定",
          type: "warning",
          callback: action => {
            console.log(action);
          }
        });
      } else {
        this.generateShipmentD();
      }
    },
    //生成发货单
    async generateShipmentD() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        // contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false, '发货')
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        })
      } else {
        // if (Number(this.form.debitAmount) > Number(this.form.settlmentAmount)) {
        //   return this.$message.error('已收款小于未收款，不能生成客户确认单')
        // }
        let lsit = []
        this.selection = this.selection.concat(this.giftData)
        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),
              pageType: "Generate",
            },
          });
        })
      }
    },
    // 生成结算
    applySettlement(type) {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        // contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false, type)
        }).catch(() => {
        })
      } else {
        this.beforeBillData(true,type)
        this.financialAccountDialog = true;
      }
    },
    //生成账单 拿到主表信息
    beforeBillData(bool,type){
      this.applyPaymentList = [];
      let arr = [];
      this.billType = type
      const data = this.goodsActives === 'gift'? this.contactsData: this.goodsShowData
      data.map(e => {
        if (e.submitPay != 1) {
          const form = {
            belongCompany: this.form.belongCompany,
            srcOrderno:this.form.orgOrderNo,
            itemType:"销售",
            corpsName:this.form.corpName,
            corpId:this.form.corpId,
            srcParentId: this.form.id,
            currency: 'CNY',
            exchangeRate: '1',
            taxRate: '0',
            accDate: this.form.businesDate,
            srcType: 1,
            tradeType: 'GN',
            optionType: 'GN',
            chargeMember: this.form.chargeMember,
            amount: e.amount,
            quantity: e.orderQuantity, // 数量
            price: e.price,
            unit: e.unit,
            goodName: e.cname,
            srcFeesId: e.id,
            costType: this.feesOption.find(e => e.cname == '货款')? this.feesOption.find(e => e.cname == '货款').id: null,
          }
          arr.push(form)
        }
      })
      let getFeeList = this.$refs.feeInfo.submitData().filter(item => item.feesType == 1 && item.submitPay != 1)
      getFeeList.forEach(item => {
        let form = {
          srcOrderno:this.form.orgOrderNo,
          itemType:"销售",
          corpsName:this.form.corpName,
          corpId:this.form.corpId,
          srcParentId: this.form.id,
          currency: 'CNY',
          exchangeRate: '1',
          taxRate: '0',
          accDate: this.form.businesDate,
          srcType: 2,
          tradeType: 'GN',
          optionType: 'GN',
          chargeMember: this.form.chargeMember,
          parentId: this.form.id,
          amount: item.amount,
          costType: item.itemId,
          srcFeesId: item.id,
          quantity: item.quantity, // 数量
          price: item.price,
        }
        arr.push(form)
      })
      this.applyPaymentList = [...arr]
      if(bool){ //申请货款
        // this.billData.srcId = -1
      }
    },
    //关闭账单
    choceFun(){
      this.financialAccountDialog  = false
    },
    feeSubmit() {
      this.saveActives = ''
      this.queryData(this.form.id);
    },
    //商品选中触发
    productSelection(selection) {
      this.selection = selection
    },
    //点击费用明细选择触发
    choice(row) {
      this.dialogCost = !this.dialogCost
      this.choiceData = true
      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
      }, [])
    },
    async getCorpRow(data) {
      getCharge('KH', data.id).then(res => {
        this.userList = res.data.data;
      })
      khDetail(data.id).then(res => {
        if (res.data.data.adminProfiles) {
          res.data.data.adminProfiles = res.data.data.adminProfiles.split(",");
          let arr = [];
          res.data.data.adminProfiles.forEach(e => {
            arr.push(this.userList.find(item => item.id == e).cname)
          })
          this.$set(this.form, 'chargeMember', arr[0])
        }
        if (res.data.data.corpsAttnList.length > 0) {
          this.khInfoList = res.data.data.corpsAttnList;
          this.$set(this.form, 'corpAttn', res.data.data.corpsAttnList[0].cname);
          this.$set(this.form, 'corpTel', res.data.data.corpsAttnList[0].tel);
        } else {
          this.khInfoList = [];
          this.$set(this.form, 'corpAttn', null);
          this.$set(this.form, 'corpTel', null);
        }
      })
      if (data.belongtocompany) {
        // this.form.belongToCorpId = data.belongtocompany
        // this.returnBack({id: this.form.belongToCorpId})
      }
      getCorpDetail({corpId:data.id}).then(res => {
        this.form.overPayment = res.data.data? res.data.data.balanceOverpaymen: 0
      })
      integralDetail({corpId:data.id}).then(res => {
        this.form.pointMutiple = res.data.data? res.data.data.balancePoints: 0
      })
      getProfit({Id: data.id}).then(res => {
        this.form.profit = res.data.data.surplusProfit? res.data.data.surplusProfit: '0.00'
      })
      this.arrivalOptions = [];
      this.arrivalOptions = await this.corpAddr(data.id)
      this.$set(this.form, 'paymentType', data.paymentType? data.paymentType: '预付')
      this.$set(this.form, 'packageRemarks', data.packageRemarks? data.packageRemarks: '塑料')
      if (this.arrivalOptions.length > 0) {
        this.$set(this.form, 'arrivalAddress', this.arrivalOptions[0].label)
      } else {
        this.$set(this.form, 'arrivalAddress', null)
      }
    },
    async getPlantRow(data) {
      this.shippingOptions = [];
      this.shippingOptions = await this.corpAddr(data.id)
      if (this.shippingOptions.length > 0) {
        this.$set(this.form, 'shippingAddress', this.shippingOptions[0].label)
      } else {
        this.$set(this.form, 'shippingAddress', null)
      }
    },
    getRow(event,row) {
      row.priceCategory = event[0].goodsTypeName
      row.code = event[0].code
      row.typeno = event[0].typeno
      row.itemType = event[0].typeno
      row.itemId = event[0].id
      row.corpId = event[0].corpId
      row.corpName = event[0].corpName
      selectGoodsNum({
        goodsId: event[0].id,
        itemType: event[0].typeno,
        tradeType: 'GN'
      }).then(res => {
        row.storageQuantity =  res.data.data
      })
      row.integralMultiples = event[0].integralMultiples
      this.quantityChange(row)
    },
    //点击商品明细选择触发
    commodityChoice(row) {
      this.dialogVisible = !this.dialogVisible
      this.commodityData = true
      this.choiceIndexT = row.$index
    },
    //导入商品触发
    importChoice() {
      // this.contactsData = this.contactsData.concat(this.tableData)
      if (this.tableData.length === 1) {
        this.goodsShowData[this.choiceIndexT].cname = this.tableData[0].cname
        this.goodsShowData[this.choiceIndexT].code = this.tableData[0].code
        this.goodsShowData[this.choiceIndexT].typeno = this.tableData[0].typeno
        this.goodsShowData[this.choiceIndexT].itemType = this.tableData[0].typeno
        this.goodsShowData[this.choiceIndexT].itemId = this.tableData[0].id
        this.goodsShowData[this.choiceIndexT].priceCategory = this.tableData[0].goodsTypeName
        this.goodsShowData[this.choiceIndexT].integralMultiples = this.tableData[0].integralMultiples
        this.goodsShowData[this.choiceIndexT].corpId = this.tableData[0].corpId
        this.goodsShowData[this.choiceIndexT].corpName = this.tableData[0].corpName
        this.quantityChange(this.goodsShowData[this.choiceIndexT])
        selectGoodsNum({
          goodsId: this.tableData[0].id,
          itemType: this.tableData[0].typeno,
          tradeType: 'GN'
        }).then(res => {
          this.goodsShowData[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) {
          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.$set(this.tableDataCost[item], 'corpId', this.form.corpId)
          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
    },
    //确认导入触发
    async importGoods() {
      if (this.goodsListSave.length > 0) {
        this.goodsListSaveHandle()
      } else {
        if (this.tableData.length > 0) {
          this.tableDataHandle()
        }
      }
    },
    goodsListSaveHandle() {
      this.saveLoading = true;
      for (let item in this.goodsListSave) {
        getMarketPrice({code: this.goodsListSave[item].code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(res => {
          if (res.data.data.length > 0) {
            this.$set(this.goodsListSave[item], 'price', res.data.data[0].salePrice)
          } else {
            this.$set(this.goodsListSave[item], 'price', '0')
          }
          this.priceChange(this.goodsListSave[item])
        })
        selectGoodsNum({
          goodsId: this.goodsListSave[item].id,
          itemType: this.goodsListSave[item].typeno,
          tradeType: 'GN'
        }).then(res => {
          this.$set(this.goodsListSave[item], 'storageQuantity', res.data.data)
          // this.goodsListSave[item].storageQuantity =  res.data.data
          this.$set(this.goodsListSave[item], 'priceCategory', this.goodsListSave[item].goodsTypeName)
          // this.goodsListSave[item].priceCategory = this.goodsListSave[item].goodsTypeName
          delete this.goodsListSave[item].goodsTypeName
          this.goodsListSave[item].itemId = this.goodsListSave[item].id
          this.$set(this.goodsListSave[item], 'corpName', this.goodsListSave[item].corpName)
          this.$set(this.goodsListSave[item], 'itemType', this.goodsListSave[item].typeno)
          // this.$set(this.goodsListSave[item], 'orderQuantity', 1)
          this.$set(this.goodsListSave[item], 'actualQuantity', 0)
          this.$set(this.goodsListSave[item], 'invoiceWeight', this.goodsListSave[item].cartonWeight)
          this.$set(this.goodsListSave[item], 'shopQuality', 0)
          this.$set(this.goodsListSave[item], 'inputMold', 0) // 判断是商品还是政策 商品 0 特价 1 买赠2
          // this.$set(this.goodsListSave[item], 'priceType', this.goodsListSave[item].policyName)
          this.goodsListSave[item].amount = 0
          if (this.goodsActives == "goods") {
            this.$set(this.goodsListSave[item], 'goodType', 0)
          } else {
            this.$set(this.goodsListSave[item], 'goodType', 1)
            this.$set(this.goodsListSave[item], 'integralMultiples', this.goodsListSave[item].integral)
          }
          this.$set(this.goodsListSave[item], 'integral', '0')
          this.goodsListSave[item].sort = this.maxGoodsNum + 1
          if (this.form.packageRemarks) {
            this.goodsListSave[item].packageRemarks = this.form.packageRemarks
          }
          delete this.goodsListSave[item].id
          delete this.goodsListSave[item].pid
          delete this.goodsListSave[item].isDeleted
          delete this.goodsListSave[item].status
          delete this.goodsListSave[item].tenantId
          delete this.goodsListSave[item].updateTime
          delete this.goodsListSave[item].updateUser
          delete this.goodsListSave[item].updateUserName
          this.maxGoodsNum++

          getPurchasePrice({code: this.goodsListSave[item].code}).then(res => {
            if (res.data.data.length > 0) {
              this.$set(this.goodsListSave[item], 'purchaseAmount', res.data.data[0].purchasePrice)
            } else {
              this.$set(this.goodsListSave[item], 'purchaseAmount', '0')
            }
            this.quantityChange(this.goodsListSave[item])
            this.$refs.crudContact.rowCellAdd(this.goodsListSave[item]);
            this.$nextTick(() => {
              this.quantityChange(this.goodsListSave[item])
            })
          })
          // this.$refs.crudContact.rowCell(this.goodsListSave[item], this.goodsListSave.length - 1)
        })
      }
      this.saveLoading = false;
      this.dialogVisible = false
    },
    tableDataHandle() {
      this.saveLoading = true;
      for (let item=0;item<this.tableData.length;item++) {
        getMarketPrice({code: this.tableData[item].code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(res => {
          if (res.data.data.length > 0) {
            this.$set(this.tableData[item], 'price', res.data.data[0].salePrice)
          } else {
            this.$set(this.tableData[item], 'price', '0')
          }
          this.priceChange(this.tableData[item])
        })
        selectGoodsNum({
          goodsId: this.tableData[item].id,
          itemType: this.tableData[item].typeno,
          tradeType: 'GN'
        }).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], 'corpName', this.tableData[item].corpName);
          this.$set(this.tableData[item], 'itemType', this.tableData[item].typeno);
          // this.$set(this.tableData[item], 'orderQuantity', 1);
          this.$set(this.tableData[item], 'actualQuantity', 0);
          this.$set(this.tableData[item], 'shopQuality', 0);
          this.$set(this.tableData[item], 'invoiceWeight', this.tableData[item].cartonWeight);
          this.$set(this.tableData[item], 'inputMold', 0);
          // this.$set(this.tableData[item], 'priceType', this.tableData[item].policyName);
          this.tableData[item].amount = 0;
          if (this.goodsActives == "goods") {
            this.$set(this.tableData[item], 'goodType', 0)
          } else {
            this.$set(this.tableData[item], 'goodType', 1)
            this.$set(this.tableData[item], 'integralMultiples', this.tableData[item].integral)
          }
          this.$set(this.tableData[item], 'integral', '0')
          this.tableData[item].sort = this.maxGoodsNum + 1
          if (this.form.packageRemarks) {
            this.tableData[item].packageRemarks = this.form.packageRemarks
          }
          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++
          getPurchasePrice({code: this.tableData[item].code}).then(rest => {
            if (rest.data.data.length > 0) {
              this.$set(this.tableData[item], 'purchaseAmount', rest.data.data[0].purchasePrice)
            } else {
              this.$set(this.tableData[item], 'purchaseAmount', '0')
            }
            this.quantityChange(this.tableData[item])
            this.$refs.crudContact.rowCellAdd(this.tableData[item]);
            this.$nextTick(() => {
              this.quantityChange(this.tableData[item])
            })
          })
          // this.$refs.crudContact.rowCell(this.tableData[item], this.tableData.length - 1)
        })
      }
      this.saveLoading = false;
      this.dialogVisible = false
    },
    closeGoods() {
      this.treeDataGoods = [];
      this.treeDeptId = "";
      this.activeName = "searchList";
    },
    closeFees() {
      this.treeDeptIdCost = "";
      this.treeData = [];
    },
    closePolicy() {
      this.treePolicyId = '';
      this.uploadPolicy.policyName = ''
      this.dataPolicy = [];
      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.uploadPolicy.policyName = data.id;
      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.treeDeptId = ''
      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
        this.customerBuyFree.menu = false
      } else {
        this.customerBuyFree.selection = true
        this.customerBuyFree.menu = true
      }
    },
    //销售政策买赠促销选中触发
    selectionChangePolicyTwo(list) {
      this.policyDataTwo = list
      // this.policyDataTwo.forEach(item => {
      //   this.$set(item, 'price', item.salePrice)
      // })
      if (this.policyDataTwo.length > 0) {
        this.optionPolicy.selection = false
        this.optionPolicy.menu = false
      } else {
        this.optionPolicy.selection = true
        this.optionPolicy.menu = true
      }
    },
    //匹配id去重
    deWeightFour(arr) {
      let arrTemp = [];
      arr = arr.reduce(function (a, b) {
        if ( arrTemp.indexOf(b.id+b.id)==-1 ) {
          a.push(b)
          arrTemp.push(b.id+b.id)
        }
        return a
      }, [])
      return arr
    },
    //导入商品政策
    importPolicy() {
      let list = []
      if (this.buyAndGiveList.length > 0 || this.goodsListPolicy > 0){
        list = this.deepClone(this.buyAndGiveList.concat(this.goodsListPolicy))
      }else {
        list = this.deepClone(this.policyData.concat(this.policyDataTwo))
      }
      // list = this.deWeightFour(list)
      let listLength = this.policyDataTwo.length + this.buyAndGiveList.length
      // 买赠额外加一条
      let buyFree = []
      if (this.policyDataTwo.length > 0 || this.goodsListPolicy.length > 0 || this.buyAndGiveList.length >0) {
        buyFree = this.deepClone((this.policyDataTwo.concat(this.goodsListPolicy)).concat(this.buyAndGiveList))
      }
      for (let item in list) {
        if (this.policyData.length > 0 || this.buyAndGiveList > 0) {
          if (!list[item].specialOffer) {
            getMarketPrice({code: list[item].code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(response => {
              if (response.data.data.length > 0) {
                this.$set(list[item], 'price', response.data.data[0].salePrice)
              } else {
                this.$set(list[item], 'price', '0')
              }
              this.priceChange(list[item])
            })
          } else {
            this.$set(list[item], 'price', list[item].specialOffer)
            this.priceChange(list[item])
          }
          this.$set(list[item], 'inputMold', 1)
          this.$set(list[item], 'goodType', 0)
        } else {
          if (!list[item].salePrice) {
            getMarketPrice({code: list[item].code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(response => {
              if (response.data.data.length > 0) {
                this.$set(list[item], 'price', response.data.data[0].salePrice)
              } else {
                this.$set(list[item], 'price', '0')
              }
              this.priceChange(list[item])
            })
          } else {
            this.$set(list[item], 'price', list[item].salePrice)
            this.priceChange(list[item])
          }
          this.$set(list[item], 'inputMold', 2)
          this.$set(buyFree[item], 'inputMold', 2)
          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], 'goodType', 0)
        }
        selectGoodsNum({
          goodsId: list[item].itemId,
          itemType: list[item].typeno,
          tradeType: 'GN'
        }).then(res => {
          this.$set(list[item], 'storageQuantity', res.data.data)
          if (listLength != 0) {
            this.$set(buyFree[item], 'storageQuantity', res.data.data)
          }
          this.$set(list[item], 'goodType', 0)
          this.$set(list[item], 'itemType',  list[item].typeno)
          this.$set(list[item], 'actualQuantity', 0)
          this.$set(list[item], 'orderQuantity', list[item].orderQuantity? list[item].orderQuantity: 0)
          // this.$set(list[item], 'amount', 0)
          this.$set(list[item], 'priceCategory', list[item].productCategory)
          if(this.policyForm.cname){
            this.$set(list[item], 'priceType', this.policyForm.cname)
          }
          this.$set(list[item], 'cname', list[item].productCategory)
          this.$set(list[item], 'sort', this.maxGoodsNum + 1)
          console.log(list[item])
          this.$set(list[item], 'purchaseAmount', list[item].purchasePrice)
          // 积分
          this.$set(list[item], 'integralMultiples', 0)
          this.$set(list[item], 'integral', 0)
          this.$set(list[item], 'shopQuality', 0)

          if (listLength != 0) {
            this.$set(buyFree[item], 'actualQuantity', 0)
            this.$set(buyFree[item], 'orderQuantity', 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.$set(buyFree[item], 'integralMultiples', 0)
            this.$set(buyFree[item], 'integral', 0)
            this.$set(buyFree[item], 'shopQuality', 0)
            this.$set(buyFree[item], 'goodType', 0)
            this.maxGoodsNum++
            delete buyFree[item].id
            delete buyFree[item].pid
            delete buyFree[item].isDeleted
            delete buyFree[item].status
            delete buyFree[item].tenantId
            delete buyFree[item].updateTime
            delete buyFree[item].updateUser
            delete buyFree[item].updateUserName
          }
          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.$nextTick(() => {
            this.quantityChange(list[item])
          })
          if (listLength != 0) {
            this.$refs.crudContact.rowCellAdd(buyFree[item]);
            this.quantityChange(buyFree[item])
          }
        })
      }
      this.policyDialog = false
    },
    //费用刷新触发
    refreshChangeCost() {
      this.treeDeptIdCost = '';
      this.pageCost.currentPage = 1;
      this.onLoadCost(this.pageCost);
    },
    //新增商品信息保存触发
    rowSave(row, done, loading) {
      // 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.goodsShowData.splice(row.$index, 1);
            if (this.goodsActives == 'goods') {
              this.form.presenterIntegral = 0;
              this.form.orderAmount = 0;
              this.goodsShowData.forEach(item => {
                this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
                this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
              })
              this.computedCost()
            } else {
              this.form.convertIntegral = 0;
              this.goodsShowData.forEach(item => {
                this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
              })
            }
          })
        } else {
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.goodsShowData.splice(row.$index, 1);
          if (this.goodsActives == 'goods') {
            this.form.presenterIntegral = 0;
            this.form.orderAmount = 0;
            this.goodsShowData.forEach(item => {
              this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
              this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
            })
            this.computedCost()
          } else {
            this.form.convertIntegral = 0;
            this.goodsShowData.forEach(item => {
              this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
            })
          }
        }
      })
    },
    // 批量删除
    removeList() {
      const isId = this.selection.filter(item => item.id);
      const noId = this.selection.filter(item => !item.id);
      const ids = []
      isId.forEach(e => ids.push(e.id));
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.goodsLoading = true;
        if (ids.length > 0) {
          removeList(ids.join(',')).then(res => {
            this.selection.forEach(item => {
              const index = this.goodsShowData.findIndex(e => e == item);
              this.goodsShowData.splice(index, 1);
            })
            this.$message.success('删除成功')
          }).finally(() => {
            this.goodsLoading = false;
          })
        } else {
          this.selection.forEach(item => {
            const index = this.goodsShowData.findIndex(e => e == item);
            this.goodsShowData.splice(index, 1);
          })
          this.$message.success('删除成功')
          this.goodsLoading = false;
        }
      })
    },
    //新增费用明细保存触发
    rowSaveProject(row, done, loading) {
      // this.advantageProjectData.push(row)
      done()
    },
    //修改费用明细触发
    rowUpdateProject(row, index, done, loading) {
      done(row);
    },
    policyOnLoad(params = {}) {
      this.loadingPolicy = true;
      this.policyForm = {};
      detailList(this.treePolicyId).then(res => {
        this.policyForm = res.data.data;
        //特价促销
        if(res.data.data.specialItemList) {
          this.dataPolicy = res.data.data.specialItemList
          this.dataPolicy.forEach(item => {
            this.$set(item, 'orderQuantity', 0);
          })
        } else {
          this.dataPolicy = []
        }
        //买赠促销
        if (res.data.data.presentItemList) {
          this.contactsDataBuyFree = res.data.data.presentItemList
        } else {
          this.contactsDataBuyFree = []
        }
      }).finally(() => {
        this.loadingPolicy = false;
      })
    },
    //
    goodsSearch(params, done) {
      this.treeDeptId = ''
      params = {
        ...params,
        artsVision: this.form.belongToCorpId
      }
      this.onLoad(this.page, params);
      done()
    },
    //商品列表查询
    onLoad(page, params = {artsVision: this.form.belongToCorpId}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query), this.treeDeptId, null).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.pageList.total = data.total
        this.data = data.records;
        this.goodsListShow = data.records;
        this.loading = false;
      });
    },
    // 费用查询按钮
    feesSearch(params, done) {
      this.treeDeptIdCost = '';
      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 => {
        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.success("操作成功!");
            this.advantageProjectData.splice(row.$index, 1);
          })
        } else {
          this.$message.success("操作成功!");
          this.advantageProjectData.splice(row.$index, 1);
        }
      })
    },
    //修改提交触发
    async editCustomer(isBack = false, type,other) {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          const length = this.goodsActives === 'gift' ? this.contactsData.length : this.goodsShowData.length
          const length1 = this.goodsActives === 'goods' ? this.giftData : this.goodsShowData
          for (let i = 0; i < length; i++) {
            const data = this.goodsActives === 'gift' ? this.contactsData : this.goodsShowData;
            if (Number(data[i].orderQuantity) > Number(data[i].storageQuantity)) {
              return this.$message.error('商品信息第' + (Number(i) + 1) + '行订货数量大于库存数量')
            }
            if (Number(data[i].purchaseAmount) === 0) {
              return this.$message.error('商品信息第' + (parseInt(i) + 1) + '行采购价格不能为0')
            }
            if (!Number(data[i].purchaseAmount)) {
              return this.$message.error('商品信息第' + (parseInt(i) + 1) + '行采购价格不能为空')
            }
          }
          let integral = 0;//积分
          if (length1) {
            length1.forEach(item => {
              integral += Number(item.integral)
            })
          }
          if (Number(this.form.pointMutiple) < Number(integral)) return this.$message.error('积分余额不足')
          //商品信息
          if (this.goodsActives == 'gift') {
            this.form.orderItemsList = this.goodsShowData.concat(this.contactsData)
          } else {
            this.form.orderItemsList = this.goodsShowData.concat(this.giftData)
          }
          // 判断是否能保存
          let goodsData = this.form.orderItemsList.filter(item => item.goodType == 0)
          // 计算特价占比
          let allNum = 0; // 总数量
          let specialNum = 0; // 特价数量
          let sizeNum = 0; // 大尺寸数量
          goodsData.forEach(item => allNum += Number(item.orderQuantity));
          // inputMold判断是商品还是政策 商品 0 特价 1 买赠2,isSpecial 0正常 1特价
          goodsData.filter(item => item.inputMold === 1 && item.isSpecial === 1).forEach(item => specialNum += Number(item.orderQuantity));
          goodsData.filter(item => Number(item.size) >= 17).forEach(item => sizeNum += Number(item.orderQuantity));
          this.$set(this.form, 'specialOfferOf', allNum == 0 ? '0.00' : (specialNum / allNum * 100).toFixed(2));
          this.$set(this.form, 'largeScale', allNum == 0 ? '0.00' : (sizeNum / allNum * 100).toFixed(2));
          for (let item in goodsData) {
            if (Number(goodsData[item].orderQuantity) > Number(goodsData[item].storageQuantity)) {
              return this.$message.error('商品信息第' + (parseInt(item) + 1) + '行订货数量不能超过库存')
            }
          }
          this.form.orderFeesList = this.$refs.feeInfo.submitData()
          let packFee;
          if (this.form.packageRemarks && this.form.packageRemarks !== '无包装' && this.form.packageRemarks !== '不包装') {
            let arr = this.form.orderFeesList.filter(item => item.feesType == 1)
            packFee = arr.findIndex(item => item.feeName == '包装费')
          }
          if (packFee == -1) {
            return this.$message.error('费用明细未有包装费')
          }
          // 产生返利、本次使用返利为空 默认为0
          this.form.createProfit = this.form.createProfit ? this.form.createProfit : 0
          this.form.thisUsedProfit = this.form.thisUsedProfit ? this.form.thisUsedProfit : 0
          // 计算毛利额
          this.$set(this.form, 'orderAmount', 0)
          // 成本价
          let purchaseAmount = 0
          if (this.form.orderAmount && this.form.settlmentAmount) {
            this.$set(this.form, "balanceAmount", (Number(this.form.orderAmount) - Number(this.form.settlmentAmount)).toFixed(2));
          }
          // 销售金额
          this.form.orderAmount = 0;
          // 计算销售金额
          console.log(this.form.orderItemsList)
          this.form.orderItemsList.forEach(item => {
            if (item.goodType == 0) {
              if (item.purchaseAmount) {
                purchaseAmount += (Number(item.purchaseAmount) * Number(item.orderQuantity)).toFixed(2)
              }
              this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
            }
          })
          // 判断订货数量不能小于等于0
          for (let item in this.form.orderItemsList) {
            if (Number(this.form.orderItemsList[item].orderQuantity) <= 0) {
              return this.$message.error('订货数量不能小于等于0')
            }
          }
          // 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'
          // 如果有id解锁，没有跳过
          // this.form.id && this.unLock({moduleName: 'xs',tableName: 'business_order', billId: this.form.id})
          this.saveLoading = true
          await this.computedCost()
          typeSave(this.form).then(res => {
            // this.$set(this.detailData, 'seeDisabled', true);
            if (!other) {
              this.$message({type: "success", message: this.form.id ? "修改成功!" : "新增成功!"});
            }
            if (isBack) {
              //成功关闭此页面回到列表页
              this.$emit("goBack");
              this.leaveDetailsKey(this.$route.name)
            } else {
              this.saveActives = ''
              this.queryData(res.data.data.id, false, other)
            }
            if (type == '发货') {
              let lsit = []
              this.selection = this.selection.concat(this.giftData)
              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), pageType: "Generate",},
                });
              })
            } else if (type == '采购') {
              if ((Number(this.form.settlmentAmount) < Number(this.form.debitAmount)) && !this.arrearsCheck) return this.$message.error('收款未收齐，禁止生成采购单');
              this.$confirm("是否生成采购单?", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }).then(() => {
                saveSell(this.form.id).then(res => {
                  if (res.data.code == 200) {
                    this.$message.success("生成成功");
                    this.messageVisble = true
                    this.$nextTick(() => {
                      this.$refs.messagePost.init()
                    })
                  }
                });
              });
            } else if (type == '收费') {
              this.beforeBillData(true, type)
              this.applySettlementDialog = true;
            }
          }).finally(() => {
            this.saveLoading = false
          })
        } else {
          return this.$message.error('存在漏填必填项，请补全');
        }
      });
    },
    // 计算应收未收款
    computedCost() {
      // if (Number(this.form.caseOverPayment) > Number(this.form.overPayment)) {
      //   this.form.caseOverPayment = 0;
      //   return this.$message.error('本次使用的溢付款不能超过总溢付款')
      // }
      if (Number(this.form.thisUsedProfit) > Number(this.form.profit)) {
        this.form.thisUsedProfit = 0;
        return this.$message.error('本次使用的返利不能超过返利余额')
      }
      // 销售金额
      let orderAmount = this.form.orderAmount? this.form.orderAmount: 0
      // 已收款
      let settlmentAmount = this.form.settlmentAmount? this.form.settlmentAmount: 0
      // 本次溢付款
      // let caseOverPayment = this.form.caseOverPayment? this.form.caseOverPayment: 0
      // 本次试用返利
      let thisUsedProfit = this.form.thisUsedProfit? this.form.thisUsedProfit: 0
      let feeAmountD = 0; //费用明细应收
      let feeAmountC = 0; //费用明细应付
      this.$refs.feeInfo.submitData().filter(item => item.feesType == 1).forEach(item => {
        feeAmountD += Number(item.amount)
      })
      this.$refs.feeInfo.submitData().filter(item => item.feesType == 2).forEach(item => {
        feeAmountC += Number(item.amount)
      })
      this.$set(this.form, 'debitAmount', ((Number(orderAmount) - Number(thisUsedProfit) + Number(feeAmountD) - Number(feeAmountC)).toFixed(2)))
      this.$set(this.form, "balanceAmount", (Number(this.form.debitAmount) - 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)
      }
      if (!row.integralMultiples) {
        row.integralMultiples = 0
      }
      row.integral = (Number(row.orderQuantity) * Number(row.integralMultiples)).toFixed(2)

      if (this.goodsActives == 'goods') {
        // 计算销售金额
        this.form.orderAmount = 0
        // 计算赠送积分
        this.form.presenterIntegral = 0;
        this.goodsShowData.forEach(item => {
          this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
          this.form.presenterIntegral = (Number(this.form.presenterIntegral) + Number(item.integral)).toFixed(2)
        })
        this.computedCost()
      } else {
        this.form.convertIntegral = 0;
        this.goodsShowData.forEach(item => {
          this.form.convertIntegral = (Number(this.form.convertIntegral) + Number(item.integral)).toFixed(2)
        })
      }
    },
    priceChange(row) {
      if (!row.price) {
        row.price = 0;
        row.amount = '0.00'
      } else {
        row.amount = (row.price * row.orderQuantity).toFixed(2)
      }
      if (this.goodsActives == 'goods') {
        // 计算销售金额
        this.form.orderAmount = 0
        this.goodsShowData.forEach(item => {
          this.form.orderAmount = (Number(this.form.orderAmount) + Number(item.amount)).toFixed(2)
        })
        this.computedCost()
      }
    },
    //返回列表
    backToList() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        // contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(true)
        }).catch(() => {
          !this.detailData.seeDisabled && this.form.id && this.unLock({moduleName: 'xs',tableName: 'business_order', billId: this.form.id})
          this.$emit("goBack");
          this.leaveDetailsKey(this.$route.name)
        })
      } else {
        !this.detailData.seeDisabled && this.form.id && this.unLock({moduleName: 'xs',tableName: 'business_order', billId: this.form.id})
        this.$emit("goBack");
        this.leaveDetailsKey(this.$route.name)
      }
    },
    // 保存列设置
    async saveColumn(name) {
      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;
          this.$nextTick(() => {
            this.$refs.crudContact.doLayout()
          })
        }
      } 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;
        }
      }
    },
    async resetColumn() {
      this.customerContact = customerContact
      const inSave = await this.delColumnData(
        this.getColumnName(15),
        customerContact
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crudContact.doLayout()
        })
        this.$message.success("重置成功");
        this.judgeNew()
        //关闭窗口
        this.$refs.crudContact.$refs.dialogColumn.columnBox = false;
      }
    },
    returnBack(row) {
      console.log(row)
      this.$refs.KHSelect[0].updateData(row.id)
      getKHList({corpType: 'KH', belongtocompany: row.id}).then(res => {
        //注释自动带出客户全称
        // this.form.corpId = res.data.data.records.length > 0? res.data.data.records[0].id: null
        // if (this.form.corpId) {
        //   this.getCorpRow({adminProfiles: res.data.data.records[0].adminProfiles,
        //     id: res.data.data.records[0].id,
        //     packageRemarks: res.data.data.records[0].packageRemarks,
        //     paymentType: res.data.data.records[0].paymentType})
        // }
      })
      getKHList({corpType: 'GYS', belongtocompany: row.id}).then(res => {
        this.form.productionPlant = res.data.data.records.length > 0? res.data.data.records[0].id: null;
        if (this.form.productionPlant) {
          this.getPlantRow({id: this.form.productionPlant})
        }
      })
      this.form.belongCompany = row.cname
      getlistBankBy(row.id).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)
      }
    },
    // 联系人变化
    corpAttnChange(val) {
      let isTrue = false
      this.khInfoList.forEach(item => {
        if (val == item.id) {
          this.$set(this.form, 'corpTel', item.tel)
          isTrue = true
        }
      })
      if (!isTrue) {
        this.$set(this.form, 'corpTel', null)
      }
    },
    // 合计计算
    summaryMethod({ columns, data }) {
      const sums = [];
      if (columns.length > 0) {
        columns.forEach((item, index) => {
          sums[0] = '合计'
          if (
            item.property == "amount" ||
            item.property == "orderQuantity" ||
            item.property == "actualQuantity" ||
            item.property == "integral" ||
            item.property == "cartonWeight" ||
            item.property == "cntrVolumn"
          ) {
            let amountSum = 0;
            let orderQuantitySum = 0;
            let actualQuantitySum = 0;
            let integralSum = 0;
            let cartonWeight = 0;
            let cntrVolumn = 0;
            if (this.selection.length > 0) {
              this.selection.forEach(e => {
                amountSum = _.add(amountSum, Number(e.amount));
                orderQuantitySum = _.add(orderQuantitySum, Number(e.orderQuantity));
                actualQuantitySum = _.add(actualQuantitySum, Number(e.actualQuantity));
                integralSum = _.add(integralSum, Number(e.integral));
                cartonWeight = _.add(cartonWeight, Number(e.cartonWeight));
                cntrVolumn = _.add(cntrVolumn, Number(e.cntrVolumn));
              })
            }else {{
              this.goodsShowData.forEach(e => {
                amountSum = _.add(amountSum, Number(e.amount));
                orderQuantitySum = _.add(orderQuantitySum, Number(e.orderQuantity));
                actualQuantitySum = _.add(actualQuantitySum, Number(e.actualQuantity));
                integralSum = _.add(integralSum, Number(e.integral));
                cartonWeight = _.add(cartonWeight, Number(e.cartonWeight));
                cntrVolumn = _.add(cntrVolumn, Number(e.cntrVolumn));
              })
            }}
            // 订货数量合计
            if (item.property == "orderQuantity") {
              sums[index] = orderQuantitySum ? orderQuantitySum.toFixed(0) : "0";
            }
            // 发货数量合计
            if (item.property == "actualQuantity") {
              sums[index] = actualQuantitySum ? actualQuantitySum.toFixed(0) : "0";
            }
            // 金额合计
            if (item.property == "amount") {
              sums[index] = amountSum ? amountSum.toFixed(2) : "0.00";
            }
            // 积分合计
            if (item.property == "integral") {
              sums[index] = integralSum ? integralSum.toFixed(2) : "0.00";
            }
            // 重量合计
            if (item.property == "cartonWeight") {
              sums[index] = cartonWeight ? cartonWeight.toFixed(2) : "0.00";
            }
            // 体积合计
            if (item.property == "cntrVolumn") {
              sums[index] = cntrVolumn ? cntrVolumn.toFixed(5) : "0.00000";
            }
          }
        })
      }
      return sums;
    },
    // 标签页切换
    tabHandle(data) {
      if (data.name == 'searchList') {
        this.goodsListShow = this.data;
        this.page.total = this.pageList.total
      } else if (data.name == 'importStaging') {
        this.goodsListShow = this.goodsListSave;
        this.page.total = 0
      }
    },
    // 政策标签页切换
    tabHandleTwo(data) {
      if (data.name == 'searchList') {
        this.dataPolicy = this.dataTwo;
        this.contactsDataBuyFree = this.dataThree;
      } else if (data.name == 'importStaging') {
        this.dataTwo = this.dataPolicy;
        this.dataPolicy = this.goodsListPolicy;
        this.dataThree = this.contactsDataBuyFree;
        this.contactsDataBuyFree = this.buyAndGiveList;
      }
    },
    removeStagList(row, index,type) {
      if (type === 'policy'){
        this.goodsListPolicy.splice(row.$index, 1)
        if (this.goodsListPolicy.length == 0){
          this.customerBuyFree.selection = true
          this.optionPolicy.selection = true
          this.$set(this.customerBuyFree,'menu',true)
        }
      }else if (type === 'policy_buyAndGive'){
        this.buyAndGiveList.splice(row.$index, 1)
        if (this.buyAndGiveList.length == 0){
          this.customerBuyFree.selection = true
          this.optionPolicy.selection = true
          this.$set(this.optionPolicy,'menu',true)
        }
      }else {
        this.goodsListSave.splice(row.$index, 1)
      }
    },
    importStagList(row, index,type) {
      if (type === 'policy'){
        this.goodsListPolicy.push(row);
        if (this.goodsListPolicy.length>0){
          this.customerBuyFree.selection = false
          this.optionPolicy.selection = true
          this.$set(this.customerBuyFree,'menu',false)
        }
      }else if (type === 'policy_buyAndGive'){
        this.buyAndGiveList.push(row);
        if (this.buyAndGiveList.length>0){
          this.customerBuyFree.selection = true
          this.optionPolicy.selection = false
          this.$set(this.optionPolicy,'menu',false)
        }
      }else {
        this.goodsListSave.push(row);
      }
    },
    // 商品信息标签页切换
    handleClick(data) {
      if (this.saveActives == data.name) return
      this.saveActives = data.name
      this.goodsDisabled = true
      if (data.name == 'goods') {
        this.giftData = this.goodsShowData.filter(item => item.goodType == 1)
        // 显示
        this.customerContact.column.forEach(item => {
          if (item.prop == 'integralMultiples') item.label = '积分倍数'
          if (item.prop == 'integral') item.label = '赠送积分'
          if (item.prop == 'orderQuantity') item.label = '订货数量'
          if (item.prop == 'priceType' || item.prop == 'code' || item.prop == 'typeno' || item.prop == 'corpId'
            || item.prop == 'actualQuantity' || item.prop == 'storageQuantity'
            || item.prop == 'purchaseAmount' || item.prop == 'price' || item.prop == 'amount'
            || item.prop == 'shopQuality'
          ) {
            item.hide = false;
            item.showColumn = true;
            if (!this.permission.show_purPrice) {
              if (item.prop == 'purchaseAmount') {
                item.hide = true;
                item.showColumn = false;
              }
            }
          }
        })
        // contactsData它是商品的数组    giftData它是赠品的数组   goodsShowData它是展示页面的数组一共三个
        this.goodsShowData = this.deepClone(this.contactsData);
        setTimeout(() => {
          this.goodsDisabled = false
        },500)
      } else {
        // 隐藏字段
        this.contactsData = this.goodsShowData.filter(item => item.goodType == 0)
        this.customerContact.column.forEach(item => {
          if (item.prop == 'deliveryAmount') item.label = '积分'
          if (item.prop == 'actualQuantity') item.label = '数量'
          if (item.prop == 'integralMultiples') item.label = '积分'
          if (item.prop == 'integral') item.label = '兑换积分'
          if (item.prop == 'orderQuantity') item.label = '数量'
          if (item.prop == 'priceType' || item.prop == 'code' || item.prop == 'typeno' || item.prop == 'corpId'
            || item.prop == 'actualQuantity' || item.prop == 'storageQuantity'
            || item.prop == 'purchaseAmount' || item.prop == 'price' || item.prop == 'amount'
            || item.prop == 'shopQuality'
          ) {
            item.hide = true;
            item.showColumn = false;
          }
        })
        // this.giftData=this.goodsShowData.filter(e=>e.typegood==1)
        this.goodsShowData = this.deepClone(this.giftData);
        setTimeout(() => {
          this.goodsDisabled = false
        },500)
      }
    },
    // 切换之前
    beforeLeave(activeName, oldActiveName) {
    },
    // 查看账单
    // 查看申请记录
    openApplicationDialog(){
      this.applicationDialog = true
    },
    //关闭记录
    choceApplication(){
      this.applicationDialog = false
    },
    //费用明细回调
    beforeFinance(feesData,callback){
      this.advantageProjectData = feesData;
      let params = {}
      //暂时默认通过  之后优化
      params.valid = true
      params.parentId = this.form.id
      params.srcOrderno = this.form.orderNo
      callback(params)
    },
    // 请核
    pleaseCheck() {
      if (!this.form.id){
        return this.editCustomer(false,'','check')
      }
      const giftList = this.goodsActives == 'gift'? this.goodsShowData: this.giftData
      if (this.verification()) {
        this.$confirm(giftList.length == 0?"此单没有赠品，确定提交此次审批吗？": "您确定提交此次申请吗？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const data = {
            id : this.form.id,
            checkType: 'xsqh',
            url: '/businessManagement/salesOrder/index',
            pageStatus:"this.$store.getters.domSaleStatus",
            pageLabel:"销售订单(N)",
            checkFlag: 2,
          }
          this.pageLoading = true
          this.saveLoading = true
          pleaseCheck(data).then(res => {
            this.$message.success('请核成功')
            this.saveActives = ''
            this.queryData(this.form.id)
          }).finally(() => {
            this.pageLoading = false
            this.saveLoading = false
          })
        })
      }
    },
    repealCancel(){
       this.$confirm("您确定撤回此次申请吗？", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          const data = {
            id : this.form.id,
            checkType: 'xsqh',
            pageLabel:"销售订单(N)",
            checkFlag: 2,
          }
          this.pageLoading = true
         this.saveLoading = true
          repealCancel(data).then(res => {
            this.$message.success('撤回成功')
            this.saveActives = ''
            this.queryData(this.form.id)
          }).finally(() => {
            this.pageLoading = false
            this.saveLoading = false
          })
        })
    },
    // 欠款发货审批
    arrearsPleaseCheck() {
      if (this.verification()) {
        const data = {
          id : this.form.id,
          checkType: 'xstpqh',
          url: '/businessManagement/salesOrder/index',
          pageStatus:"this.$store.getters.domSaleStatus",
          pageLabel:"销售订单(N)",
          checkFlag: 3
        }
        this.pageLoading = true
        this.saveLoading = true
        pleaseCheck(data).then(res => {
          this.$message.success('请核成功')
          this.saveActives = ''
          this.queryData(this.form.id)
        }).finally(() => {
          this.pageLoading = false
          this.saveLoading = false
        })
      }
    },
    // 验证新旧值对比
    verification() {
      let getGoodsList = []
      let getGiftList = []
      let getFeeList = this.$refs.feeInfo.submitData()
      // this.goodsShowData.findIndex(item => item.goodType == 0) == -1
      if (this.goodsActives == 'gift') {
        getGiftList = this.goodsShowData
        getGoodsList = this.contactsData
      } else {
        getGoodsList = this.goodsShowData
        getGiftList = this.giftData
      }
      if (contrastObj(this.form, this.oldForm) ||
        contrastList(getGoodsList, this.oldGoodsList) ||
        contrastList(getGiftList, this.oldGiftList) ||
        // contrastList(getFeeList, this.oldFeesList) ||
        contrastList(this.bankOfDepositData, this.oldUploadList)
      ) {
        this.$confirm("数据发生变化未有提交记录, 是否提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.editCustomer(false)
        }).catch(() => {
          return false;   //取消改动数据
        })
      } else {
        return true;  //没有动过数据
      }
    },
    //打开审核
    openCheckDialog(){
      this.checkData  = this.detailData.check
      this.checkDialog = true;
    },
    //关闭审核
    choceCheckFun(){
      this.checkDialog = false;
    },
    choceScheduleFun(){
      this.checkScheduleDialog = false
    },
    shopQualityChange(val, row) {
      // (val == 1) && (row.price = 0)
      if (val == 0) {
        this.shopQualityDisable = true;
        getMarketPrice({code: row.code, isFreight: this.form.isFreight, isLabel: this.form.isLabel}).then(res => {
          if (res.data.data.length > 0) {
            this.$set(row, 'price', res.data.data[0].salePrice)
          } else {
            this.$set(row, 'price', '0')
          }
          this.priceChange(row)
        }).finally(() => {
          this.shopQualityDisable = false;
        })
      } else if(val == 1) {
        row.price = 0
        this.priceChange(row)
      }
    },
    editHandle() {
      const data = {
        moduleName: 'xs',
        tableName: 'business_order',
        billId: this.form.id,
        no: localStorage.getItem('browserID'),
        billNo: this.form.orderNo
      }
      this.saveLoading = true
      this.checkLock(data).then(res => {
        if (res.data.code == 200) {
          this.onLock(data).then(response => {
            this.saveActives = ''
            this.queryData(this.form.id)
          })
          this.inDetailsKey(this.$route.name, {
            moduleName: 'xs',
            tableName: 'business_order',
            billId: this.form.id,
          })
          this.detailData.seeDisabled = false;
        }
      }).catch(error => {
      }).finally(() => {
        this.saveLoading = false
      })
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    changeApproveOpen() {
      this.changeApproveVis = true
      this.$nextTick(() => {
        this.$refs.changeApprove.init()
      })
    },
    closeChangeApprove() {
      this.changeApproveVis = false
    },
    // 商品信息价格计算
    amountChange(row) {
      if (!row.orderQuantity) {
        row.orderQuantity = 0;
      }
      if (!row.price) {
        row.price = 0;
      }
      row.amount = Number(row.price) * Number(row.orderQuantity)
    },
    // 库存刷新
    resetStock() {
      this.goodsShowData.forEach(item => {
        selectGoodsNum({
          goodsId: item.itemId,
          itemType: item.itemType? item.itemType: item.typeno,
          tradeType: 'GN',
          storageId: this.form.storageId
        }).then(res => {
          item.storageQuantity = res.data.data
        })
      })
      this.$message.success('刷新成功')
    },
    // 导入政策下载模板
    downLoadPolicy() {
      this.$confirm('是否下载模板文件？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-purchase-sales/orderitems/policy?${
            this.website.tokenHeader
          }=${getToken()}`
        );
      })
    },
  },
  computed: {
    ...mapGetters(["userInfo", "permission"])
  },
  watch: {
    customerContact(oldVal, newVal) {
      if (!this.permission.show_purPrice) {
        oldVal.column.forEach(item => {
          if (item.prop == 'purchaseAmount') {
            item.hide = true;
            item.showColumn = false;
          }
        })
      }
      if (this.roleName.includes('业务员')) {
        oldVal.column.forEach(item => {
          if (item.prop == 'purchaseAmount') {
            item.hide = true;
            item.showColumn = false;
          }
        })
      }else {
        oldVal.column.forEach(item => {
          if (item.prop == 'purchaseAmount') {
            item.hide = false;
            item.showColumn = true;
          }
        })
      }
    }
  }
}
</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;
}
.isShow {
  display: none;
}
.order_number:hover {
  display: none;
}
.number_button {
  display: none;
}
.order_number:hover + .number_button {
  display: block;
}
</style>
