<template>
  <div class="salesDetail-All-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle" v-if="!bizSn">
          <a href="javascript:;" @click="handleBack"><a-icon type="left"></a-icon> 返回列表</a>
        </template>
        <template slot="extra">
          <a-button
            key="1"
            type="primary"
            class="button-info"
            id="salesDetail-xs-print-btn"
            v-if="$hasPermissions('B_salesPrint')"
            :disabled="localDataSource.length==0"
            @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="localDataSource.length==0"
            @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="localDataSource.length==0"
            @click="handlePrint('export','B_salesDetailExport')">导出Excel</a-button>
          <a-button
            key="4"
            type="default"
            class="button-info"
            id="salesDetail-export-btn"
            v-if="$hasPermissions('B_salesTypeExport')"
            :disabled="localDataSource.length==0"
            @click="handlePrint('typeExport','B_salesTypeExport')">销售分类导出</a-button>
        </template>
      </a-page-header>

      <a-card size="small" :bordered="false" class="pages-wrap">
        <!-- 基础信息 -->
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions size="small" :column="3">
              <a-descriptions-item label="销售单号" :span="2">
                {{ detailData&&detailData.salesBillNo || '--' }}
                <span v-if="detailData&&detailData.salesBillNoSource">（原：{{ detailData&&detailData.salesBillNoSource || '--' }}）</span>
              </a-descriptions-item>
              <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.settleStyleSnDictValue || '--' }}</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.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="备注" :span="3">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
        <!-- 统计信息 -->
        <a-alert type="info" style="margin: 10px 0;">
          <div slot="message">
            <div>
              已下推数量：<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>{{ toThousands(detailData.totalDiscountAmount) }}</strong>；</span>
              <span v-if="isAveragePrice">合计重量(kg)：<strong>{{ detailData&&(detailData.totalWeightKg || detailData.totalWeightKg==0) ? detailData.totalWeightKg : '--' }}</strong>；</span>
              <span v-if="isAveragePrice&&$hasPermissions(pageTypeAuth + '_costPrice')">平均成本公斤单价：<strong>{{ detailData&&(detailData.totalWeightAvgCost || detailData.totalWeightAvgCost==0) ? toThousands(detailData.totalWeightAvgCost) : '--' }}</strong>；</span>
              <span v-if="isAveragePrice&&$hasPermissions(pageTypeAuth + '_salesPrice')">平均售价公斤单价：<strong>{{ detailData&&(detailData.totalWeightAvgPrice || detailData.totalWeightAvgPrice==0) ? toThousands(detailData.totalWeightAvgPrice) : '--' }}</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="$refs.table.refresh(true)">
                <a-row :gutter="15" type="flex">
                  <a-col :md="6" :sm="24" flex="350px">
                    <a-form-item label="出库仓库">
                      <chooseWarehouse ref="warehouse" v-model="queryParam.warehouseSn"></chooseWarehouse>
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="productInfoList-refresh">查询</a-button>
                    <a-button style="margin-left: 5px" @click="resetSearchForm" id="productInfoList-reset">重置</a-button>
                  </a-col>
                </a-row>
              </a-form>
            </div>
            <div>
              <a-button v-if="detailData && (detailData.billStatus == 'WAIT_AUDIT' || detailData.billStatus == 'HQ_CHANGE')" type="link" @click="openStockOut">缺货明细</a-button>
              <a-checkbox v-model="isCityPrice" v-if="$hasPermissions(authCode + '_cityPrice')"><span style="display: inline-block;margin-top: 1px;">市级价</span></a-checkbox>
              <a-checkbox v-model="isAveragePrice" v-if="$hasPermissions(pageTypeAuth + '_avgprice')"><span style="display: inline-block;margin-top: 1px;">平均公斤单价</span></a-checkbox>
            </div>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: 300 }"
          :defaultLoadData="false"
          :showPagination="false"
          bordered>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <div>
              <span>{{ text }}</span>
              <a-badge count="促" v-if="record.promotionFlag=='GIFT'" :number-style="{ backgroundColor: '#52c41a', zoom:'80%' }"></a-badge>
              <a-badge count="特" v-if="record.promotionFlag=='DISCOUNT'" :number-style="{ backgroundColor: '#faad14', zoom:'80%' }"></a-badge>
              <!-- 可审核时才可显示“缺”货产品 -->
              <a-badge count="缺" v-if="(Number(record.stockQty) < Number(record.unpushedQty)) && (detailData&&(detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesAudit'))">
              </a-badge>
            </div>
          </template>
          <!-- 当前库存 -->
          <template slot="stockQty" slot-scope="text, record">
            <div v-if="record.stockQty || record.stockQty==0">
              <p style="margin: 0;" v-if="Number(record.stockQty) < Number(record.unpushedQty)">{{ record.stockQty }}(<span class="redStyle">缺{{ Number(record.unpushedQty) - Number(record.stockQty) }}</span>)</p>
              <p style="margin: 0;" v-else>{{ record.stockQty }}</p>
            </div>
            <span v-else>--</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <div class="affix-cont">
      <a-button
        size="large"
        style="width: 100px;"
        :disabled="spinning"
        type="primary"
        class="button-info"
        id="salesDetail-audit-btn"
        v-if="detailData&&detailData.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesAudit')"
        @click="handleAudit()"
      >
        审核
      </a-button>
      <a-button
        type="default"
        :disabled="spinning"
        class="button-info"
        size="large"
        style="width: 100px;margin: 0 20px;"
        id="salesDetail-edit-btn"
        v-if="detailData&&detailData.salesBillSource != 'PURCHASE' && (detailData.billStatus == 'WAIT_SUBMIT' || detailData.billStatus == 'WAIT_AUDIT' || detailData.billStatus == 'AUDIT_REJECT')&&$hasPermissions('B_salesEdit')"
        @click="handleEdit()"
      >
        编辑
      </a-button>
      <a-button
        size="large"
        style="width: 100px;margin: 0 20px;"
        :disabled="spinning"
        type="default"
        class="button-info"
        id="salesDetail-edit-btn"
        v-if="detailData&&detailData.salesBillSource == 'PURCHASE' && (detailData.billStatus == 'WAIT_AUDIT'||detailData.billStatus == 'HQ_CHANGE')&&$hasPermissions('B_salesEdit')"
        @click="handleEdit()"
      >
        改单
      </a-button>
      <a-button
        size="large"
        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>
    </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>
  </div>
