<template>
  <div class="salesDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont">
        <template slot="subTitle">
          <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="$hasPermissions('B_salesPrint')">
          <!-- <span>打印字段：</span>
          <a-select key="1" style="width:150px" id="salesDetail-pritKey" placeholder="请选择打印字段" allowClear>
            <a-select-option v-for="item in pritKey" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select>
          <span><i style="color: red;">*</i>打印模板：</span>
          <a-select key="2" style="width:150px" id="salesDetail-pritKey" placeholder="请选择打印模板" allowClear>
            <a-select-option v-for="item in pritModal" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
          </a-select> -->
          <!-- <a-button key="5" id="salesDetail-export-btn">导出</a-button> -->
          <a-radio-group key="3" v-model="printerType">
            <a-radio value="NEEDLE">针式</a-radio>
            <a-radio value="INK">喷墨</a-radio>
          </a-radio-group>
          <a-button key="2" id="salesDetail-preview-btn" :disabled="localDataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="salesDetail-print-btn" :disabled="localDataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </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? detailData.buyerName : '--' }}</a-descriptions-item>
              <a-descriptions-item label="客户地址">{{ detailData&&detailData.shippingAddressProvinceName ? detailData.shippingAddressProvinceName : '--' }}{{ detailData.shippingAddressCityName || '--' }}{{ detailData.shippingAddressCountyName || '--' }}{{ detailData.shippingAddress || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleEntity&&detailData.settleStyleEntity.name?detailData.settleStyleEntity.name: '--' }}</a-descriptions-item>
              <a-descriptions-item label="联系电话">{{ detailData&&detailData.consigneeTel ? detailData.consigneeTel : '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ detailData&&detailData.remarks ? detailData.remarks : '--' }}</a-descriptions-item>
              <a-descriptions-item label="销售单号">{{ detailData&&detailData.salesBillNo ? detailData.salesBillNo : '--' }}</a-descriptions-item>
              <a-descriptions-item label="制单人">{{ detailData&&detailData.operatorName ? detailData.operatorName : '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务员">{{ detailData&&detailData.salesManName ? detailData.salesManName : '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ detailData&&detailData.billStatusDictValue ? detailData.billStatusDictValue : '--' }}</a-descriptions-item>
              <a-descriptions-item label="财务状态">{{ detailData&&detailData.financialStatusDictValue ? 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: 15px;">
          <div slot="message">
            总款数：<strong>{{ detailData&&detailData.totalCategory ? detailData.totalCategory : 0 }}</strong>；
            总数量：<strong>{{ detailData&&detailData.totalQty ? detailData.totalQty : 0 }}</strong>；
            总赠品数量：<strong>{{ detailData&&detailData.giftQty ? detailData.giftQty : 0 }}</strong>；
            急件总款数：<strong>{{ detailData&&detailData.oosCategory ? detailData.oosCategory : 0 }}</strong>；
            急件总数量：<strong>{{ detailData&&detailData.oosQty ? detailData.oosQty : 0 }}</strong>；<br/>
            总售价：<strong>{{ detailData&&detailData.totalAmount ? detailData.totalAmount : 0 }}</strong>；
            总成本：<strong>{{ detailData&&detailData.totalCost ? detailData.totalCost : 0 }}</strong>；
            总毛利：<strong>{{ detailData&&detailData.grossProfit ? detailData.grossProfit : 0 }}</strong>；
            折后总售价：<strong>{{ detailData&&detailData.discountedAmount ? detailData.discountedAmount : 0 }}</strong>；
            折扣：<strong>{{ detailData&&detailData.discountRate ? detailData.discountRate : 0 }}%</strong>；
            折扣金额：<strong>{{ detailData&&detailData.discountAmount ? detailData.discountAmount : 0 }}</strong>；
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 1660 }"
          bordered>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { getOperationalPrecision } from '@/libs/tools.js'
import { STable, VSelect } from '@/components'
import { salesDetailBySn, salesDetailPrint } from '@/api/sales'
import { salesDetailList } from '@/api/salesDetail'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      disabled: false,
      pritKey: [
        { id: 0, name: '打印促销' },
        { id: 1, name: '打印支付方式' },
        { id: 2, name: '打印收款方式' }
      ],
      pritModal: [
        { id: 0, name: '普通模板一' },
        { id: 1, name: '普通模板二' },
        { id: 2, name: '仓库模板一' }
      ],
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center', fixed: 'left' },
        { title: '产品编码', dataIndex: 'productCode', width: 140, align: 'center' },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价', dataIndex: 'cost', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '售价', dataIndex: 'price', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '折后售价', dataIndex: 'discountedPrice', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '销售数量', dataIndex: 'qty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '单位', dataIndex: 'productOrigUnit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价小计', dataIndex: 'totalAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '折后小计', dataIndex: 'discountedAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '折扣金额', dataIndex: 'discountAmount', width: 100, align: 'center', customRender: function (text) { return '￥' + (text || 0) } },
        { title: '仓库', dataIndex: 'warehouseName', width: 100, align: 'center' },
        { title: '仓位', dataIndex: 'warehouseLocationName', width: 100, align: 'center' },
        { title: '是否急件', dataIndex: 'oosFlagDictValue', width: 100, align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return salesDetailList(Object.assign(parameter, { salesBillSn: this.$route.params.sn })).then(res => {
          const 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, //  详情数据
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'salesQueryList' })
    },
    // 编辑
    handleEdit () {
      const row = this.detailData
      this.$router.push({ name: 'salesEdit', params: { id: row.id, sn: row.salesBillSn, priceType: row.priceType } })
    },
    //  详情
    getDetail () {
      salesDetailBySn({ salesBillSn: this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        } else {
          this.detailData = null
        }
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      _this.spinning = true
      salesDetailPrint({ sn: this.$route.params.sn, type: this.printerType }).then(res => {
        _this.spinning = false
        if (res.type == 'application/json') {
          var reader = new FileReader()
          reader.addEventListener('loadend', function () {
            const obj = JSON.parse(reader.result)
            _this.$notification.error({
              message: '提示',
              description: obj.message
            })
          })
          reader.readAsText(res)
        } else {
          this.print(res, type)
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printf" name="printf" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printf'].focus()
        window.frames['printf'].print()
      }
    }
  },
  mounted () {
    this.getDetail()
  }
}
</script>

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