<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>
          <span style="margin: 0 15px;color: #666;font-weight: bold;">单号：{{ basicInfoData&&basicInfoData.allocateNo }}</span>
          <a-button
            v-if="isEdit"
            type="link"
            class="button-default"
            id="allocateBillDetail-edit-btn"
            @click.stop="handleEdit">
            <a-icon type="edit"/>编辑
          </a-button>
          <a-button id="allocateBillDetail-showDetail-btn" type="link" class="button-default" @click="showDetail=!showDetail">
            <a-icon :type="showDetail ? 'eye-invisible' : 'eye'"/> {{ showDetail?'隐藏':'查看' }}信息
          </a-button>
        </template>
        <!-- 操作区，位于 title 行的行尾 -->
        <template slot="extra">
          <a-button
            key="4"
            type="primary"
            class="button-info"
            v-if="$hasPermissions('B_transferOut_print')"
            id="allocateBillDetail-dbPrint-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbPrint')">调拨打印</a-button>
          <a-button
            key="3"
            type="primary"
            class="button-info"
            v-if="$hasPermissions('B_transferOutType_print')"
            id="allocateBillDetail-dbflPrint-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbflPrint')">调拨分类打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="2"
            type="default"
            class="button-info"
            v-if="$hasPermissions('B_transferOut_detail_export')"
            id="allocateBillDetail-export-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbExport')">导出Excel</a-button>
          <a-button
            key="1"
            type="default"
            class="button-info"
            v-if="$hasPermissions('B_transferOutType_export')"
            id="allocateBillDetail-exportType-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('dbflExport')">调拨分类导出</a-button>
        </template>
      </a-page-header>
      <!-- 基础信息 -->
      <div ref="tableSearch" v-if="!outBizSn">
        <a-card size="small" :bordered="false" class="allocateBillDetail-cont" v-show="showDetail">
          <div style="padding: 0;" ref="basicInformation">
            <a-descriptions :column="4">
              <a-descriptions-item label="调往对象">{{ (basicInfoData&&basicInfoData.targetName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调出仓库">{{ (basicInfoData&&basicInfoData.warehouseName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="发货编号">{{ (basicInfoData&&basicInfoData.sendNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货客户名称">{{ (basicInfoData&&basicInfoData.receiverName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调拨单号">{{ (basicInfoData&&basicInfoData.allocateNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="打印状态">{{ (basicInfoData&&basicInfoData.printStateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="费用类型">
                {{ (basicInfoData&&basicInfoData.costTypeName) || '--' }}
              </a-descriptions-item>
              <a-descriptions-item label="调拨类型">
                <div>
                  <span v-if="basicInfoData&&basicInfoData.allocateSortName">{{ basicInfoData.allocateSortName || '--' }}</span>
                  <span v-if="basicInfoData&&basicInfoData.allocateTypeName">/{{ basicInfoData.allocateTypeName || '--' }}</span>
                </div>
              </a-descriptions-item>
              <a-descriptions-item label="费用归属品牌">
                {{ (basicInfoData&&basicInfoData.productBrandName) || '--' }}
              </a-descriptions-item>
              <a-descriptions-item label="费用归属品类">
                <div>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName1">{{ basicInfoData.productTypeName1 || '--' }}</span>
                  <span v-else>--</span>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName2">/{{ basicInfoData.productTypeName2 || '--' }}</span>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName3">/{{ basicInfoData.productTypeName3 || '--' }}</span>
                </div>
              </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="发货说明" :span="4">
                {{ (basicInfoData&&basicInfoData.explainInfo) || '--' }}
              </a-descriptions-item>
              <a-descriptions-item label="备注" :span="4">{{ (basicInfoData&&basicInfoData.remark) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="附件" :span="4">
                <div v-if="basicInfoData&&basicInfoData.attachmentList&&basicInfoData.attachmentList.length">
                  <a
                    target="_blank"
                    id="allocateBillDetail-attachmentList"
                    style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
                    :href="item.filePath"
                    v-for="item in basicInfoData.attachmentList"
                    :key="item.id">
                    {{ item.fileName }}
                  </a>
                </div>
                <span v-else>--</span>
              </a-descriptions-item>
            </a-descriptions>
          </div>
        </a-card>
      </div>
      <div ref="tableSearch" style="padding: 0 12px;" v-else>
        <a-collapse :activeKey="['1']">
          <a-collapse-panel key="1" header="基础信息">
            <a-descriptions :column="4">
              <a-descriptions-item label="调往对象">{{ (basicInfoData&&basicInfoData.targetName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调出仓库">{{ (basicInfoData&&basicInfoData.warehouseName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="发货编号">{{ (basicInfoData&&basicInfoData.sendNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货客户名称">{{ (basicInfoData&&basicInfoData.receiverName) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="调拨单号">{{ (basicInfoData&&basicInfoData.allocateNo) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="业务状态">{{ (basicInfoData&&basicInfoData.stateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="打印状态">{{ (basicInfoData&&basicInfoData.printStateDictValue) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="费用类型">
                {{ (basicInfoData&&basicInfoData.costTypeName) || '--' }}
              </a-descriptions-item>
              <a-descriptions-item label="调拨类型">
                <div>
                  <span v-if="basicInfoData&&basicInfoData.allocateSortName">{{ basicInfoData.allocateSortName || '--' }}</span>
                  <span v-if="basicInfoData&&basicInfoData.allocateTypeName">/{{ basicInfoData.allocateTypeName || '--' }}</span>
                </div>
              </a-descriptions-item>
              <a-descriptions-item label="费用归属品牌">
                {{ (basicInfoData&&basicInfoData.productBrandName) || '--' }}
              </a-descriptions-item>
              <a-descriptions-item label="费用归属品类">
                <div>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName1">{{ basicInfoData.productTypeName1 || '--' }}</span>
                  <span v-else>--</span>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName2">/{{ basicInfoData.productTypeName2 || '--' }}</span>
                  <span v-if="basicInfoData&&basicInfoData.productTypeName3">/{{ basicInfoData.productTypeName3 || '--' }}</span>
                </div>
              </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="备注" :span="4">{{ (basicInfoData&&basicInfoData.remark) || '--' }}</a-descriptions-item>
              <a-descriptions-item label="附件" :span="4">
                <div v-if="basicInfoData&&basicInfoData.attachmentList&&basicInfoData.attachmentList.length">
                  <a
                    target="_blank"
                    id="allocateBillDetail-attachmentList"
                    style="color: #00aaff;text-decoration: underline;margin-right: 15px;"
                    :href="item.filePath"
                    v-for="item in basicInfoData.attachmentList"
                    :key="item.id">
                    {{ item.fileName }}
                  </a>
                </div>
                <span v-else>--</span>
              </a-descriptions-item>
            </a-descriptions>
          </a-collapse-panel>
        </a-collapse>
      </div>

      <a-card size="small" :bordered="false" class="allocateBillDetail-cont">
        <!-- 总计 -->
        <div ref="countInfo">
          <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('M_transferOut_detail_costPrice')||$hasPermissions('M_tfoPrint_detail_costPrice')||$hasPermissions('M_mso_detail_costPrice')">总成本：<strong>{{ (productTotal&&(productTotal.totalCost || productTotal.totalCost==0)) ? toThousands(productTotal.totalCost) : '--' }}</strong> ；</span>
              <span v-if="$hasPermissions('M_transferOut_detail_salesPrice')||$hasPermissions('M_tfoPrint_detail_salesPrice')||$hasPermissions('M_mso_detail_salesPrice')">总售价：<strong>{{ (productTotal&&(productTotal.totalPrice || productTotal.totalPrice==0)) ? toThousands(productTotal.totalPrice) : '--' }}</strong>；</span>
            </div>
          </a-alert>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :style="{ height:outBizSn? '380px': tableHeight+70+'px' }"
          :scroll="{ y:outBizSn?380: tableHeight }"
          :defaultLoadData="false"
          bordered>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 打印导出 -->
    <print-modal
      :openModal="openModal"
      :itemData="basicInfoData"
      :nowType="nowType"
      @export="exportOk"
      @ok="handleOk"
      @close="openModal=false" />
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
// 组件
import { STable, VSelect } from '@/components'
import printModal from './printModal.vue'
import { printBase64Fun, exportExcel } from '@/libs/JGPrint.js'
// 接口
import { allocateBillDetailList, allocateBillDetail, allocateBillDetailCount, allocateBillDetailPrint, allocateBillDetailExcel } from '@/api/allocateBill'
export default {
  name: 'TransferOutDetail',
  mixins: [commonMixin],
  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 => {
          let data
          if (res.status == 200) {
            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, // dbflExport 调拨分类 dbPrint调拨
      showDetail: false, // 显示隐藏基础信息
      tableHeight: 0// 计算表格高度
    }
  },
  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 _this = this
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productEntity.code', width: '10%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: '20%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productEntity.origCode', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '调出数量', dataIndex: 'qty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('M_transferOut_detail_costPrice') || this.$hasPermissions('M_tfoPrint_detail_salesPrice') || this.$hasPermissions('M_mso_detail_costPrice')) { // 成本价权限
        arr.splice(5, 0, { title: '成本价', dataIndex: 'cost', width: '9%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(8, 0, { title: '成本小计', dataIndex: 'totalCost', width: '9%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.$hasPermissions('M_transferOut_detail_salesPrice') || this.$hasPermissions('M_tfoPrint_detail_salesPrice') || this.$hasPermissions('M_mso_detail_salesPrice')) { //  售价权限
        const ind = this.$hasPermissions('M_transferOut_detail_costPrice') || this.$hasPermissions('M_tfoPrint_detail_costPrice') ? 6 : 5
        arr.splice(ind, 0, { title: '售价', dataIndex: 'price', width: '8%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
        arr.splice(ind + 4, 0, { title: '售价小计', dataIndex: 'totalPrice', width: '9%', align: 'right', customRender: function (text) { return ((text || text == 0) ? _this.toThousands(text) : '--') } })
      }
      if (this.basicInfoData && this.basicInfoData.targetType === 'DEALER') {
        arr.splice(7, 0, { title: '价格级别', dataIndex: 'priceLevelDictValue', width: '8%', align: 'center', customRender: function (text) { return text || '--' } })
      }
      arr.push({ title: '费用归属部门', dataIndex: 'departmentName', width: '8%', align: 'center', customRender: function (text) { return text || '--' } })

      return arr
    }
  },
  watch: {
    // 基础信息显示关闭  表格高度变化
    showDetail (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    //  返回列表
    handleBack () {
      this.$router.push({ name: 'transferOutList', 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}` })
    },
    // 打印/导出
    handlePrint (type) {
      this.nowType = type
      this.openModal = true
    },
    // 导出成功
    exportOk (data) {
      const _this = this
      const filename = this.nowType == 'dbflExport' ? '调拨分类' : '调拨'
      this.spinning = true
      const params = { allocateSn: this.outBizSn || this.$route.params.sn, ...data }
      exportExcel(allocateBillDetailExcel, params, filename, function () {
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 打印成功
    handleOk (objs) {
      const _this = this
      const params = JSON.parse(JSON.stringify(objs))
      delete params.type
      _this.spinning = true
      const taskName = this.nowType == 'dbPrint' ? '调拨' : '调拨分类'
      printBase64Fun(
        allocateBillDetailPrint,
        params,
        objs.isPreview ? 'preview' : 'print',
        taskName,
        () => {
          _this.spinning = false
          _this.$store.state.app.curActionPermission = ''
        },
        {
          billType: 'ALLOCATE',
          billSn: objs.allocateSn,
          billNo: objs.allocateNo,
          printType: taskName + '打印'
        }, !this.basicInfoData.printState || this.basicInfoData.printState == 'UNABLE_PRINT' || this.basicInfoData.printState == 'CANCEL_PRINT')
    },
    // 初始化
    pageInit () {
      this.$refs.table.refresh(true)
      this.getDetail()
      this.getDetailCount()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  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()
    }
  },
  deactivated () {
    this.$store.state.app.curActionPermission = ''
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

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