<template>
  <div class="pushOrder-forOut-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&&!bizSn">
          <a href="javascript:;" @click="handleBack"><a-icon type="left"></a-icon> 返回列表</a>
        </template>
        <template slot="extra">
          <a-button
            key="4"
            type="primary"
            class="button-info"
            id="salesDetail-fhdy-print-btn"
            :disabled="localDataSource.length==0"
            v-if="$hasPermissions('B_dispatchPrint')"
            @click="handlePrint('DISPATCH_BILL')">发货打印</a-button>
          <a-button
            key="3"
            type="primary"
            class="button-info"
            id="salesDetail-fhfl-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('DISPATCH_BILL_TYPE')">发货分类打印</a-button>
          <a-divider type="vertical" />
          <a-button
            key="2"
            type="default"
            class="button-info"
            id="purchaseOrderDetail-export-btn"
            :disabled="localDataSource.length==0"
            v-if="$hasPermissions('B_dispatchExport')"
            @click="openExcelModal=true">导出Excel</a-button>
          <a-button
            key="1"
            type="default"
            class="button-info"
            id="salesDetail-fhfl-print-btn"
            :disabled="localDataSource.length==0"
            v-if="$hasPermissions('B_dispatchTypeExport')"
            @click="handleFlExport('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="销售单号">{{ detailData&&detailData.salesBillNo || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备货单号">{{ detailData&&detailData.dispatchBillNo || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货客户名称">{{ detailData&&detailData.receiverName || '--' }}</a-descriptions-item>
              <a-descriptions-item label="发货编号">{{ detailData&&detailData.sendNo || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收款方式">{{ detailData&&detailData.settleStyleSnDictValue || '--' }}</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="收货电话" v-if="detailData&&detailData.salesBillExtEntity">{{ detailData&&detailData.salesBillExtEntity&&detailData.salesBillExtEntity.consigneeTel || '--' }}</a-descriptions-item>
              <a-descriptions-item label="收货地址" :span="2" 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="业务状态">{{ detailData&&detailData.billStatusDictValue || '--' }}</a-descriptions-item>
              <a-descriptions-item label="备注">{{ detailData&&detailData.remarks || '--' }}</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>；
            <span v-if="$hasPermissions('B_dispatchDetail_salesPrice')">本次下推金额：<strong>{{ detailData&&(detailData.totalAmount || detailData.totalAmount==0) ? toThousands(detailData.totalAmount) : '--' }}</strong>；</span>
            <span v-if="$route.params.type!='stockOut'&&$hasPermissions('B_dispatchDetail_cityPrice')">
              本次下推市级价金额：<strong>{{ detailData&&(detailData.totalCityAmount || detailData.totalCityAmount==0) ? toThousands(detailData.totalCityAmount) : '--' }}</strong>；
            </span>
          </div>
        </a-alert>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.no"
          rowKeyName="no"
          :columns="($route.params.type=='stockOut' || outBizSubSn) ? outColumns : columns"
          :data="loadData"
          :scroll="{ y: 500 }"
          :defaultLoadData="false"
          bordered>
          <!-- 产品编码 -->
          <template slot="productCode" slot-scope="text, record">
            <span>{{ text }}</span>
            <a-badge count="促" v-if="record.promotionFlag&&record.promotionFlag.indexOf('GIFT')>=0" :number-style="{ backgroundColor: '#52c41a', zoom:'80%' }"></a-badge>
            <a-badge count="特" v-if="record.promotionFlag&&record.promotionFlag.indexOf('DISCOUNT')>=0" :number-style="{ backgroundColor: '#faad14', zoom:'80%' }"></a-badge>
          </template>
          <!-- 销售价 -->
          <template slot="price" slot-scope="text, record">
            {{ toThousands(text) }}
            <span v-if="record.promotionFlag&&(record.promotionFlag.indexOf('GIFT')>=0||record.promotionFlag.indexOf('DISCOUNT')>=0)" title="原价">({{ toThousands(record.origPrice) }})</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 发货分类打印 -->
    <sendTypeModal
      ref="typePrint"
      :hasNoPrint="hasNoPrint"
      :nowType="nowType"
      :openModal="openModal"
      @ok="handlePrintOk"
      @close="openModal=false" />
    <!-- 导出Excel -->
    <export-excel-modal :openModal="openExcelModal" :itemData="detailData" @ok="handleExcelOk" @close="openExcelModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import sendTypeModal from './sendTypeModal.vue'
import exportExcelModal from './exportExcelModal.vue'
import { printBase64Fun, exportExcel } from '@/libs/JGPrint.js'
import { dispatchDetaillListForOut, dispatchFindBySn, dispatchDetailPrint, dispatchDetailExcel } from '@/api/dispatch'
export default {
  name: 'DetailForOut',
  mixins: [commonMixin],
  components: { STable, VSelect, sendTypeModal, exportExcelModal },
  props: {
    outBizSubSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    },
    bizSn: { //  有值则为弹框，无值则为页面
      type: [Number, String],
      default: ''
    }
  },
  data () {
    return {
      disabled: false,
      spinning: false,
      outColumns: [
        { title: '序号', dataIndex: 'no', width: '6%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '25%', scopedSlots: { customRender: 'productCode' }, align: 'left' },
        { title: '产品名称', dataIndex: 'productName', width: '33%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '20%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productOrigUnit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '本次出库数', dataIndex: 'qty', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return dispatchDetaillListForOut(Object.assign(parameter, { dispatchBillSn: this.outBizSubSn || this.bizSn || 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
              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: '', //  当前打印类型
      openExcelModal: false, // 导出弹框
      fromRouter: null, // 页面来源
      nowType: 'print' // 操作类型
    }
  },
  computed: {
    // 是否可打印
    hasNoPrint () {
      return this.detailData && (this.detailData.printStatus == 'UNABLE_PRINT' || this.detailData.printStatus == 'CANCEL_PRINT')
    },
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '19%', scopedSlots: { customRender: 'productCode' }, align: 'left' },
        { title: '产品名称', dataIndex: 'productName', width: '10%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '19%', align: 'left', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productOrigUnit', width: '6%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '销售价格', dataIndex: 'price', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        // { title: '市级销售价格', dataIndex: 'cityPrice', width: '10%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '销售数量', dataIndex: 'salesQty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本次下推数', dataIndex: 'qty', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
        // { title: '本次下推金额', dataIndex: 'totalAmount', width: '8%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } }
      ]
      if (this.$hasPermissions('B_dispatchDetail_salesPrice')) { //  售价权限
        arr.splice(5, 0, { title: '销售价格', dataIndex: 'price', width: '8%', align: 'right', scopedSlots: { customRender: 'price' } })
        arr.splice(9, 0, { title: '本次下推金额', dataIndex: 'totalAmount', width: '8%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      if (this.$hasPermissions('B_dispatchDetail_cityPrice')) { //  市级权限
        arr.splice(6, 0, { title: '市级销售价格', dataIndex: 'cityPrice', width: '10%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') })
      }
      return arr
    }
  },
  methods: {
    //  返回
    handleBack () {
      this.$router.push({ name: 'pushOrderManagementList' })
    },
    //  详情
    getDetail () {
      dispatchFindBySn({ dispatchBillSn: this.outBizSubSn || this.bizSn || this.$route.params.sn }).then(res => {
        if (res.status == 200) {
          this.detailData = res.data
        } else {
          this.detailData = null
        }
      })
    },
    // 导出Excel
    handleExcelOk (priceType, data, fileName) {
      const _this = this
      const params = {
        dispatchBillSn: this.outBizSubSn || this.bizSn || this.$route.params.sn,
        printType: priceType,
        ...data
      }
      this.spinning = true
      exportExcel(dispatchDetailExcel, params, fileName, function () {
        _this.spinning = false
        _this.$store.state.app.curActionPermission = ''
      })
    },
    // 发货分类导出
    handleFlExport () {
      this.openModal = true
      this.nowType = 'export'
      this.$refs.typePrint.setData(this.detailData, this.outBizSubSn || this.bizSn || this.$route.params.sn)
    },
    // 打印预览/快捷打印
    handlePrint (type) {
      this.nowPrintType = type
      if (type == 'DISPATCH_BILL') { // 发货打印
        const params = {
          dispatchBillSn: this.detailData.dispatchBillSn,
          dispatchBillNo: this.detailData.dispatchBillNo
        }
        this.$store.state.app.curActionPermission = 'B_dispatchPrint'
        this.handlePrintOk(params, '发货', 'preview')
      } else if (type == 'DISPATCH_BILL_TYPE') { // 发货分类打印
        this.openModal = true
        this.nowType = 'print'
        this.$refs.typePrint.setData(this.detailData, this.outBizSubSn || this.bizSn || this.$route.params.sn)
      }
    },
    // 发货分类打印,导出
    handlePrintOk (obj, taskName, type) {
      const _this = this
      const params = {
        type: this.nowPrintType,
        dispatchBillSn: this.outBizSubSn || this.bizSn || this.$route.params.sn
      }
      // 打印
      if (type != 'export') {
        _this.spinning = true

        // 货位编号
        if (obj.orderBy) {
          params.type = params.type + '_STACK_PLACE'
        }
        // 原厂编码
        if (obj.origCode == 1) {
          params.type = params.type + '_ORIG_CODE'
        }
        // 装箱号
        if (obj.packNo == 1) {
          params.type = params.type + '_PACK_NUM'
        }
        printBase64Fun(
          dispatchDetailPrint,
          Object.assign(params, obj || {}),
          type,
          taskName,
          () => {
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          },
          {
            billType: 'DISPATCH',
            billSn: obj.dispatchBillSn,
            billNo: obj.dispatchBillNo,
            printType: taskName + '打印'
          }, this.hasNoPrint)
      } else {
        this.handleExcelOk('DISPATCH_BILL_TYPE', obj, taskName)
      }
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab || this.outBizSubSn || this.bizSn) { // 页签刷新 或 为弹框时调用
      this.$refs.table.refresh(true)
      this.getDetail()
    }
  },
  activated () {
    // 如果是新页签打开或者进入新的子页（例：存在列表第2条数据编辑页页签时再打开第4条数据的编辑页），则重置当前页面
    if (this.$store.state.app.isNewTab || !this.$store.state.app.isNewSubTab) {
      this.$refs.table.refresh(true)
      this.getDetail()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.fromRouter = from
    })
  }
}
</script>

<style lang="less">
  .pushOrder-forOut-wrap{
    .ant-card-body:first-child{
      padding-bottom: 0;
    }
    .footer-cont{
      margin-top: 5px;
      text-align: center;
    }
  }
</style>
