<template>
  <div class="storeTransferOutDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="storeTransferOutDetail-back" :style="{ padding: !outBizSn ? '16px 24px' : '0px 24px' }" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle" v-if="!outBizSn">
          <a id="storeTransferOutDetail-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <a-button
            v-if="isEdit&&$hasPermissions('B_storeCallOutEdit')"
            type="primary"
            size="small"
            style="background-color: #1890ff;margin-left: 20px;border: #1890ff;"
            id="storeTransferOutDetail-edit-btn"
            @click.stop="handleEdit">编辑</a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra" v-if="outBizSn ? $hasPermissions('B_outboundOrderDetail') : $hasPermissions('B_storeCallOutPrint')">
          <a-checkbox key="4" v-model="printCostChecked">打印成本</a-checkbox>
          <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="storeTransferOutDetail-preview-btn" :disabled="localDataSource.length==0" @click="handlePrint('preview')">打印预览</a-button>
          <a-button key="1" type="primary" id="storeTransferOutDetail-print-btn" :disabled="localDataSource.length==0" @click="handlePrint('print')">快捷打印</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="storeTransferOutDetail-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions :column="3">
              <a-descriptions-item label="调往对象名称">{{ (basicInfoData&&basicInfoData.putPersonName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="店内调出单号">{{ (basicInfoData&&basicInfoData.storeCallOutNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="财务状态">{{ (basicInfoData&&basicInfoData.settleStateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调拨类型">{{ (basicInfoData&&basicInfoData.callOutTypeName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ (basicInfoData&&basicInfoData.remarks) || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="storeTransferOutDetail-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            总款数 <strong>{{ (productTotal&&(productTotal.productTotalCategory || productTotal.productTotalCategory==0)) ? productTotal.productTotalCategory : '--' }}</strong> ，
            总数量 <strong>{{ (productTotal&&(productTotal.productTotalQty || productTotal.productTotalQty==0)) ? productTotal.productTotalQty : '--' }}</strong> ，
            总成本 <strong>{{ (productTotal&&(productTotal.productTotalCost || productTotal.productTotalCost==0)) ? '￥'+productTotal.productTotalCost : '--' }}</strong>
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ x: 995 }"
          bordered>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import { getOperationalPrecision } from '@/libs/tools.js'
import { storeCallOutDetailList, storeCallOutDetailCount, storeCallOutDetailSn, storeCallOutDetailPrint } from '@/api/storeCallOut'
export default {
  components: { STable, VSelect },
  props: {
    outBizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: 200, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '单位', dataIndex: 'productUnit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '成本价(￥)', dataIndex: 'outCost', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调出仓库', dataIndex: 'warehouseName', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调出数量', dataIndex: 'outQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '成本小计(￥)', dataIndex: 'costSubtotal', width: 115, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return storeCallOutDetailList(Object.assign(parameter, { storeCallOutSn: this.outBizSn || 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
            // 成本小计  由于数据库内小数位数为4位，页面则需显示2位。因此会做小数运算精度处理
            data.list[i].costSubtotal = getOperationalPrecision(data.list[i].outCost, data.list[i].outQty)
          }
          this.localDataSource = data.list
          this.spinning = false
          return data
        })
      },
      localDataSource: [],
      basicInfoData: null, //  基本信息
      productTotal: null, //  合计
      printerType: 'NEEDLE', //  打印机类型
      printCostChecked: true //  打印成本
    }
  },
  computed: {
    isEdit () {
      return ((this.basicInfoData && this.basicInfoData.state == 'WAIT_SUBMIT') || (this.basicInfoData && this.basicInfoData.state == 'WAIT_AUDIT')) && this.$hasPermissions('B_storeCallOutEdit')
    }
  },
  methods: {
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/storeTransferOut/list', query: { closeLastOldTab: true } })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      const _this = this
      _this.spinning = true
      storeCallOutDetailPrint({ sn: this.outBizSn || this.$route.params.sn, type: this.printerType, costFlag: this.printCostChecked ? '1' : '0' }).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="printfsod" name="printfsod" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printfsod'].focus()
        window.frames['printfsod'].print()
      }
    },
    // 基本信息
    getDetail () {
      storeCallOutDetailSn({ sn: this.outBizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
        } else {
          this.basicInfoData = null
        }
      })
    },
    // 合计
    getDetailCount () {
      storeCallOutDetailCount({ storeCallOutSn: this.outBizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
        } else {
          this.productTotal = null
        }
      })
    },
    //  编辑
    handleEdit () {
      this.$router.push({ path: `/allocationManagement/storeTransferOut/edit/${this.basicInfoData.id}/${this.basicInfoData.storeCallOutSn}` })
    }
  },
  mounted () {
    this.getDetail()
    this.getDetailCount()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (!vm.spinning) {
        vm.getDetail()
        vm.getDetailCount()
        vm.$refs.table.refresh()
      }
    })
  }
}
</script>

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