<template>
  <div class="salesReturnDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesReturnDetail-cont">
        <template slot="subTitle">
          <a href="javascript:;" @click="handleBack"><a-icon type="left"></a-icon> 返回列表</a>
        </template>
        <template slot="extra" v-if="$hasPermissions('B_salesReturnPrint')">
          <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="salesReturnDetail-preview-btn" :disabled="localDataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="salesReturnDetail-print-btn" :disabled="localDataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <a-card size="small" :bordered="false" class="salesReturnDetail-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="客户地址">
                <div v-if="detailData&&(detailData.provinceName || detailData.cityName || detailData.countyName || detailData.customerAddr)">
                  {{ detailData&&detailData.provinceName || '' }}
                  {{ detailData&&detailData.cityName || '' }}
                  {{ detailData&&detailData.countyName || '' }}
                  {{ detailData&&detailData.customerAddr || '' }}
                </div>
                <span v-else>--</span>
              </a-descriptions-item>
              <a-descriptions-item label="联系电话">{{ detailData&&detailData.contactTel || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
              <a-descriptions-item label="退货单号">{{ detailData&&detailData.salesReturnNo || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ detailData&&detailData.stateDictValue || '--' }}</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;" v-if="detailData">
          <div slot="message">
            总款数：<strong>{{ countData&&(countData.totalCategory || countData.totalCategory==0) ? countData.totalCategory : '--' }}</strong>；
            总数量：<strong>{{ countData&&(countData.totalQty || countData.totalQty==0) ? countData.totalQty : '--' }}</strong>；
            废品数量：<strong>{{ countData&&(countData.totalCelQty || countData.totalCelQty==0) ? countData.totalCelQty : '--' }}</strong>；<br/>
            退货总金额：<strong>{{ countData&&(countData.totalAmount || countData.totalAmount==0) ? countData.totalAmount : '--' }}</strong>；
            折扣金额：<strong>{{ countData&&(countData.discountAmount || countData.discountAmount==0) ? countData.discountAmount : '--' }}</strong>；
            折扣：<strong>{{ countData&&(countData.discountRate || countData.discountRate==0) ? countData.discountRate+'%' : '--' }}</strong>；
            折后金额：<strong>{{ countData&&(countData.discountedAmount || countData.discountedAmount==0) ? countData.discountedAmount : '--' }}</strong>；
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="default"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 1430 }"
          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 { salesReturnDetail, salesReturnQueryCount, salesReturnDetailList, salesReturnDetailPrint } from '@/api/salesReturn'
export default {
  name: 'SalesReturnDetail',
  components: { STable, VSelect },
  data () {
    return {
      spinning: false,
      disabled: false,
      countData: null,
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center', fixed: 'left' },
        { title: '产品编码', dataIndex: 'productCode', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { 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: 'price', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折后售价', dataIndex: 'discountedPrice', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货数量', dataIndex: 'qty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '废品数量', dataIndex: 'celQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '入库数量', dataIndex: 'rkqty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '退货金额小计', dataIndex: 'saleReturnSubtotal', width: 120, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折扣金额', dataIndex: 'discountAmount', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '折后退货金额小计', dataIndex: 'discountedAmount', width: 150, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, { salesReturnBillSn: this.$route.params.sn })
        this.getQueryCount(params)
        return salesReturnDetailList(params).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)
            data.list[i].productCode = productCode || '--'
            data.list[i].productName = productName || '--'
            data.list[i].productOrigCode = productOrigCode || '--'
            // 退货数量和入库数量取值同一个字段，因表格使用统一字段会报错，因此重新定义
            data.list[i].rkqty = data.list[i].qty || 0
            // 折后退货金额小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
            data.list[i].saleReturnSubtotal = 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({ path: '/salesManagement/salesReturn/list', query: { closeLastOldTab: true } })
    },
    // 明细统计
    getQueryCount (params) {
      salesReturnQueryCount(params).then(res => {
        this.countData = res.data || null
      })
    },
    //  详情
    getDetail () {
      salesReturnDetail({ sn: 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
      salesReturnDetailPrint({ 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">
  .salesReturnDetail-wrap{
    .salesReturnDetail-cont{
      margin-bottom: 15px;
    }
  }
</style>
