<template>
  <div class="salesDetail-wrap" :style="{paddingBottom:hideFooter||bizSn?'0px':'45px'}">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle">
          <a id="salesDetail-back-btn" href="javascript:;" v-if="!bizSn" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ detailData&&detailData.salesBillNo }}</span>
          <span v-if="detailData&&detailData.salesBillNoSource">（原：{{ detailData&&detailData.salesBillNoSource || '--' }}）</span>
          <span style="margin: 0 10px;color: #666;">客户名称：{{ detailData&&detailData.buyerName }}</span>
          <a-button size="small" type="link" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
        <template slot="extra">
          <a-button
            key="1"
            type="primary"
            class="button-info"
            id="salesDetail-xs-print-btn"
            v-if="$hasPermissions('B_salesPrint')"
            :disabled="hasData"
            @click="handlePrint('SALES_BILL','B_salesPrint')">销售打印</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-info"
            id="salesDetail-xsfl-print-btn"
            v-if="$hasPermissions('B_salesTypePrint')"
            :disabled="hasData"
            @click="handlePrint('SALES_BILL_TYPE','B_salesTypePrint')">销售分类打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="3"
            type="default"
            class="button-info"
            id="salesDetail-export-btn"
            v-if="$hasPermissions('B_salesDetailExport')"
            :disabled="hasData"
            @click="handlePrint('export','B_salesDetailExport')">导出Excel</a-button>
          <a-button
            key="4"
            type="default"
            class="button-info"
            id="salesDetail-exportType-btn"
            v-if="$hasPermissions('B_salesTypeExport')"
            :disabled="hasData"
            @click="handlePrint('typeExport','B_salesTypeExport')">销售分类导出</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="pages-wrap" style="margin-bottom: 6px;" v-show="showDetail">
        <div style="padding: 0;">
          <a-descriptions size="small" :column="3">
            <a-descriptions-item label="客户名称">{{ detailData&&detailData.buyerName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收货地址" :span="2">{{ shippingAddress||'--' }}</a-descriptions-item>
            <a-descriptions-item label="收货人">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收货电话">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeTel || '--' }}</a-descriptions-item>
            <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleSnDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="审核时间">{{ detailData&&detailData.auditDate || '--' }}</a-descriptions-item>
            <a-descriptions-item label="业务状态" v-if="detailData">{{ detailData.billStatusDictValue || '--' }}{{ (detailData.billStatus=='SUPERIOR_AUDIT_REJECT'||detailData.billStatus=='TRANSFER_AUDIT_REJECT')?'（'+detailData.transferDealerName+'）':'' }}</a-descriptions-item>
            <a-descriptions-item label="财务状态">{{ detailData&&detailData.financialStatusDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="转单时间" v-if="detailData&&detailData.transferDate">{{ detailData.transferDate }}</a-descriptions-item>
            <a-descriptions-item label="改单时间" v-if="detailData&&detailData.salesBillSource=='PURCHASE'&&detailData.submitDate">{{ detailData.submitDate }}</a-descriptions-item>
            <a-descriptions-item label="最新提交时间" v-if="detailData&&detailData.salesBillSource=='SALES'&&detailData.submitDate">{{ detailData.submitDate }}</a-descriptions-item>
            <a-descriptions-item label="发货经销商" v-if="detailData&&detailData.billStatus&&(detailData.billStatus=='TRANSFER_YES'||detailData.billStatus=='TRANSFER_FINISH')">{{ detailData.transferDealerName || '--' }}</a-descriptions-item>
            <a-descriptions-item label="备注" :span="3">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
          </a-descriptions>
        </div>
      </a-card>
      <a-card
        size="small"
        :bordered="false"
        class="pages-wrap"
        style="margin-bottom: 6px;"
        :bodyStyle="{padding:'10px 10px 0'}">
        <!-- 统计信息 -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message">
            <div class="form-grid">
              <div class="tongji-bar-col">
                <div v-if="$hasPermissions(authCode + '_costPrice')">总成本：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_costPrice')">总毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>总数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')">总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>已取消数量：<strong>{{ detailData&&(detailData.totalCancelQty || detailData.totalCancelQty==0) ? detailData.totalCancelQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')">已取消金额：<strong>{{ detailData&&(detailData.totalCancelAmount || detailData.totalCancelAmount==0) ? toThousands(detailData.totalCancelAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>已下推数量：<strong>{{ detailData&&(detailData.totalPushedQty || detailData.totalPushedQty==0) ? detailData.totalPushedQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')">已下推金额：<strong>{{ detailData&&(detailData.totalPushedAmount || detailData.totalPushedAmount==0) ? toThousands(detailData.totalPushedAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>待下推数量：<strong>{{ detailData&&(detailData.totalUnpushedQty || detailData.totalUnpushedQty==0) ? detailData.totalUnpushedQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')"> 待下推金额：<strong>{{ detailData&&(detailData.totalUnpushedAmount || detailData.totalUnpushedAmount==0) ? toThousands(detailData.totalUnpushedAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>已发货数量：<strong>{{ detailData&&(detailData.totalDispatchQty || detailData.totalDispatchQty==0) ? detailData.totalDispatchQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')">已发货金额：<strong>{{ detailData&&(detailData.totalDispatchAmount || detailData.totalDispatchAmount==0) ? toThousands(detailData.totalDispatchAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div>待发货数量：<strong>{{ detailData&&(detailData.totalUndispatchQty || detailData.totalUndispatchQty==0) ? detailData.totalUndispatchQty : '--' }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')">待发货金额：<strong>{{ detailData&&(detailData.totalUndispatchAmount || detailData.totalUndispatchAmount==0) ? toThousands(detailData.totalUndispatchAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div v-if="$hasPermissions(authCode + '_costPrice')&&isAveragePrice"><label style="width:108px;">平均成本公斤单价：<strong>{{ detailData&&(detailData.totalWeightAvgCost || detailData.totalWeightAvgCost==0) ? toThousands(detailData.totalWeightAvgCost) : '--' }}</strong>；</label></div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')&&isAveragePrice"><label style="width:108px;">平均售价公斤单价：<strong>{{ detailData&&(detailData.totalWeightAvgPrice || detailData.totalWeightAvgPrice==0) ? toThousands(detailData.totalWeightAvgPrice) : '--' }}</strong>；</label></div>
              </div>
              <div class="tongji-bar-col">
                <div v-if="isAveragePrice">合计重量(kg)：<strong>{{ detailData&&(detailData.totalWeightKg || detailData.totalWeightKg==0) ? detailData.totalWeightKg : '--' }}</strong>；</div>
                <div v-if="isCityPrice">&nbsp;&nbsp;市级总售价：<strong>{{ detailData&&(detailData.totalCityAmount || detailData.totalCityAmount==0) ? toThousands(detailData.totalCityAmount) : '--' }}</strong>；</div>
              </div>
              <div class="tongji-bar-col">
                <div v-if="$hasPermissions(authCode + '_salesPrice')&&detailData&&detailData.totalDiscountAmount" style="color: red;">优惠金额：<strong>{{ Number(detailData.totalDiscountAmount).toFixed(2) }}</strong>；</div>
                <div v-if="$hasPermissions(authCode + '_salesPrice')&&detailData&&detailData.totalConvertPromoGiftsAmount" style="color: red;width:200px;">促销产品转采购额金额：<strong>{{ Number(detailData.totalConvertPromoGiftsAmount).toFixed(2) }}</strong>；</div>
              </div>
            </div>
          </div>
        </a-alert>
        <!-- 查询 -->
        <div class="table-page-search-wrapper">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <div style="flex-grow: 1;width: 60%;">
              <a-form layout="inline" @keyup.enter.native="searchTable">
                <a-row :gutter="15" type="flex">
                  <a-col flex="300px">
                    <a-form-item label="出库仓库">
                      <chooseWarehouse id="salesDetail-warehouse" ref="warehouse" v-model="warehouseSn"></chooseWarehouse>
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px" v-if="hasPrompActive">
                    <a-form-item label="产品类型">
                      <a-select
                        v-model="promoProductClz"
                        @change="e=> {borrowFlag = undefined}"
                        id="salesDetail-promoProductClz"
                        allowClear
                        :dropdownMatchSelectWidth="false"
                        placeholder="请选择产品类型">
                        <a-select-option value="0">
                          正常产品
                        </a-select-option>
                        <a-select-option value="REGULAR">
                          正价产品（活动）
                        </a-select-option>
                        <a-select-option value="DISCOUNT">
                          特价产品
                        </a-select-option>
                        <a-select-option value="GIFT">
                          促销产品
                        </a-select-option>
                        <a-select-option value="convertPromoGiftsFlag" v-if="showConvertPromoGifts">
                          促销产品（转采购额）
                        </a-select-option>
                        <a-select-option value="GATE">
                          门槛产品
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="200px" v-if="hasPrompActive&&promoProductClz!=='0'">
                    <a-form-item label="累计产品">
                      <v-select code="FLAG" v-model="borrowFlag" allowClear placeholder="请选择是否累计产品"></v-select>
                    </a-form-item>
                  </a-col>
                  <a-col flex="300px" v-if="showTransferDealer">
                    <a-form-item label="发货经销商库存">
                      <v-select
                        code="STOCK_LABEL"
                        id="purchaseOrder-basicInfo-transferQty"
                        v-model="transferQty"
                        allowClear
                        placeholder="请选择是否满足"
                      ></v-select>
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24">
                    <a-button type="primary" @click="searchTable" :disabled="disabled" id="salesDetail-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" id="salesDetail-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <div>
              <span v-if="selectedDealer">发货经销商：{{ selectedDealer }}</span>
              <a-button
                id="salesDetail-updateStock"
                type="link"
                v-if="showTransferDealer"
                @click="openDealerModal"
                class="button-dealerStock">选择发货经销商</a-button>
              <a-button id="salesDetail-stockOut" v-if="showStock" type="link" @click="openStockOut">缺货明细</a-button>
              <!-- <a-checkbox id="salesDetail-updateStock" @change="e=>getThreeStock(e)" v-if="showStock"><span style="display: inline-block;margin-top: 1px;">第三方库存</span></a-checkbox> -->
              <a-checkbox id="salesDetail-cityPrice" v-model="isCityPrice" v-if="$hasPermissions(authCode + '_cityPrice')"><span style="display: inline-block;margin-top: 1px;">市级价</span></a-checkbox>
              <a-checkbox id="salesDetail-cityPrice" v-model="isAveragePrice" v-if="$hasPermissions(authCode + '_avgprice')"><span style="display: inline-block;margin-top: 1px;">平均公斤单价</span></a-checkbox>
            </div>
          </div>
        </div>
      </a-card>
      <!-- 正常产品列表 -->
      <a-card
        size="small"
        :bordered="false"
        class="salesEdit-cont"
        style="margin-bottom: 6px;"
        v-show="!hideNormalTable"
      >
        <div>
          <detailProductList
            ref="productList"
            :maxHeight="pageHeight"
            :detailData="detailData"
            :warehouseSn="warehouseSn"
            :activeList="activeList"
            :promoProductClz="promoProductClz"
            :pageType="$route.params.pageType"
            :salesBillSn="$route.params.sn || bizSn"
            :authCode="authCode"
            :chooseList="chooseDealerList"
            :transferQty="transferQty"
            :borrowFlag="borrowFlag"
            :showTransferDealer="showTransferDealer"
            :showCityPrice="isCityPrice"
            :showAveragePrice="isAveragePrice"
            @hideTable="hideTable">
          </detailProductList>
        </div>
        <div v-if="hideNormalTable&&hideActiveTable" :style="{height:pageHeight+10+'px'}" class="empty-data-box">
          <a-empty description="暂无产品" :image="simpleImage"/>
        </div>
      </a-card>
      <!-- 活动产品列表 -->
      <a-card
        size="small"
        :bordered="false"
        class="salesEdit-cont"
        v-if="!hideActiveTable"
      >
        <div slot="title">
          <div style="display: flex;justify-content: space-between;align-items: center;">
            <strong>活动产品</strong>
            <div>
              <a-popover placement="bottom">
                <template slot="content">
                  <a-checkbox-group v-model="colsValue">
                    <a-row style="width:100px;padding:0;">
                      <a-col :span="24" style="margin:3px 0;" v-for="(item) in colsOptions" :key="item.value">
                        <a-checkbox :value="item.value">{{ item.label }}</a-checkbox>
                      </a-col>
                    </a-row>
                  </a-checkbox-group>
                </template>
                <a-button size="small" type="link" class="button-info"><a-icon type="eye"/> 显示列</a-button>
              </a-popover>
            </div>
          </div>
        </div>
        <activeStatisticsList
          ref="activeTjList"
          type="view"
          @selected="active => salesPromoSnSet = active"
          :activeList="activeList"
          :warehouseSn="warehouseSn"
          :salesBillSn="$route.params.sn || bizSn"
          :showCols="colsValue"
        ></activeStatisticsList>
        <detailProductList
          ref="productActiveList"
          type="active"
          :maxHeight="pageHeight"
          :detailData="detailData"
          :activeList="activeList"
          :warehouseSn="warehouseSn"
          :promoProductClz="promoProductClz"
          :borrowFlag="borrowFlag"
          :pageType="$route.params.pageType"
          :salesBillSn="$route.params.sn || bizSn"
          :salesPromoSnSet="salesPromoSnSet"
          :authCode="authCode"
          :showCityPrice="isCityPrice"
          :showAveragePrice="isAveragePrice"
          @hideTable="hideTable"
          @onlyBorrow="v=>onlyBorrowFlag=v">
        </detailProductList>
      </a-card>
    </a-spin>
    <div class="affix-cont" :class="bizSn?'affix-footer-bar':''" :style="{padding:hideFooter?0:'10px 0'}">
      <a-button
        style="width: 100px;margin: 0 10px;"
        :disabled="spinning"
        type="primary"
        class="button-info"
        id="salesDetail-transfer-btn"
        v-if="$hasPermissions('B_salesTransfer')&&$route.params.pageType=='salesNewDetailTransfer'&&(detailData&&detailData.promoFlag!=1&&(detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'SUPERIOR_AUDIT_REJECT' || detailData.billStatus == 'TRANSFER_AUDIT_REJECT')&&detailData.salesBillSource=='PURCHASE'&&detailData.orderType=='TIRE')"
        @click="handleOrder()"
      >
        转单
      </a-button>
      <a-button
        type="default"
        class="button-info"
        :disabled="spinning"
        style="width: 100px;margin: 0 10px;"
        id="salesDetail-edit-btn"
        v-if="detailData&&detailData.salesBillSource == 'SALES' && (detailData.billStatus == 'WAIT_SUBMIT' || detailData.billStatus == 'WAIT_AUDIT' || detailData.billStatus == 'AUDIT_REJECT' || detailData.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesEdit')"
        @click="handleEdit()"
      >
        编辑
      </a-button>
      <a-button
        style="width: 100px;margin: 0 10px;"
        :disabled="spinning"
        type="default"
        id="salesDetail-edit1-btn"
        v-if="detailData&&detailData.salesBillSource == 'PURCHASE' && (detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'HQ_CHANGE'||detailData.billStatus == 'SUPERIOR_AUDIT_REJECT' || detailData.billStatus == 'TRANSFER_AUDIT_REJECT')&&$hasPermissions('B_salesEdit')"
        @click="handleChangeOrder()"
      >
        改单
      </a-button>
      <a-button
        style="width: 100px;margin: 0 10px;"
        :disabled="spinning"
        type="primary"
        class="button-info"
        id="salesDetail-UPaudit-btn"
        v-if="detailData&&(detailData.billStatus == 'WAIT_AUDIT'||isSupAudit||detailData.billStatus == 'SUPERIOR_AUDIT_REJECT' || detailData.billStatus == 'TRANSFER_AUDIT_REJECT')&&$hasPermissions('B_salesAudit')"
        @click="handleAudit()"
      >
        {{ isSupAudit?'上级':'' }}审核
      </a-button>
      <!-- 转单审核 -->
      <a-button
        style="width: 100px;margin: 0 10px;"
        :disabled="spinning"
        type="primary"
        class="button-info"
        id="salesDetail-audit-btn"
        v-if="$hasPermissions('B_higherLevelAudit')&&detailData&&detailData.billStatus == 'SUPERIOR_WAIT_AUDIT'&&detailData.orderType=='TIRE'"
        @click="handleTransferAudit"
      >
        审核
      </a-button>
      <a-button
        style="width: 100px;margin: 0 10px;"
        :disabled="spinning"
        type="primary"
        class="button-success"
        id="salesDetail-batchAudit-btn"
        v-if="detailData&&(detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'SUPERIOR_AUDIT_REJECT' || detailData.billStatus == 'TRANSFER_AUDIT_REJECT')&&$hasPermissions('B_salesAudit')&&$route.params.pageType!='salesNewDetailTransfer'"
        @click="handleAudit('batch')"
      >
        一键审核
      </a-button>
      <a-button
        id="salesDetail-dispatch"
        style="width: 100px;margin: 0 10px;"
        type="primary"
        class="button-warning"
        v-if="detailData&&detailData.billStatus == 'WAIT_PUSH'&&$hasPermissions('B_salesDispatch')"
        @click="handleDispatch(detailData)"
      >下推</a-button>
    </div>
    <!-- 打印导出 -->
    <print-modal :openModal="openModal" :itemData="detailData" :nowType="nowType" @ok="handleOk" @close="closePrint" />
    <!-- 审核 -->
    <auditModal
      :openModal="visibleAudit"
      :content="auditText"
      :spinning="spinningAudit"
      @close="visibleAudit=false"
      @ok="auditOrder('AUDIT_PASS')"
      @fail="auditOrder('AUDIT_REJECT')" />
    <!-- 审核加下推 -->
    <dsModal ref="dsModal" title="销售单一键审核" :openModal="showDsModal" @close="showDsModal=false" @ok="handleOnceAudit" />
    <!-- 缺货明细 -->
    <stockOutDetail :openModal="showStockOut" :detailData="detailData" :salesBillSn="$route.params.sn || bizSn" @close="showStockOut=false"></stockOutDetail>
    <!-- 改单时价格变更提示 -->
    <tipModal ref="tipModal" :openModal="openTipModal" :dataList="sourceData" @close="closeTipModal" @ok="openTipModalOk"></tipModal>
    <!-- 审核时校验销售价低于成本价提示 -->
    <vaildPriceModal
      ref="vaildPriceModal"
      :openModal="openVaildPriceModal"
      :dataObj="tempData"
      @close="closeVaildPrice"
      @ok="vaildPriceOk"></vaildPriceModal>
    <!-- 发货经销商库存 弹窗 -->
    <dealerStockModal :itemSn="$route.params.sn" :showStock="showStock" :openModal="openDealerStock" @close="openDealerStock = false" @ok="openDealerStockOk"></dealerStockModal>
    <!-- 审核弹窗 -->
    <auditConfirmModal :openModal="openTransferOrder" :detailData="detailData" @ok="transferOrderAuditOk" @close="openTransferOrder=false"></auditConfirmModal>
  </div>
</template>

<script>
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { Empty } from 'ant-design-vue'
import { VSelect } from '@/components'
import printModal from './printModal.vue'
import auditModal from '@/views/common/auditModal.vue'
import dsModal from '@/views/salesManagement/waitDispatchNew/dsModal.vue'
import stockOutDetail from './stockOutDetailModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import detailProductList from './comps/detailProductList.vue'
import activeStatisticsList from './comps/activeStatisticsList.vue'
import tipModal from './tipModal.vue'
import vaildPriceModal from './vaildPriceModal.vue'
import dealerStockModal from './comps/dealerStockModal.vue'
import auditConfirmModal from './auditModal.vue'
// 接口
import {
  salesPromoQueryList,
  getSalesDetail,
  salesDetailPrint,
  salesDetailExcel,
  salesDetailTypeExcel,
  salesWriteAuditPass,
  salesWriteUpAuditPass,
  salesWriteAuditReject,
  salesWriteUpAuditReject,
  salesWriteAuditPush,
  getThirdStockQty,
  salesPromoValidaAudit,
  changeBillCheckUpdatePrice,
  changeBillCheck } from '@/api/salesNew'
import { transferVerify, transfer, transferAudit } from '@/api/sales'

export default {
  name: 'SalesDetailNew',
  mixins: [commonMixin],
  components: { VSelect, printModal, auditModal, dsModal, stockOutDetail, chooseWarehouse, detailProductList, activeStatisticsList, tipModal, vaildPriceModal, dealerStockModal, auditConfirmModal },
  props: {
    bizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE, // 空图片
      hideNormalTable: false, // 是否隐藏表格
      hideActiveTable: true, // 是否隐藏活动表格
      showDsModal: false, // 一键审核弹框
      showStockOut: false, // 缺货明细弹框
      activeList: [], // 参与活动列表
      authCode: '', // 权限码
      hasData: false, // 是否有数据
      showDetail: false, // 基础信息是否显示
      openModal: false, // 打印导出弹框
      detailData: null, //  详情数据
      nowType: null, // 打印导出类型
      isCityPrice: false, //  是否显示市级价
      isAveragePrice: false, // 是否显示
      visibleAudit: false, // 审核弹框
      spinningAudit: false, // 审核loading
      auditText: null, // 审核备注信息
      fromRouter: null, // 从那个页面打开当前页面
      warehouseSn: undefined, // 所在仓库
      promoProductClz: undefined, // 产品类型
      openTipModal: false, // 改单弹窗
      sourceData: undefined, // 价格变动数据
      tempData: undefined, // 校验临时数据
      openVaildPriceModal: false, // 校验价格弹框
      transferQty: undefined, // 发货经销商库存查询
      borrowFlag: undefined, // 是否累计产品
      openDealerStock: false, // 打开经销商库存弹窗
      openTransferOrder: false, // 打开转单弹窗
      selectedDealer: '', // 发货经销商名称
      selectedDealerSn: undefined, // 发货经销商sn
      salesPromoSnSet: [], // 当前勾选的活动sn
      chooseDealerList: [], // 发货经销商数据
      colsOptions: [],
      colsValue: [],
      onlyBorrowFlag: false
    }
  },
  computed: {
    // 详细地址
    shippingAddress () {
      const shippingAddrProvinceName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrProvinceName ? this.detailData.salesBillExtEntity.shippingAddrProvinceName : ''
      const shippingAddrCityName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrCityName ? this.detailData.salesBillExtEntity.shippingAddrCityName : ''
      const shippingAddrCountyName = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddrCountyName ? this.detailData.salesBillExtEntity.shippingAddrCountyName : ''
      const shippingAddr = this.detailData && this.detailData.salesBillExtEntity && this.detailData.salesBillExtEntity.shippingAddr ? this.detailData.salesBillExtEntity.shippingAddr : ''
      if (!shippingAddrProvinceName && !shippingAddrCityName && !shippingAddrCountyName && !shippingAddr) {
        return '--'
      } else {
        return shippingAddrProvinceName + shippingAddrCityName + shippingAddrCountyName + shippingAddr
      }
    },
    // 是否因此底部栏按钮
    hideFooter () {
      const detailData = this.detailData
      return detailData && ((detailData.salesBillSource != 'SALES' && detailData.billStatus == 'AUDIT_REJECT') || detailData.billStatus == 'FINISH' || detailData.billStatus == 'OUTING_WAREHOUSE' || detailData.billStatus == 'TRANSFER_FINISH' || detailData.billStatus == 'TRANSFER_YES')
    },
    // 是否有促销活动产品
    hasPrompActive () {
      return this.detailData && this.detailData.promoFlag == 1
    },
    // 是否有可转采购额
    hasConvertPromoGifts () {
      return this.detailData && this.detailData.totalConvertPromoGiftsQty
    },
    // 是否有促销产品（转采购额）
    showConvertPromoGifts () {
      return this.activeList && this.activeList.filter(item => item.enabledFlag == 1).find(item => item.promotionRule && item.promotionRule.convertExpenseFlag == 1 && item.promotionRule.promotionRuleType == 'BUY_PROD_GIVE_PROD')
    },
    // 是否显示三方库存列
    showStock () {
      return this.detailData && (this.detailData.billStatus == 'WAIT_AUDIT' || this.detailData.billStatus == 'HQ_CHANGE' || this.detailData.billStatus == 'SUPERIOR_AUDIT_REJECT') && this.$hasPermissions('B_salesAudit')
    },
    // 是否显示发货经销商按钮  发货经销商库存
    showTransferDealer () {
      return this.$hasPermissions('B_salesTransfer') && this.$route.params.pageType != 'salesNewDetailAudit' && (this.detailData && this.detailData.promoFlag != 1 && (this.detailData.billStatus == 'WAIT_AUDIT' || this.detailData.billStatus == 'SUPERIOR_AUDIT_REJECT' || this.detailData.billStatus == 'TRANSFER_AUDIT_REJECT') && this.detailData.salesBillSource == 'PURCHASE' && this.detailData.orderType == 'TIRE')
    },
    // 表格高度计算
    pageHeight () {
      if (!this.bizSn && (this.hideNormalTable || this.hideActiveTable || this.activeList.length == 0)) {
        return window.innerHeight - 330 + (this.hideFooter ? 45 : 0)
      }
      return 'auto'
    },
    // 是否上级审核
    isSupAudit () {
      return this.detailData && this.detailData.billStatus == 'SUPERIOR_WAIT_AUDIT' && this.detailData.orderType !== 'TIRE'
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$emit('close')
      this.$router.push({ name: 'salesQueryNewList' })
    },
    // 打开 发货经销商库存弹窗
    openDealerModal () {
      this.openDealerStock = true
    },
    getColsOptions () {
      this.colsOptions = [
        { label: '序号', value: '0' },
        { label: '活动类型', value: '1' },
        { label: '规则简称', value: '2' },
        { label: '门槛产品', value: '3' },
        { label: '特价', value: '4' },
        { label: '正价产品', value: '5' },
        { label: '促销品', value: '6' },
        { label: '采购额', value: '7' },
        { label: '款数', value: '8' },
        { label: '数量', value: '9' },
        { label: '总金额', value: '10' },
        { label: '优惠金额', value: '11' }
      ]
      // this.colsValue = this.colsOptions.filter(item => item.value < 8 && item.value != 3 || item.value == 11).map(item => item.value)
      this.colsValue = this.colsOptions.map(item => item.value)
    },
    // 确定选择经销商库存转单
    openDealerStockOk (val, data) {
      this.selectedDealer = val.dealerName
      this.selectedDealerSn = val.dealerSn
      this.chooseDealerList = data
      this.openDealerStock = false
      this.$nextTick(() => {
        this.searchTable()
      })
    },
    // 是否隐藏表格
    hideTable (type, len) {
      this.spinning = false
      if (type == 'normal') {
        this.hideNormalTable = !(this.promoProductClz == 0 || this.promoProductClz == undefined) || this.borrowFlag != undefined || (len == 0 && this.activeList.length)
      } else {
        if (this.promoProductClz == 0) {
          this.hideActiveTable = true
        }
      }
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      this.$emit('close')
      this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
    },
    // 改单
    handleChangeOrder () {
      const _this = this
      const row = _this.detailData
      changeBillCheck({ salesBillSn: row.salesBillSn }).then(res => {
        let data
        if (res.status == 200) {
          data = res.data
          if (data && data.length > 0) {
            _this.sourceData = res.data
            const obj = {
              buyerName: row.buyerName,
              salesBillNo: row.salesBillNo
            }
            _this.$refs.tipModal.getShowInfo(obj)
            _this.openTipModal = true
          } else {
            _this.$emit('close')
            _this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
          }
        }
      })
    },
    // 改单成功  关闭弹窗
    openTipModalOk (ajaxData) {
      const row = this.detailData
      ajaxData.salesBillSn = row.salesBillSn
      ajaxData.detailList = this.sourceData
      changeBillCheckUpdatePrice(ajaxData).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.openTipModal = false
          this.$nextTick(() => {
            this.$emit('close')
            this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
          })
        }
      })
    },
    // 取消时，跳转编辑页面
    closeTipModal () {
      this.openTipModal = false
      this.$emit('close')
      this.$router.push({ name: 'salesNewEdit', params: { sn: this.$route.params.sn || this.bizSn } })
    },
    // 查询第三方库存
    getThreeStock (e) {
      this.hideActiveTable = this.activeList.length == 0
      this.$refs.productList.showThreeStock(e.target.checked)
      if (!this.hideActiveTable) this.$refs.productActiveList.showThreeStock(e.target.checked)
    },
    //  重置
    resetSearchForm () {
      this.warehouseSn = undefined
      this.promoProductClz = undefined
      this.transferQty = undefined
      this.borrowFlag = undefined
      this.searchTable()
    },
    // 查询数据
    searchTable () {
      this.hideNormalTable = false
      this.hideActiveTable = this.activeList.length == 0
      this.spinning = true
      this.$nextTick(() => {
        this.$refs.productList.searchTable()
        if (!this.hideActiveTable) this.$refs.productActiveList.searchTable()
      })
    },
    // 详情
    getDetail () {
      this.spinning = true
      getSalesDetail({ salesBillSn: this.bizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data || null
          this.detailData.totalDiscountAmount = Number(this.detailData.totalOrigAmount || 0) - Number(this.detailData.totalAmount || 0)
        }
        this.getActiveList()
        this.getColsOptions()
      })
    },
    // 获取销售单参与的活动列表
    async getActiveList () {
      // 已参与活动列表
      const list = await salesPromoQueryList({ salesBillSn: this.$route.params.sn || this.bizSn }).then(res => res.data || [])
      this.activeList = list.filter(item => {
        return item.promotion && item.promotionRule && item.enabledFlag == 1
      })
      this.hideActiveTable = this.activeList.length == 0
      // 触发活动统计查询变量
      this.$nextTick(() => {
        if (!this.hideActiveTable) {
          this.$refs.activeTjList.hasInit = false
        }
      })
      this.spinning = false
      setTimeout(() => {
        this.resetSearchForm()
      }, 300)
    },
    // 打开缺货明细弹框
    openStockOut () {
      if (this.$refs.productList && this.$refs.productList.outStockStr != '' || this.activeList.length && this.$refs.productActiveList.outStockStr != '') {
        this.showStockOut = true
      } else {
        this.$info({
          title: '提示',
          content: '此销售单暂无缺货产品！',
          centered: true
        })
      }
    },
    // 下推
    handleDispatch (row) {
      this.$emit('close')
      this.$router.push({ name: 'waitDispatchNew', params: { salesBillSn: row.salesBillSn } })
    },
    // 转单
    handleOrder () {
      const _this = this
      if (!_this.selectedDealerSn) {
        _this.$message.warning('请选择发货经销商!')
        return
      }
      _this.spinning = true
      // 验证
      transferVerify({ salesBillSn: _this.$route.params.sn, transferDealerSn: _this.selectedDealerSn }).then(res => {
        if (res.status == 200) {
          if (res.data && Object.keys(res.data).length) {
            _this.$confirm({
              title: '提示',
              content: <div><strong style="color:#ed1c24;">{res.data.dealerName}</strong>非<strong style="color:#ed1c24;">{res.data.buyerName}</strong>的轮胎上级或省仓，提交后待上级审核通过完成转单</div>,
              centered: true,
              closable: true,
              okText: '提交',
              onOk () {
                _this.spinning = false
                // 验证成功
                _this.handleTransfer()
              },
              onCancel () {
                _this.spinning = false
              }
            })
          } else {
            this.handleTransfer()
          }
        }
      })
    },
    // 提交转单
    handleTransfer () {
      this.spinning = true
      transfer({ salesBillSn: this.$route.params.sn, transferDealerSn: this.selectedDealerSn }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          //  转单成功 关闭详情跳列表
          this.handleBack()
        }
        this.spinning = false
      })
    },
    // 打开 转单审核弹窗
    handleTransferAudit () {
      this.openTransferOrder = true
    },
    // 确认转单审核
    transferOrderAuditOk (val) {
      transferAudit({ salesBillSn: this.$route.params.sn, auditPassFlag: val }).then(res => {
        if (res.status == 200) {
          this.openTransferOrder = false
          this.$message.success(res.message)
          //  转单成功 关闭详情跳列表
          this.handleBack()
        }
      })
    },
    // 打开审核/一键审核弹框
    async handleAudit (isBatch) {
      const _this = this
      this.spinning = true
      // 校验产品是否付个促销活动规则
      const vaildActive = await salesPromoValidaAudit({ salesBillSn: this.bizSn || this.$route.params.sn }).then(res => res.data)
      if (vaildActive && vaildActive.length > 0) {
        const a = vaildActive.filter(item => item.type == 1) // 不可提交
        const c = vaildActive.filter(item => item.type == 'price_less_0') // 不可提交
        const b = vaildActive.filter(item => item.type == 0) // 文字提示，可跳过继续提交
        const d = vaildActive.filter(item => item.type == 'price_less_cost' || item.type == 'wait_up_audit_price_less_cost') // 价格校验表格提示,可跳过继续提交
        const e = vaildActive.filter(item => item.type == 'allBorrowProductFlag') // 只有累计产品
        // 上级审核不校验规则
        if (this.isSupAudit) {
          // 售价是否低于参考成本价
          _this.validPriceLessCost(d, isBatch)
          return
        }
        // 弹出不符合规则弹框，不可提交
        if (a.length) {
          this.$info({
            title: '提示',
            centered: true,
            class: 'confirm-center',
            okText: '关闭',
            width: 600,
            content: <div style="padding-top:15px;">
              <ol>
                {a.map(item => (
                  <li style="padding:3px 0;">{item.message}</li>
                ))}
              </ol>
              <div style="padding:10px 0;text-align:center"><strong>请按照以上提示修改后再提交</strong></div>
            </div>
          })
          _this.spinning = false
          return
        }
        // 不可提交
        if (c.length) {
          // 弹框显示表格提示
          if (!isBatch) {
            _this.openVaildPrice(c[0])
          } else {
            // 弹框文字提示
            _this.tempData = { vaildPriceList: c[0].data.map(item => item.productCode) }
            _this.verificationSuccess(isBatch)
          }
          return
        }
        // 文字提示，可跳过继续提交
        if (b.length) {
          // 弹出确认提示信息，可跳过继续提交
          _this.$confirm({
            title: '提示',
            centered: true,
            class: 'confirm-center',
            okText: '确定',
            width: 600,
            content: <div style="padding-top:15px;">
              <ol>
                {b.map(item => (
                  <li style="padding:3px 0;">{item.message}</li>
                ))}
              </ol>
            </div>,
            onOk () {
              // 只有累计产品
              if (e.length) {
                _this.onlyBorrowProduct(e)
                return
              }
              // 售价是否低于参考成本价
              _this.validPriceLessCost(d, isBatch)
            },
            onCancel () {
              _this.spinning = false
            }
          })
          return
        }
        // 只有累计产品
        if (e.length) {
          _this.onlyBorrowProduct(e)
          return
        }
        // 售价是否低于参考成本价
        _this.validPriceLessCost(d, isBatch)
      } else {
        _this.verificationSuccess(isBatch)
      }
    },
    // 只有累计产品弹框
    onlyBorrowProduct (e) {
      const _this = this
      _this.auditText = e[0].message
      _this.visibleAudit = true
      _this.spinning = false
    },
    // 售价是否低于参考成本价提示弹框
    validPriceLessCost (d, isBatch) {
      const _this = this
      if (d.length) {
        if (isBatch) { // 一键审核,弹框文字提示
          _this.tempData = { vaildPriceList: d[0].data.map(item => item.productCode) }
          _this.verificationSuccess(isBatch)
        } else {
          // 审核或上级审核，弹框表格提示
          _this.openVaildPrice(d[0])
        }
      } else {
        _this.verificationSuccess(isBatch)
      }
    },
    // 校验销售价低于成本价提示
    openVaildPrice (data) {
      this.tempData = data
      this.openVaildPriceModal = true
    },
    // 关闭校验销售价低于成本价提示
    closeVaildPrice () {
      this.spinning = false
      this.tempData = null
      this.openVaildPriceModal = false
    },
    // 消息提示
    messageInfo (content) {
      this.$info({
        title: '提示',
        content: content,
        centered: true,
        onOk: () => {
          this.spinning = false
        }
      })
    },
    // 验证通过
    verificationSuccess (isBatch) {
      if (isBatch) { // 一键审核
        if (this.$refs.productActiveList && this.$refs.productActiveList.hasOutStockOfActive) {
          this.messageInfo('参加促销活动的产品存在缺货，不可一键审核!')
          return
        }
        if (this.showConvertPromoGifts) {
          this.messageInfo('该活动规则中，促销产品可转费用报销单，不可一键审核!')
          return
        }
        if (this.$refs.productList && this.$refs.productList.hasJGtire || this.$refs.productActiveList && this.$refs.productActiveList.hasJGtire) {
          this.messageInfo('销售单内有品牌是【箭冠】，且三级分类是【轮胎】的产品，不可一键审核！')
          return
        }
        if (this.tempData && this.tempData.vaildPriceList) {
          this.messageInfo('产品' + this.tempData.vaildPriceList + '售价已低于成本价，不可一键审核!')
          return
        }
        // 一键审核成功
        this.showDsModal = true
        this.$refs.dsModal.setDetail(this.detailData)
        this.spinning = false
      } else {
        this.auditText = null
        this.visibleAudit = true
        this.spinning = false
      }
    },
    // 一键审核确定
    handleOnceAudit (data) {
      const params = {
        salesBillSn: this.bizSn || this.$route.params.sn,
        billStatus: 'AUDIT_PASS',
        dispatchBill: data
      }
      this.spinningAudit = true
      this.spinning = true
      salesWriteAuditPush(params).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          //  关闭详情跳列表
          this.handleBack()
        }
        this.spinningAudit = false
        this.spinning = false
      })
    },
    // 价格低于成本校验提示，继续审核
    vaildPriceOk (type) {
      // 审核通过或不通过
      if (type == 'AUDIT_PASS' || type == 'AUDIT_REJECT') {
        this.auditOrder(type)
      }
      // 上级审核,不通过或通过
      if (type == 'AUDIT_UP_PASS' || type == 'AUDIT_UP_REJECT') {
        const upFun = type == 'AUDIT_UP_PASS' ? salesWriteUpAuditPass : salesWriteUpAuditReject
        this.spinning = true
        upFun({
          salesBillSn: this.bizSn || this.$route.params.sn,
          billStatus: type == 'AUDIT_UP_PASS' ? 'AUDIT_PASS' : undefined
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.closeVaildPrice()
            this.handleBack()
          }
          this.$refs.vaildPriceModal.spinning = false
          this.spinning = false
        })
      }
    },
    // 审核
    auditOrder (billStatus) {
      this.spinningAudit = true
      const auditFun = billStatus == 'AUDIT_PASS' ? salesWriteAuditPass : salesWriteAuditReject
      auditFun({
        salesBillSn: this.bizSn || this.$route.params.sn,
        billStatus: billStatus,
        leaderAuditFlag: this.isSupAudit ? 1 : 0
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.spinningAudit = false
          const _this = this
          this.closeVaildPrice()
          this.$nextTick(() => {
            // 审核通过，跳转到带下推页面
            if (billStatus == 'AUDIT_PASS' && !_this.auditText) {
              _this.$emit('close')
              _this.$router.push({ name: 'waitDispatchNew', params: { salesBillSn: _this.bizSn || _this.$route.params.sn } })
            } else {
              // 不通过关闭详情返回列表
              _this.handleBack()
            }
          })
        } else {
          this.visibleAudit = false
          this.spinningAudit = false
        }
      })
    },
    // 打印导出弹框
    handlePrint (type, authCode) {
      const _this = this
      if (this.onlyBorrowFlag) {
        _this.$message.warning('单据均是累计产品无需打印或导出!')
        return
      }
      _this.$store.state.app.curActionPermission = authCode
      // 销售分类导出
      if (type == 'typeExport') {
        const params = {
          salesBillSn: this.bizSn || this.$route.params.sn
        }
        _this.spinning = true
        exportExcel(salesDetailTypeExcel, params, '销售分类' + moment().format('YYYYMMDDHHmmss'), () => {
          _this.spinning = false
          _this.closePrint()
        })
      } else {
        this.detailData.authCode = authCode
        this.nowType = type
        this.openModal = true
      }
    },
    // 关闭打印弹框
    closePrint () {
      this.$store.state.app.curActionPermission = ''
      this.openModal = false
    },
    // 确定打印或预览,导出
    handleOk (objs) {
      const _this = this
      const params = JSON.parse(JSON.stringify(objs))
      _this.$store.state.app.curActionPermission = this.detailData.authCode
      delete params.type
      _this.spinning = true
      if (this.nowType == 'export') { //  导出
        exportExcel(salesDetailExcel, params, '销售' + moment().format('YYYYMMDDHHmmss'), () => {
          _this.spinning = false
          _this.closePrint()
        })
      } else { //  打印
        const taskName = this.nowType == 'SALES_BILL' ? '销售单' : '销售分类'
        printFun(salesDetailPrint, params, objs.type, taskName, () => {
          _this.spinning = false
          _this.closePrint()
        })
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab || this.bizSn) { // 页签刷新时调用
      this.getDetail()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.getDetail()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.fromRouter = from
      vm.authCode = to.meta.permission
    })
  }
}
</script>

<style lang="less">
  .salesDetail-wrap{
    position: relative;
    height: 100%;
    padding-bottom: 45px;
    box-sizing: border-box;
    .empty-data-box{
      width: 100%;
      padding: 10% 30px;
    }
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .salesDetail-cont{
      margin-bottom: 6px;
    }
    .active-title{
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      background: #f3f8fa;
    }
    .flexBox{
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .affix-footer-bar{
      text-align: center;
      background: #fff;
    }
    .redStyle{
      font-weight: bold;
      color: red;
    }
    .form-grid{
      display: flex;
      flex:1;
    }
  }
</style>
