<template>
  <div class="salesDetail-wrap" :style="{paddingBottom:hideFooter?'0px':'45px'}">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle" v-if="!bizSn">
          <a id="salesDetail-back-btn" href="javascript:;" @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="业务状态">{{ detailData&&detailData.billStatusDictValue || '--' }}</a-descriptions-item>
            <a-descriptions-item label="财务状态">{{ detailData&&detailData.financialStatusDictValue || '--' }}</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="备注" :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;" >
        <!-- 统计信息 -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message">
            <div>
              总销售数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
              已取消数量：<strong>{{ detailData&&(detailData.totalCancelQty || detailData.totalCancelQty==0) ? detailData.totalCancelQty : '--' }}</strong>；
              已下推数量：<strong>{{ detailData&&(detailData.totalPushedQty || detailData.totalPushedQty==0) ? detailData.totalPushedQty : '--' }}</strong>；
              待下推数量：<strong>{{ detailData&&(detailData.totalUnpushedQty || detailData.totalUnpushedQty==0) ? detailData.totalUnpushedQty : '--' }}</strong>；
              已发货数量：<strong>{{ detailData&&(detailData.totalDispatchQty || detailData.totalDispatchQty==0) ? detailData.totalDispatchQty : '--' }}</strong>；
              待发货数量：<strong>{{ detailData&&(detailData.totalUndispatchQty || detailData.totalUndispatchQty==0) ? detailData.totalUndispatchQty : '--' }}</strong>；<br/>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_costPrice')">总成本：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? toThousands(detailData.totalCost) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_costPrice')">总毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? toThousands(detailData.grossProfit) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">已取消金额：<strong>{{ detailData&&(detailData.totalCancelAmount || detailData.totalCancelAmount==0) ? toThousands(detailData.totalCancelAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">已下推金额：<strong>{{ detailData&&(detailData.totalPushedAmount || detailData.totalPushedAmount==0) ? toThousands(detailData.totalPushedAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">待下推金额：<strong>{{ detailData&&(detailData.totalUnpushedAmount || detailData.totalUnpushedAmount==0) ? toThousands(detailData.totalUnpushedAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">已发货金额：<strong>{{ detailData&&(detailData.totalDispatchAmount || detailData.totalDispatchAmount==0) ? toThousands(detailData.totalDispatchAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')">待发货金额：<strong>{{ detailData&&(detailData.totalUndispatchAmount || detailData.totalUndispatchAmount==0) ? toThousands(detailData.totalUndispatchAmount) : '--' }}</strong>；</span>
              <span v-if="isCityPrice">市级总售价：<strong>{{ detailData&&(detailData.totalCityAmount || detailData.totalCityAmount==0) ? toThousands(detailData.totalCityAmount) : '--' }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')&&detailData&&detailData.totalDiscountAmount" style="color: red;">优惠金额：<strong>{{ Number(detailData.totalDiscountAmount).toFixed(2) }}</strong>；</span>
              <span v-if="$hasPermissions(authCode + '_salesPrice')&&detailData&&detailData.totalConvertPromoGiftsAmount" style="color: red;">促销产品转采购额金额：<strong>{{ Number(detailData.totalConvertPromoGiftsAmount).toFixed(2) }}</strong>；</span>
            </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.trim="promoFlag" id="salesDetail-promoFlag" 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 :md="6" :sm="24" style="margin-bottom: 10px;">
                    <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>
              <a-button id="salesDetail-updateStock" type="primary" v-if="showStock" @click="getThreeStock" class="button-info">第三方库存</a-button>
              <a-button id="salesDetail-stockOut" v-if="detailData && (detailData.billStatus == 'WAIT_AUDIT' || detailData.billStatus == 'HQ_CHANGE')" type="link" @click="openStockOut">缺货明细</a-button>
              <a-checkbox id="salesDetail-cityPrice" v-model="isCityPrice" v-if="$hasPermissions(authCode + '_cityPrice')"><span style="display: inline-block;margin-top: 1px;">市级价</span></a-checkbox>
            </div>
          </div>
        </div>
        <!-- 正常产品列表 -->
        <div>
          <detailProductList
            ref="productList"
            :maxHeight="pageHeight"
            :detailData="detailData"
            :warehouseSn="warehouseSn"
            :promoFlag="promoFlag"
            :salesBillSn="$route.params.sn || bizSn"
            :authCode="authCode"
            :showCityPrice="isCityPrice">
          </detailProductList>
        </div>
      </a-card>
      <!-- 活动产品列表 -->
      <a-card
        size="small"
        :bordered="false"
        title="活动产品"
        class="salesEdit-cont"
        v-if="activeList.length"
      >
        <activeStatisticsList
          ref="activeTjList"
          type="view"
          :activeList="activeList"
          :warehouseSn="warehouseSn"
          :salesBillSn="$route.params.sn || bizSn"
        ></activeStatisticsList>
        <detailProductList
          ref="productActiveList"
          type="active"
          :detailData="detailData"
          :warehouseSn="warehouseSn"
          :promoFlag="promoFlag"
          :salesBillSn="$route.params.sn || bizSn"
          :authCode="authCode"
          :showCityPrice="isCityPrice">
        </detailProductList>
      </a-card>
    </a-spin>
    <div class="affix-cont" :style="{padding:hideFooter?0:'7px 0 4px'}">
      <a-button
        style="width: 100px;"
        :disabled="spinning"
        type="primary"
        class="button-info"
        id="salesDetail-audit-btn"
        v-if="(detailData&&(detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus=='WAIT_UP_AUDIT_PASS'))&&$hasPermissions('B_salesAudit')"
        @click="handleAudit()"
      >
        审核
      </a-button>
      <a-button
        type="primary"
        :disabled="spinning"
        style="width: 100px;margin: 0 20px;"
        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 20px;"
        :disabled="spinning"
        type="primary"
        id="salesDetail-edit1-btn"
        v-if="detailData&&detailData.salesBillSource == 'PURCHASE' && (detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesEdit')"
        @click="handleChangeOrder()"
      >
        改单
      </a-button>
      <a-button
        style="width: 100px;"
        :disabled="spinning"
        type="primary"
        class="button-success"
        id="salesDetail-batchAudit-btn"
        v-if="detailData&&detailData.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesAudit')"
        @click="handleAudit('batch')"
      >
        一键审核
      </a-button>
      <a-button
        id="salesDetail-dispatch"
        style="width: 100px;"
        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"
      modalType="0"
      :openModal="openVaildPriceModal"
      :dataObj="tempData"
      @close="openVaildPriceModal=false"
      @ok="vaildPriceOk"></vaildPriceModal>
  </div>
</template>

<script>
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
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 {
  salesPromoQueryStatisticsList,
  salesDetailBySn,
  salesDetailPrint,
  salesDetailExcel,
  salesDetailTypeExcel,
  salesWriteAuditPass,
  salesWriteUpAuditPass,
  salesWriteAuditReject,
  salesWriteAuditPush,
  getThirdStockQty,
  salesPromoValidaAudit,
  changeBillCheckUpdatePrice,
  changeBillCheck } from '@/api/salesNew'

export default {
  name: 'SalesDetailNew',
  mixins: [commonMixin],
  components: { VSelect, printModal, auditModal, dsModal, stockOutDetail, chooseWarehouse, detailProductList, activeStatisticsList, tipModal, vaildPriceModal },
  props: {
    bizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false,
      showDsModal: false, // 一键审核弹框
      showStockOut: false, // 缺货明细弹框
      activeList: [], // 参与活动列表
      authCode: '', // 权限码
      hasData: false, // 是否有数据
      showDetail: false, // 基础信息是否显示
      openModal: false, // 打印导出弹框
      detailData: null, //  详情数据
      nowType: null, // 打印导出类型
      isCityPrice: false, //  是否显示市级价
      visibleAudit: false, // 审核弹框
      spinningAudit: false, // 审核loading
      auditText: null, // 审核备注信息
      fromRouter: null, // 从那个页面打开当前页面
      warehouseSn: undefined, // 所在仓库
      promoFlag: undefined, // 产品类型
      openTipModal: false, // 改单弹窗
      sourceData: undefined, // 价格变动数据
      tempData: undefined, // 校验临时数据
      openVaildPriceModal: 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.billStatus == 'HQ_CHANGE' || (detailData.salesBillSource != 'SALES' && detailData.billStatus == 'AUDIT_REJECT') || detailData.billStatus == 'FINISH' || detailData.billStatus == 'OUTING_WAREHOUSE')
    },
    // 是否有促销活动产品
    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.$hasPermissions('B_salesAudit')
    },
    // 表格高度计算
    pageHeight () {
      return this.activeList.length == 0 ? window.innerHeight - 315 + (this.hideFooter ? 45 : 0) : 302
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryNewList' })
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      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.$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.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
          })
        }
      })
    },
    // 取消时，跳转编辑页面
    closeTipModal () {
      this.openTipModal = false
      this.$router.push({ name: 'salesNewEdit', params: { sn: this.$route.params.sn || this.bizSn } })
    },
    // 价格低于成本校验提示，继续审核
    vaildPriceOk (type) {
      // 不通过
      if (type == 'AUDIT_REJECT') {
        this.auditOrder(type)
      } else {
        // 如果时 待上级审核，调用
        if (this.detailData.billStatus == 'WAIT_UP_AUDIT_PASS') {
          this.auditOrder(type)
          return
        }
        this.spinning = true
        // 通过，业务状态变更 待上级审核
        salesWriteUpAuditPass({
          salesBillSn: this.bizSn || this.$route.params.sn,
          billStatus: type
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.handleBack()
          }
          this.$refs.vaildPriceModal.spinning = false
          this.spinning = false
        })
      }
    },
    // 查询第三方库存
    getThreeStock () {
      this.spinning = true
      getThirdStockQty({ salesBillSn: this.bizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.$refs.productList.showThreeStock()
          this.resetSearchForm()
        }
        this.spinning = false
      })
    },
    //  重置
    resetSearchForm () {
      this.warehouseSn = undefined
      this.promoFlag = undefined
      setTimeout(() => {
        this.searchTable()
      }, 100)
    },
    // 查询数据
    searchTable () {
      this.$refs.productList.searchTable()
      if (this.activeList.length) this.$refs.productActiveList.searchTable()
    },
    // 详情
    getDetail () {
      salesDetailBySn({ 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()
      })
    },
    // 获取销售单参与的活动列表
    async getActiveList () {
      // 已参与活动列表
      const list = await salesPromoQueryStatisticsList({ salesBillSn: this.$route.params.sn || this.bizSn }).then(res => res.data || [])
      this.activeList = list.filter(item => item.promotion && item.promotionRule)
      // 触发活动统计查询变量
      this.$nextTick(() => {
        if (this.activeList.length) {
          this.$refs.activeTjList.hasInit = false
        }
      })
      setTimeout(() => {
        this.resetSearchForm()
      }, 500)
    },
    // 打开缺货明细弹框
    openStockOut () {
      if (this.$refs.productList.outStockStr != '') {
        this.showStockOut = true
      } else {
        this.$info({
          title: '提示',
          content: '此销售单暂无缺货产品！',
          centered: true
        })
      }
    },
    // 下推
    handleDispatch (row) {
      this.$router.push({ name: 'waitDispatchNew', params: { salesBillSn: row.salesBillSn } })
    },
    // 打开审核/一键审核弹框
    async handleAudit (isBatch) {
      const _this = this
      // 校验产品是否付个促销活动规则
      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 b = vaildActive.filter(item => item.type == 0) // 可跳过继续提交
        const d = vaildActive.filter(item => item.type == 'audit') // 售价是否低于参考成本价
        // 弹出不符合规则弹框，不可提交
        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
        } else 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 () {
              _this.verificationSuccess(isBatch)
            }
          })
          _this.spinning = false
        } else if (d.length) {
          // 售价是否低于参考成本价
          if (isBatch) { // 一键审核
            _this.tempData = { vaildPriceList: d[0].salesPromoDetailEntityList.map(item => item.productCode) }
            this.verificationSuccess(isBatch)
          } else {
            // 审核
            _this.tempData = d[0]
            _this.openVaildPriceModal = true
          }
        } else {
          this.verificationSuccess(isBatch)
        }
      } else {
        this.verificationSuccess(isBatch)
      }
    },
    // 消息提示
    messageInfo (content) {
      this.$info({
        title: '提示',
        content: content,
        centered: true
      })
    },
    // 验证通过
    verificationSuccess (isBatch) {
      if (isBatch) { // 一键审核
        if (this.$refs.productList.hasOutStockOfActive) {
          this.messageInfo('参加促销活动的产品存在缺货，不可一键审核!')
          return
        }
        if (this.$refs.productList.showConvertPromoGifts) {
          this.messageInfo('该活动规则中，促销产品可转费用报销单，不可一键审核!')
          return
        }
        if (this.$refs.productList.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)
      } else {
        this.auditText = null
        this.visibleAudit = true
      }
    },
    // 一键审核
    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
      })
    },
    // 审核
    auditOrder (billStatus) {
      this.spinningAudit = true
      const auditFun = billStatus == 'AUDIT_PASS' ? salesWriteAuditPass : salesWriteAuditReject
      auditFun({
        salesBillSn: this.bizSn || this.$route.params.sn,
        billStatus: billStatus
      }).then(res => {
        if (res.status == 200) {
          this.visibleAudit = false
          this.$message.success(res.message)
          this.spinningAudit = false
          const _this = this
          this.$nextTick(() => {
            if (billStatus == 'AUDIT_PASS' && !_this.auditText) {
              _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
      _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.$store.state.app.curActionPermission = ''
        })
      } 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.$store.state.app.curActionPermission = ''
        })
      } else { //  打印
        const taskName = this.nowType == 'SALES_BILL' ? '销售单' : '销售分类'
        printFun(salesDetailPrint, params, objs.type, taskName, () => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        })
      }
    }
  },
  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;
    >.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;
    }
    .footer-cont{
      margin-top: 5px;
      text-align: center;
    }
    .redStyle{
      font-weight: bold;
      color: red;
    }
  }
</style>
