<template>
  <div v-if="showPage" class="salesDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont" :style="{ padding: !outBizSn ? '16px 24px' : '0px 24px' }">
        <template slot="subTitle" v-if="!outBizSn">
          <a href="javascript:;" @click="handleBack"><a-icon type="left"></a-icon> 返回列表</a>
          <a-button
            v-if="(detailData&&detailData.billStatus !== 'CANCEL' && detailData.billStatus !== 'FINISH' && detailData.billStatus != 'WAIT_OUT_WAREHOUSE')&&$hasPermissions('B_salesEdit')"
            type="primary"
            size="small"
            style="background-color: #1890ff;margin-left: 20px;border: #1890ff;"
            id="salesDetail-edit-btn"
            @click.stop="handleEdit">编辑</a-button>
        </template>
        <template slot="extra" v-if="outBizSn ? $hasPermissions('B_outboundOrderDetail') : $hasPermissions('B_salesPrint')">
          <Print :disabled="localDataSource.length==0" @handlePrint="handlePrint"></Print>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="salesDetail-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions size="small" :column="3">
              <a-descriptions-item label="客户名称">{{ detailData&&detailData.buyerName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="客户地址" :span="2">
                <div v-if="detailData&&(detailData.shippingAddressProvinceName || detailData.shippingAddressCityName || detailData.shippingAddressCountyName || detailData.shippingAddress)">
                  {{ detailData&&detailData.shippingAddressProvinceName || '' }}
                  {{ detailData&&detailData.shippingAddressCityName || '' }}
                  {{ detailData&&detailData.shippingAddressCountyName || '' }}
                  {{ detailData&&detailData.shippingAddress || '' }}
                </div>
                <span v-else>--</span>
              </a-descriptions-item>
              <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleEntity&&detailData.settleStyleEntity.name || '--' }}</a-descriptions-item>
              <a-descriptions-item label="联系电话">{{ detailData&&detailData.consigneeTel || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
              <a-descriptions-item label="销售单号">{{ detailData&&detailData.salesBillNo || '--' }}</a-descriptions-item>
              <a-descriptions-item label="制单人">{{ detailData&&detailData.operatorName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务员">{{ detailData&&detailData.salesManName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="来源">{{ detailData&&detailData.salesBillSourceDictValue || '--' }}</a-descriptions-item>
              <a-descriptions-item label="下级采购单号" v-if="detailData&&detailData.salesBillSource=='PURCHASE'">{{ detailData&&detailData.purchaseBillNo || '--' }}</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>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="pages-wrap">
        <!-- alert -->
        <a-alert type="info" style="margin-bottom: 10px;">
          <div slot="message">
            总款数：<strong>{{ detailData&&(detailData.totalCategory || detailData.totalCategory==0) ? detailData.totalCategory : '--' }}</strong>；
            总数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
            总赠品数量：<strong>{{ detailData&&(detailData.giftQty || detailData.giftQty==0) ? detailData.giftQty : '--' }}</strong>；
            急件总款数：<strong>{{ detailData&&(detailData.oosCategory || detailData.oosCategory==0) ? detailData.oosCategory : '--' }}</strong>；
            急件总数量：<strong>{{ detailData&&(detailData.oosQty || detailData.oosQty==0) ? detailData.oosQty : '--' }}</strong>；<br/>
            总售价：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? detailData.totalAmount : '--' }}</strong>；
            总成本：<strong>{{ detailData&&(detailData.totalCost || detailData.totalCost==0) ? detailData.totalCost : '--' }}</strong>；
            总毛利：<strong>{{ detailData&&(detailData.grossProfit || detailData.grossProfit==0) ? detailData.grossProfit : '--' }}</strong>；
            折后总售价：<strong>{{ detailData&&(detailData.discountedAmount || detailData.discountedAmount==0) ? detailData.discountedAmount : '--' }}</strong>；
            折扣：<strong>{{ detailData&&(detailData.discountRate || detailData.discountRate==0) ? detailData.discountRate+'%' : '--' }}</strong>；
            折扣金额：<strong>{{ detailData&&(detailData.discountAmount || detailData.discountAmount==0) ? detailData.discountAmount : '--' }}</strong>；
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          bordered>
        </s-table>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { getOperationalPrecision } from '@/libs/tools.js'
import { STable, VSelect } from '@/components'
import { salesDetailBySn, salesDetailPrint, salesDetailExport } from '@/api/sales'
import { salesDetailList } from '@/api/salesDetail'
import Print from '@/views/common/print.vue'
import { hdPrint } from '@/libs/JGPrint'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect, Print },
  mixins: [commonMixin],
  props: {
    outBizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      showPage: false,
      spinning: false,
      disabled: false,
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', dataIndex: 'cost', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '售价', dataIndex: 'price', width: '5%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折后售价', dataIndex: 'discountedPrice', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '销售数量', dataIndex: 'qty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productOrigUnit', width: '4%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价小计', dataIndex: 'totalAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折后小计', dataIndex: 'discountedAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折扣金额', dataIndex: 'discountAmount', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '仓库', dataIndex: 'warehouseName', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '是否急件', dataIndex: 'oosFlagDictValue', width: '6%', align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return salesDetailList(Object.assign(parameter, { salesBillSn: this.outBizSn || this.$route.params.sn })).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              const productCode = (data.list[i].productEntity && data.list[i].productEntity.code) || (data.list[i].dealerProductEntity && data.list[i].dealerProductEntity.code)
              const productName = (data.list[i].productEntity && data.list[i].productEntity.name) || (data.list[i].dealerProductEntity && data.list[i].dealerProductEntity.name)
              const productOrigCode = (data.list[i].productEntity && data.list[i].productEntity.origCode) || (data.list[i].dealerProductEntity && data.list[i].dealerProductEntity.origCode)
              const productOrigUnit = (data.list[i].productEntity && data.list[i].productEntity.unit) || (data.list[i].dealerProductEntity && data.list[i].dealerProductEntity.unit)
              data.list[i].productCode = productCode || '--'
              data.list[i].productName = productName || '--'
              data.list[i].productOrigCode = productOrigCode || '--'
              data.list[i].productOrigUnit = productOrigUnit || '--'
              data.list[i].warehouseName = data.list[i].warehouseEntity && data.list[i].warehouseEntity.name || '--'
              data.list[i].warehouseLocationName = data.list[i].warehouseLocationEntity && data.list[i].warehouseLocationEntity.name || '--'
              // 售价小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
              data.list[i].salePriceSubtotal = getOperationalPrecision(data.list[i].price, data.list[i].qty)
            }
            this.localDataSource = data.list
            this.disabled = false
          }
          return data
        })
      },
      localDataSource: [],
      detailData: null //  详情数据
    }
  },
  methods: {
    // 打印预览/快捷打印
    handlePrint (type, printerType) {
      const _this = this
      _this.spinning = true
      let url = salesDetailPrint
      const params = { sn: this.outBizSn || this.$route.params.sn }
      if (type == 'export') { //  导出
        url = salesDetailExport
      }
      // 打印或导出
      hdPrint(printerType, type, url, params, '销售单', function () {
        _this.spinning = false
      })
    },
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/salesQuery/list' })
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      this.$router.push({ name: 'salesEdit', params: { id: row.id, sn: row.salesBillSn, priceType: row.priceType } })
    },
    //  详情
    getDetail () {
      salesDetailBySn({ salesBillSn: this.outBizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        } else {
          this.detailData = null
        }
      })
    },
    pageInit () {
      const vm = this
      vm.$nextTick(() => {
        vm.spinning = false
        vm.disabled = false
        vm.$refs.table.refresh(true)
        vm.getDetail()
      })
    }
  },
  mounted () {
    this.showPage = true
    if (!this.$store.state.app.isNewTab || this.outBizSn) { // 页签刷新 或 为弹框时调用
      this.pageInit()
    }
  },
  activated () {
    this.showPage = true
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  deactivated () {
    // this.localDataSource = []
    // this.showPage = false
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style lang="less">
  .salesDetail-wrap{
    .salesDetail-cont{
      margin-bottom: 10px;
    }
  }
</style>
