<template>
  <div class="salesDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="salesDetail-cont" :style="{ padding: !outBizSubSn ? '16px 24px' : '0px 24px' }">
        <template slot="subTitle" v-if="!outBizSubSn">
          <a href="javascript:;" @click="handleBack"><a-icon type="left"></a-icon> 返回列表</a>
        </template>
        <template slot="extra" v-if="$hasPermissions('B_dispatchPrint')">
          <a-button
            key="4"
            type="primary"
            class="button-error"
            id="salesDetail-xs-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('SALES_BILL')">销售打印</a-button>
          <a-button
            key="3"
            type="primary"
            class="button-info"
            id="salesDetail-xsfl-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('SALES_BILL_TYPE')">销售分类打印</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-success"
            id="salesDetail-fhdy-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('DISPATCH_BILL')">发货打印</a-button>
          <a-button
            key="1"
            type="primary"
            class="button-warning"
            id="salesDetail-fhfl-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('DISPATCH_BILL_TYPE')">发货分类打印</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 || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货人" v-if="detailData&&detailData.salesBillExtEntity">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleSnDictValue || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货地址" :span="3" v-if="detailData&&detailData.salesBillExtEntity">
                {{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.shippingAddrProvinceName || '' }}
                {{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.shippingAddrCityName || '' }}
                {{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.shippingAddrCountyName || '' }}
                {{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.shippingAddr || '' }}
              </a-descriptions-item>
              <a-descriptions-item label="收货电话" v-if="detailData&&detailData.salesBillExtEntity">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeTel || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ detailData&&detailData.remarks || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ detailData&&detailData.billStatusDictValue || '--' }}</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;" v-if="detailData!=null">
          <div slot="message">
            <span v-if="$route.params.type!='stockOut'">
              总销售数量：<strong>{{ detailData&&(detailData.totalSalesQty || detailData.totalSalesQty==0) ? detailData.totalSalesQty : '--' }}</strong>；
            </span>
            本次下推数量：<strong>{{ detailData&&(detailData.totalQty || detailData.totalQty==0) ? detailData.totalQty : '--' }}</strong>；
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="($route.params.type=='stockOut' || outBizSubSn) ? outColumns : columns"
          :data="loadData"
          :scroll="{ x: 1070, y: 500 }"
          bordered>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <a-badge count="促" v-if="record.promotionFlag == 1">
              <div style="padding-right: 15px;">{{ text }}</div>
            </a-badge>
            <span v-else>{{ text }}</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 分类打印 -->
    <choose-type-modal :openModal="openModal" :outBizSubSn="outBizSubSn" @ok="handleOk" @close="openModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import chooseTypeModal from './chooseTypeModal.vue'
import { dispatchDetaillList, dispatchFindBySn, dispatchDetailPrint } from '@/api/dispatch'
export default {
  name: 'SalesDetail',
  components: { STable, VSelect, chooseTypeModal },
  props: {
    outBizSubSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      disabled: false,
      spinning: false,
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: 220, scopedSlots: { customRender: 'productCode' }, align: 'center' },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productOrigUnit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '销售数量', dataIndex: 'salesQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次下推数', dataIndex: 'qty', width: 130, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      outColumns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: 220, scopedSlots: { customRender: 'productCode' }, align: 'center' },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productOrigUnit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '本次出库数', dataIndex: 'qty', width: 130, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return dispatchDetaillList(Object.assign(parameter, { dispatchBillSn: this.outBizSubSn || 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 == ' ' ? '--' : productOrigCode
            data.list[i].productOrigUnit = productOrigUnit || '--'
          }
          this.localDataSource = data.list
          this.disabled = false
          return data
        })
      },
      detailData: null, //  详情数据
      openModal: false,
      localDataSource: [],
      nowPrintType: '' //  当前打印类型
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ path: '/salesManagement/pushOrderManagement/list', query: { closeLastOldTab: true } })
    },
    //  详情
    getDetail () {
      dispatchFindBySn({ dispatchBillSn: this.outBizSubSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        } else {
          this.detailData = null
        }
      })
    },
    // 分类选择
    handleOk (obj) {
      this.requestFun(obj)
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      this.nowPrintType = type
      if (type == 'SALES_BILL' || type == 'DISPATCH_BILL') { //  销售打印/发货打印
        this.requestFun()
      } else if (type == 'SALES_BILL_TYPE' || type == 'DISPATCH_BILL_TYPE') { //  销售分类打印/发货分类打印
        this.openModal = true
      }
    },
    requestFun (obj) {
      const _this = this
      const params = {
        type: this.nowPrintType,
        dispatchBillSn: this.outBizSubSn || this.$route.params.sn
      }
      _this.spinning = true
      dispatchDetailPrint(Object.assign(params, obj || {})).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)
        }
      })
    },
    print (data) {
      this.spinLoading = false
      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>'
      window.frames['printf'].focus()
      window.frames['printf'].print()
    }
  },
  mounted () {
    this.getDetail()
  }
}
</script>

<style lang="less">
  .salesDetail-wrap{
    .salesDetail-cont{
      margin-bottom: 10px;
    }
    .footer-cont{
      margin-top: 5px;
      text-align: center;
    }
  }
</style>
