<template>
  <a-modal
    centered
    class="inventoryCheckingDetail-modal"
    :footer="null"
    :maskClosable="false"
    title="详情"
    v-model="isShow"
    @cancle="isShow = false"
    width="80%">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-card size="small" :bordered="false" class="inventoryCheckingDetail-cont">
        <div class="print-cont" v-if="$hasPermissions('B_inventoryCheckingPrint')">
          <a-radio-group v-model="printerType">
            <a-radio value="NEEDLE">针式</a-radio>
            <a-radio value="INK">喷墨</a-radio>
          </a-radio-group>
          <a-button
            type="primary"
            class="button-error"
            id="inventoryCheckingDetail-pd-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('pddy')">盘点打印</a-button>
          <a-button
            type="primary"
            class="button-info"
            id="inventoryCheckingDetail-sh-print-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('shdy')">审核打印</a-button>
          <a-button
            type="primary"
            class="button-warning"
            id="inventoryCheckingDetail-export-btn"
            :disabled="localDataSource.length==0"
            @click="handlePrint('export')">导出Excel</a-button>
        </div>
        <a-descriptions size="small" :column="3">
          <a-descriptions-item label="盘点单号" :span="3">
            {{ (basicInfoData&&basicInfoData.checkWarehouseNo) || '--' }}
            <div style="display: inline-block;margin-left: 10px;">
              <a-tag color="red" v-if="basicInfoData&&basicInfoData.stateDictValue">{{ basicInfoData.stateDictValue }}</a-tag>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="盘点类型">{{ (basicInfoData&&basicInfoData.checkTypeDictValue) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="是否区分仓库" v-if="basicInfoData&&basicInfoData.checkType=='SELECT'">{{ (basicInfoData&&basicInfoData.warehouseFlagDictValue) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="盘点仓库" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">{{ (basicInfoData&&basicInfoData.warehouseNameList) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="创建人">{{ (basicInfoData&&basicInfoData.creatorName) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ (basicInfoData&&basicInfoData.createDate) || '--' }}</a-descriptions-item>
          <a-descriptions-item label="审核时间">{{ (basicInfoData&&basicInfoData.checkSuperviseTime) || '--' }}</a-descriptions-item>
        </a-descriptions>
      </a-card>
      <a-card size="small" :bordered="false" class="inventoryCheckingDetail-cont">
        <!-- 总计 -->
        <a-alert type="info" style="margin-bottom:10px">
          <div slot="message">
            <div style="display: flex;justify-content: space-between;align-items: center;">
              <div>
                总款数： <strong>{{ productTotal&&(productTotal.totalCategory || productTotal.totalCategory==0) ? productTotal.totalCategory : '--' }}</strong> ，
                总数量： <strong>{{ productTotal&&(productTotal.stockQty || productTotal.stockQty==0) ? productTotal.stockQty : '--' }}</strong> ，
                总成本： <strong>{{ productTotal&&(productTotal.checkCost || productTotal.checkCost==0) ? '￥'+productTotal.checkCost : '--' }}</strong> ，
                盘盈数量： <strong>{{ productTotal&&(productTotal.checkProfitQty || productTotal.checkProfitQty==0) ? productTotal.checkProfitQty : '--' }}</strong> ，
                盘亏数量： <strong>{{ productTotal&&(productTotal.checkLossQty || productTotal.checkLossQty==0) ? productTotal.checkLossQty : '--' }}</strong>
              </div>
              <div>
                <span style="color: red;display: inline-block;margin-right: 8px;">红色代表盘盈</span>
                <span style="color: green;">绿色代表盘亏</span>
              </div>
            </div>
          </div>
        </a-alert>
        <!-- 筛选条件 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
            <a-row :gutter="15">
              <a-col :md="7" :sm="24">
                <a-form-item label="产品编码/产品名称" prop="productName">
                  <a-input id="inventoryCheckMakeInventoryList-productName" v-model="queryParam.productName" placeholder="请输入" allowClear />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品分类">
                  <ProductType id="inventoryCheckMakeInventoryList-productType" @change="changeProductType" v-model="productType"></ProductType>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">
                <a-form-item label="仓库">
                  <a-select id="inventoryCheckMakeInventoryList-warehouseSn" allowClear placeholder="请选择仓库" v-model="queryParam.warehouseSn" >
                    <a-select-option v-for="item in warehouseList" :key="item.warehouseSn" :value="item.warehouseSn">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="5" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckMakeInventoryList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckMakeInventoryList-reset">重置</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ x: 1200, y: 450 }"
          :rowClassName="(record, index) => record.checkProfitLossQty < 0 ? 'redBg-row':''"
          bordered>
          <!-- 产品分类 -->
          <template slot="productType" slot-scope="text, record">
            <span v-if="record.productTypeName2 || record.productTypeName3">{{ record.productTypeName2 }} {{ record.productTypeName3 ? '>' : '' }} {{ record.productTypeName3 }}</span>
            <span v-else>--</span>
          </template>
          <!-- 盈亏数量 -->
          <template slot="checkProfitLossQty" slot-scope="text, record">
            <span :style="{ color: record.checkProfitLossQty>0?'red':record.checkProfitLossQty<0?'green':'', fontWeight: record.checkProfitLossQty!=0?'bold':'' }">{{ (record.checkProfitLossQty || record.checkProfitLossQty==0) ? Math.abs(record.checkProfitLossQty) : '--' }}</span>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <!-- 打印导出 -->
    <print-modal :openModal="openPrintModal" :itemData="basicInfoData" :nowType="nowType" @ok="handleOk" @close="openPrintModal=false" />
    <!-- 打印 -->
    <div id="print"></div>
  </a-modal>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'
import printModal from './printModal.vue'
import ProductType from '@/views/common/productType.js'
import { checkWarehouseDetailList, checkWarehouseDetail, checkWarehouseDetailCount, checkWarehouseDetailExport, checkWarehouseDetailPrint, checkWarehouseWarehouse } from '@/api/checkWarehouse'
export default {
  name: 'InventoryCheckingDetailModal',
  components: { STable, ProductType, printModal },
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {
      type: String || Number,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      queryParam: {
        productName: '',
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined,
        warehouseSn: undefined
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        return checkWarehouseDetailList(Object.assign(parameter, this.queryParam, { checkWarehouseSn: this.itemSn })).then(res => {
          this.getDetailCount()
          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.disabled = false
          return data
        })
      },
      basicInfoData: null, //  基本信息
      productTotal: null,
      productType: [],
      warehouseList: [], //  仓库  下拉数据
      localDataSource: [],
      openPrintModal: false,
      nowType: null,
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: 50, align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: 180, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, align: 'center', width: 140 },
        { title: '单位', dataIndex: 'productUnit', width: 60, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'stockQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盘点数量', dataIndex: 'checkQty', width: 80, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盈亏数量', scopedSlots: { customRender: 'checkProfitLossQty' }, width: 80, align: 'center' }
      ]
      if (this.basicInfoData && this.basicInfoData.warehouseFlag == '1') {
        arr.splice(4, 0, { title: '仓库', dataIndex: 'warehouseName', width: 140, align: 'center', customRender: function (text) { return text || '--' } })
        arr.splice(5, 0, { title: '仓位', dataIndex: 'warehouseLocationName', width: 140, align: 'center', customRender: function (text) { return text || '--' } })
      }
      return arr
    }
  },
  methods: {
    // 详情
    getDetail () {
      checkWarehouseDetail({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data || null
        } else {
          this.basicInfoData = null
        }
      })
    },
    // 合计
    getDetailCount () {
      checkWarehouseDetailCount(Object.assign(this.queryParam, { checkWarehouseSn: this.itemSn })).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
          this.productTotal.checkLossQty = Math.abs(this.productTotal.checkLossQty || 0)
        } else {
          this.productTotal = null
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productName = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.productType = []
      this.$refs.table.refresh(true)
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    // 仓库下拉数据
    getWarehouseList () {
      checkWarehouseWarehouse({}).then(res => {
        if (res.status == 200) {
          this.warehouseList = res.data
        } else {
          this.warehouseList = []
        }
      })
    },
    // 打印导出
    handlePrint (type) {
      if (type == 'export') {
        this.nowType = type
        this.handleOk()
      } else {
        this.nowType = type
        this.openPrintModal = true
      }
    },
    handleOk (objs) {
      const _this = this
      let params
      let url = checkWarehouseDetailPrint //  打印
      if (this.nowType == 'export') { //  导出
        url = checkWarehouseDetailExport
        params = { checkWarehouseSn: this.itemSn }
      } else { //  打印
        params = JSON.parse(JSON.stringify(objs))
        params.printType = this.printerType
        delete params.type
      }
      _this.spinning = true
      url(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 {
          if (this.nowType == 'export' || this.nowType == 'typeExport') {
            this.download(res)
          } else {
            this.print(res, objs.type)
          }
        }
      })
    },
    print (data, type) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data], { type: 'application/pdf' }))
      document.getElementById('print').innerHTML = '<iframe id="printficd" name="printficd" src="' + url + '" hidden></iframe>'
      if (type == 'preview') { //  预览
        window.open(url)
      } else if (type == 'print') { //  打印
        window.frames['printficd'].focus()
        window.frames['printficd'].print()
      }
    },
    download (data) {
      if (!data) { return }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      const a = moment().format('YYYYMMDDHHmmss')
      const fname = '库存盘点' + a
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.printerType = 'NEEDLE'
      } else {
        const _this = this
        setTimeout(() => (
          _this.$refs.table.refresh(true)
        ), 300)
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.getDetail()
        this.getWarehouseList()
      }
    }
  }
}
</script>
<style lang="less">
  .inventoryCheckingDetail-modal{
    .ant-modal-body{
      padding: 0 24px 24px;
    }
    .print-cont{
      text-align: right;
      padding: 5px 0 10px;
    }
    .redBg-row{
      background-color: #f5cdc8;
    }
  }
</style>
