<template>
  <div class="allocateBillDetail-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-page-header :ghost="false" :backIcon="false" class="allocateBillDetail-back" :style="{ padding: !outBizSn ? '16px 24px' : '0px 24px' }" >
        <!-- 自定义的二级文字标题 -->
        <template slot="subTitle" v-if="!outBizSn">
          <a id="allocateBillDetail-back-btn" href="javascript:;" @click="handleBack"><a-icon type="left" /> 返回列表</a>
          <a-button
            v-if="isEdit"
            type="primary"
            size="small"
            style="background-color: #1890ff;margin-left: 20px;border: #1890ff;"
            id="allocateBillDetail-edit-btn"
            @click.stop="handleEdit">编辑</a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="3"
            type="primary"
            class="button-warning"
            v-if="$hasPermissions('B_transferOut_detail_export')"
            id="allocateBillDetail-export-btn"
            :disabled="localDataSource.length==0"
            @click="handleExcel">导出Excel</a-button>
          <a-button
            key="2"
            type="primary"
            class="button-error"
            v-if="$hasPermissions('B_transferOut_print')"
            id="allocateBillDetail-db-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbPrint')">调拨打印</a-button>
          <a-button
            key="1"
            type="primary"
            class="button-info"
            v-if="$hasPermissions('B_transferOut_print')"
            id="allocateBillDetail-dbfl-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbflPrint')">调拨分类打印</a-button>
        </template>
      </a-page-header>
      <a-card size="small" :bordered="false" class="allocateBillDetail-cont">
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions :column="3">
              <a-descriptions-item label="调往对象">{{ (basicInfoData&&basicInfoData.targetName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调拨单号">{{ (basicInfoData&&basicInfoData.allocateNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调拨类型">{{ (basicInfoData&&basicInfoData.allocateTypeName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="起止时间">
                <span v-if="basicInfoData&&(basicInfoData.promoStartDate || basicInfoData.promoEndDate)">{{ (basicInfoData&&basicInfoData.promoStartDate) || '--' }} ~ {{ (basicInfoData&&basicInfoData.promoEndDate) || '--' }}</span>
                <span v-else>--</span>
              </a-descriptions-item>
              <a-descriptions-item label="备注">{{ (basicInfoData&&basicInfoData.remark) || '--' }}</a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </a-card>
      <a-card size="small" :bordered="false" class="allocateBillDetail-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            总数量：<strong>{{ (productTotal&&(productTotal.totalQty || productTotal.totalQty==0)) ? productTotal.totalQty : '--' }}</strong> ，
            <span v-if="$hasPermissions('B_isShowCost')">总成本（￥）：<strong>{{ (productTotal&&(productTotal.totalCost || productTotal.totalCost==0)) ? productTotal.totalCost : '--' }}</strong> ，</span>
            总售价（￥）：<strong>{{ (productTotal&&(productTotal.totalPrice || productTotal.totalPrice==0)) ? productTotal.totalPrice : '--' }}</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>
    <!-- 打印导出 -->
    <print-modal :openModal="openModal" :itemData="basicInfoData" :nowType="nowType" @ok="handleOk" @close="openModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import printModal from './printModal.vue'
import { hdExportExcel } from '@/libs/exportExcel'
import { allocateBillDetailList, allocateBillDetail, allocateBillDetailCount, allocateBillDetailPrint, allocateBillDetailExcel } from '@/api/allocateBill'
export default {
  components: { STable, VSelect, printModal },
  props: {
    outBizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return allocateBillDetailList(Object.assign(parameter, { allocateSn: 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
          }
          this.localDataSource = data.list
          this.spinning = false
          return data
        })
      },
      basicInfoData: null, //  基本信息
      productTotal: null, //  合计
      localDataSource: [],
      openModal: false,
      nowType: null
    }
  },
  computed: {
    isEdit () {
      return this.basicInfoData && ((this.basicInfoData.state == 'WAIT_SUBMIT') || (this.basicInfoData.state == 'WAIT_AUDIT') || (this.basicInfoData.state == 'AUDIT_REJECT')) && this.$hasPermissions('M_transferOut_edit')
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '27%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productEntity.origCode', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '售价', dataIndex: 'price', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '调出数量', dataIndex: 'qty', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '售价小计(￥)', dataIndex: 'totalPrice', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('B_isShowCost')) {
        arr.splice(5, 0, { title: '成本价', dataIndex: 'cost', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
        arr.splice(8, 0, { title: '成本小计(￥)', dataIndex: 'totalCost', width: '9%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } })
      }
      return arr
    }
  },
  methods: {
    //  返回列表
    handleBack () {
      this.$router.push({ path: '/allocationManagement/transferOut/list', query: { closeLastOldTab: true } })
    },
    // 基本信息
    getDetail () {
      allocateBillDetail({ sn: this.outBizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data
        } else {
          this.basicInfoData = null
        }
      })
    },
    // 合计
    getDetailCount () {
      allocateBillDetailCount({ allocateSn: 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/transferOut/edit/${this.basicInfoData.allocateSn}/${this.basicInfoData.dealerLevel}` })
    },
    // 导出
    handleExcel () {
      const _this = this
      this.spinning = true
      hdExportExcel(allocateBillDetailExcel, { allocateSn: this.outBizSn || this.$route.params.sn }, '调拨明细', function () {
        _this.spinning = false
      })
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      this.nowType = type
      this.openModal = true
    },
    handleOk (objs) {
      const _this = this
      const params = JSON.parse(JSON.stringify(objs))
      delete params.type
      _this.spinning = true
      allocateBillDetailPrint(params).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, objs.isPreview)
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printftod" name="printftod" src="' + url + '" hidden></iframe>'
      if (type == '1') { //  预览
        window.open(url)
      } else if (type == '0') { //  打印
        window.frames['printftod'].focus()
        window.frames['printftod'].print()
      }
    },
    pageInit () {
      this.$refs.table.refresh(true)
      this.getDetail()
      this.getDetailCount()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab || this.outBizSn) { // 页签刷新 或 为弹框时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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