</template>

<script>
import { printFun, exportExcel } from '@/libs/JGPrint.js'
import { commonMixin } from '@/utils/mixin'
import moment from 'moment'
import { STable, VSelect } from '@/components'
import printModal from './printModal.vue'
import auditModal from '@/views/common/auditModal.vue'
import dsModal from '@/views/salesManagement/waitDispatch/dsModal.vue'
import stockOutDetail from './stockOutDetailModal.vue'
import chooseWarehouse from '@/views/common/chooseWarehouse'
import { salesDetailBySn, salesDetailAllList, salesDetailPrint, salesDetailExcel, salesDetailTypeExcel, salesWriteAuditReject, salesWriteAuditPass, salesWriteAuditPush } from '@/api/salesNew'
export default {
  name: 'SalesDetailALL',
  mixins: [commonMixin],
  components: { STable, VSelect, printModal, auditModal, dsModal, stockOutDetail, chooseWarehouse },
  props: {
    bizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    },
    pageTypeAuth: { // 页面权限显示
      type: String,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false,
      showDsModal: false, // 销售单一键审核弹框
      showStockOut: false, // 缺货明细弹框
      queryParam: {
        warehouseSn: undefined // 仓库sn
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.$store.state.app.curActionPermission = this.authCode
        const params = Object.assign(parameter, { salesBillSn: this.bizSn || this.$route.params.sn, warehouseSn: this.queryParam.warehouseSn })
        //  审核，需用到库存
        if (this.detailData && (this.detailData.billStatus == 'WAIT_AUDIT' || this.detailData.billStatus == 'HQ_CHANGE') && this.$hasPermissions('B_salesAudit')) {
          params.showStock = true
        } else { // 非审核
          params.showStock = false
        }
        return salesDetailAllList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = 0
            this.outStockStr = ''
            let str = ''
            for (var i = 0; i < data.length; i++) {
              data[i].no = no + i + 1
              const productCode = (data[i].productEntity && data[i].productEntity.code) || (data[i].dealerProductEntity && data[i].dealerProductEntity.code)
              const productName = (data[i].productEntity && data[i].productEntity.name) || (data[i].dealerProductEntity && data[i].dealerProductEntity.name)
              const productOrigCode = (data[i].productEntity && data[i].productEntity.origCode) || (data[i].dealerProductEntity && data[i].dealerProductEntity.origCode)
              const productOrigUnit = (data[i].productEntity && data[i].productEntity.unit) || (data[i].dealerProductEntity && data[i].dealerProductEntity.unit)
              data[i].productCode = productCode || '--'
              data[i].productName = productName || '--'
              data[i].productOrigCode = productOrigCode == ' ' ? '--' : productOrigCode
              data[i].productOrigUnit = productOrigUnit || '--'
              if (data[i].unpushedQty && (Number(data[i].stockQty) < Number(data[i].unpushedQty))) {
                str += data[i].productCode + '、'
              }
            }
            if (str.length > 0) {
              str = str.substr(0, str.length - 1)
              this.outStockStr = '产品编号为：' + str + '的产品库存不足；'
            }
            this.localDataSource = data
            this.disabled = false
          }
          return data
        })
      },
      localDataSource: [], // 原始列表数据
      openModal: false, // 打印导出弹框
      detailData: null, //  详情数据
      nowType: null, // 打印导出类型
      isCityPrice: false, //  是否显示市级价
      visibleAudit: false, // 审核弹框
      spinningAudit: false, // 审核loading
      outStockStr: '', // 缺货产品信息说明
      auditText: null, // 审核备注
      authCode: '', // 当前权限码
      isAveragePrice: 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
      }
    },
    // 列定义
    columns () {
      const _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '10%', scopedSlots: { customRender: 'productCode' }, align: 'left' },
        { title: '产品名称', dataIndex: 'productName', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '出库仓库', dataIndex: 'warehouseName', width: '8%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true }
        // { title: '成本价', dataIndex: 'showCost', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '省级价', dataIndex: 'provincePrice', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '市级价', dataIndex: 'cityPrice', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '销售价', dataIndex: 'price', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },

        // { title: '库存', dataIndex: 'stockQty', scopedSlots: { customRender: 'stockQty' }, width: '6%', align: 'center' },
        // { title: '待下推数', dataIndex: 'unpushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '已下推数', dataIndex: 'pushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '已取消数', dataIndex: 'cancelQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions(this.authCode + '_costPrice')) { //  成本价权限
        arr.push({ title: '成本价', dataIndex: 'showCost', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions(this.authCode + '_provincePrice')) {
        arr.push({ title: '省级价', dataIndex: 'provincePrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      // 是否勾选市级价格
      if (this.isCityPrice) {
        arr.push({ title: '市级价', dataIndex: 'cityPrice', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        if (this.$hasPermissions(this.authCode + '_salesPrice')) { //  售价权限
          arr.push({ title: '销售价', dataIndex: 'price', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
      } else {
        if (this.$hasPermissions(this.authCode + '_salesPrice')) { //  售价权限
          arr.push({ title: '销售价', dataIndex: 'price', width: '6%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        }
      }
      arr.push({ title: '单位', dataIndex: 'productOrigUnit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } })
      arr.push({ title: '销售数量', dataIndex: 'qty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      //  审核，需用到库存
      if (this.detailData && (this.detailData.billStatus == 'WAIT_AUDIT' || this.detailData.billStatus == 'HQ_CHANGE') && this.$hasPermissions('B_salesAudit')) {
        arr.push({ title: '库存', dataIndex: 'stockQty', scopedSlots: { customRender: 'stockQty' }, width: '6%', align: 'center' })
      }
      arr.push({ title: '待下推数', dataIndex: 'unpushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      arr.push({ title: '已下推数', dataIndex: 'pushedQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      arr.push({ title: '已取消数', dataIndex: 'cancelQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      if (this.isAveragePrice) {
        arr.push({ title: '单重（kg）', dataIndex: 'weightKg', width: '7%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.push({ title: '合计重量（kg）', dataIndex: 'totalWeightKg', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      if (this.$hasPermissions(this.pageTypeAuth + '_costPrice') && this.isAveragePrice) {
        arr.push({ title: '平均成本公斤单价', dataIndex: 'weightAvgCost', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions(this.pageTypeAuth + '_salesPrice') && this.isAveragePrice) {
        arr.push({ title: '平均售价公斤单价', dataIndex: 'weightAvgPrice', width: '10%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryList' })
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      this.$router.push({ name: 'salesEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.warehouseSn = undefined
      this.$refs.table.refresh()
    },
    // 打开缺货明细
    openStockOut () {
      if (this.outStockStr != '') {
        this.showStockOut = true
      } else {
        this.$info({
          title: '提示',
          content: '此销售单暂无缺货产品！',
          centered: true
        })
      }
    },
    // 详情
    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.$refs.table.refresh(true)
        } else {
          this.detailData = null
        }
      })
    },
    // 打开审核/一键审核弹框
    handleAudit (isBatch) {
      if (isBatch) { // 一键审核
        if (this.detailData && this.detailData.promoFlag == 1 && this.outStockStr != '') {
          this.$info({
            title: '提示',
            content: '参加促销活动的销售单，有缺货产品，不可一键审核！',
            centered: true
          })
          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.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()
    }
  }
}
</script>

  <style lang="less">
    .salesDetail-All-wrap{
      position: relative;
      height: 100%;
      padding-bottom: 51px;
      box-sizing: border-box;
      >.ant-spin-nested-loading{
        overflow-y: auto;
        height: 100%;
      }

      .flexBox{
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .footer-cont{
        margin-top: 5px;
        text-align: center;
      }
      .redStyle{
        font-weight: bold;
        color: red;
      }
      .form-grid{
        display:flex;
        flex:1;
      }
    }
  </style>
