<template>
  <div class="salesDetail-wrap" :style="{paddingBottom:hideFooter?'0px':'60px'}">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle" v-if="!bizSn">
          <a id="salesEdit-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-export-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: 8px;" 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">
        <!-- alert -->
        <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>
            </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="350px">
                    <a-form-item label="出库仓库">
                      <chooseWarehouse ref="warehouse" v-model="warehouseSn"></chooseWarehouse>
                    </a-form-item>
                  </a-col>
                  <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                    <a-button type="primary" @click="searchTable" :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>
            </div>
          </div>
        </div>
        <!-- 产品列表 -->
        <div>
          <detailProductList
            ref="productList"
            :detailData="detailData"
            :warehouseSn="warehouseSn"
            :salesBillSn="$route.params.sn || bizSn"
            :authCode="authCode"
            :maxHeight="pageHeight"
            :showCityPrice="isCityPrice">
          </detailProductList>
        </div>
      </a-card>
    </a-spin>
    <div class="affix-cont" :style="{padding:hideFooter?0:'7px 0 4px'}">
      <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="primary"
        :disabled="spinning"
        class="button-info"
        size="large"
        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
        size="large"
        style="width: 100px;margin: 0 20px;"
        :disabled="spinning"
        type="primary"
        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-info"
        id="salesDetail-batchAudit-btn"
        v-if="detailData&&detailData.billStatus == 'WAIT_AUDIT'&&$hasPermissions('B_salesAudit')"
        @click="handleAudit('batch')"
      >
        一键审核
      </a-button>
      <a-button
        size="large"
        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>
  </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 {
  salesDetailBySn,
  salesDetailPrint,
  salesDetailExcel,
  salesDetailTypeExcel,
  salesWriteAuditPass,
  salesWriteAuditReject,
  salesWriteAuditPush
} from '@/api/salesNew'

export default {
  name: 'SalesDetailNew',
  mixins: [commonMixin],
  components: { VSelect, printModal, auditModal, dsModal, stockOutDetail, chooseWarehouse, detailProductList },
  props: {
    bizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      disabled: false,
      showDsModal: false,
      showStockOut: false,
      authCode: '', // 权限码
      hasData: false, // 是否有数据
      showDetail: false,
      openModal: false,
      detailData: null, //  详情数据
      nowType: null,
      isCityPrice: false, //  是否显示市级价
      visibleAudit: false,
      auditInfo: null,
      spinningAudit: false,
      auditText: null,
      fromRouter: null,
      warehouseSn: undefined
    }
  },
  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')
    },
    pageHeight () {
      return window.innerHeight - 333 + (this.hideFooter ? 50 : 0)
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryNewList' })
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      this.$router.push({ name: 'salesNewEdit', params: { sn: row.salesBillSn, wSn: row.warehouseSn } })
    },
    //  重置
    resetSearchForm () {
      this.warehouseSn = undefined
      setTimeout(() => {
        this.searchTable()
      }, 100)
    },
    // 查询数据
    searchTable () {
      this.$refs.productList.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.$refs.productList.pageInit()
      })
    },
    // 打开缺货明细
    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 } })
    },
    // 打开审核/一键审核弹框
    handleAudit (isBatch) {
      if (isBatch) { // 一键审核
        if (this.detailData && this.detailData.promoFlag == 1 && this.$refs.productList.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.$store.state.app.curActionPermission = ''
        })
      } else {
        this.detailData.authCode = authCode
        this.nowType = type
        this.openModal = true
      }
    },
    closePrint () {
      console.log(9)
      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: 51px;
    box-sizing: border-box;
    >.ant-spin-nested-loading{
      overflow-y: auto;
      height: 100%;
    }
    .salesDetail-cont{
      margin-bottom: 10px;
    }
    .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>
