<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="2">
          <a-descriptions-item label="盘点单号" :span="2">
            {{ (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'" :span="2">{{ (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>
                <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> ，
                </div>
                <div>
                  盘盈总数量： <strong>{{ productTotal&&(productTotal.checkProfitQty || productTotal.checkProfitQty==0) ? productTotal.checkProfitQty : '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盘盈总成本： <strong>{{ productTotal&&(productTotal.checkProfitCost || productTotal.checkProfitCost==0) ? productTotal.checkProfitCost : '--' }}</strong>，</span>
                  盘亏总数量： <strong>{{ productTotal&&(productTotal.checkLossQty || productTotal.checkLossQty==0) ? productTotal.checkLossQty : '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盘亏总成本： <strong>{{ productTotal&&(productTotal.checkLossCost || productTotal.checkLossCost==0) ? productTotal.checkLossCost : '--' }}</strong>，</span>
                  盈亏总数量： <strong>{{ productTotal&&(productTotal.totalCheckProfitLossQty || productTotal.totalCheckProfitLossQty==0) ? productTotal.totalCheckProfitLossQty : '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盈亏总成本： <strong>{{ productTotal&&(productTotal.totalCheckProfitLossCost || productTotal.totalCheckProfitLossCost==0) ? productTotal.totalCheckProfitLossCost : '--' }}</strong>，</span>
                </div>
              </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">
          <div style="display: flex;justify-content: space-between;">
            <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
              <a-row :gutter="15">
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品编码" prop="productCode">
                    <a-input id="inventoryCheckMakeInventoryList-productCode" v-model.trim="queryParam.productCode" placeholder="请输入" allowClear />
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item label="产品名称" prop="productName">
                    <a-input id="inventoryCheckMakeInventoryList-productName" v-model.trim="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>
                <template v-if="advanced && (basicInfoData&&basicInfoData.warehouseFlag=='1')">
                  <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>
                </template>
                <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 @click="advanced=!advanced" style="margin-left: 5px" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'"/>
                  </a>
                </a-col>
              </a-row>
            </a-form>
            <div style="flex-shrink: 0;margin-left: 5px;"><a-checkbox v-model="isPrice"><span style="display: inline-block;margin-top: 1px;">仅显示盈亏</span></a-checkbox></div>
          </div>
        </div>
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :defaultLoadData="false"
          :scroll="{ 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>
          <!-- 盈亏成本 -->
          <template slot="checkProfitLossCost" slot-scope="text, record">
            <span :style="{ color: record.checkProfitLossCost>0?'red':record.checkProfitLossCost<0?'green':'', fontWeight: record.checkProfitLossCost!=0?'bold':'' }">{{ (record.checkProfitLossCost || record.checkProfitLossCost==0) ? '￥'+formatDecimal(Math.abs(record.checkProfitLossCost), 2) : '--' }}</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 { commonMixin } from '@/utils/mixin'
import { downloadExcel } from '@/libs/JGPrint.js'
import { STable } from '@/components'
import printModal from './printModal.vue'
import ProductType from '@/views/common/productType.js'
import { formatDecimal } from '@/libs/tools'
import { checkWarehouseDetailList, checkWarehouseDetail, checkWarehouseDetailCount, checkWarehouseDetailExport, checkWarehouseDetailPrint, checkWarehouseWarehouse } from '@/api/checkWarehouse'
export default {
  name: 'InventoryCheckingDetailModal',
  components: { STable, ProductType, printModal },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: {
      type: String || Number,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      advanced: false,
      queryParam: {
        productName: '',
        productCode: '',
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined,
        warehouseSn: undefined
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam, { checkWarehouseSn: this.itemSn })
        if (this.isPrice) {
          params.profitLossFlag = 1
        }
        return checkWarehouseDetailList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            this.getDetailCount(params)
            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
          }
          this.spinning = false
          return data
        })
      },
      basicInfoData: null, //  基本信息
      productTotal: null,
      productType: [],
      warehouseList: [], //  仓库  下拉数据
      localDataSource: [],
      isPrice: false, //  仅显示盈亏
      openPrintModal: false,
      nowType: null,
      printerType: 'NEEDLE' //  打印机类型
    }
  },
  computed: {
    columns () {
      const arr = [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '产品编码', dataIndex: 'productCode', width: '13%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '17%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '产品分类', scopedSlots: { customRender: 'productType' }, align: 'center', width: '11%' },
        { title: '单位', dataIndex: 'productUnit', width: '5%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '库存数量', dataIndex: 'stockQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盘点数量', dataIndex: 'checkQty', width: '6%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '盈亏数量', scopedSlots: { customRender: 'checkProfitLossQty' }, width: '6%', align: 'center' }
        // { title: '盈亏成本', scopedSlots: { customRender: 'checkProfitLossCost' }, width: '6%', align: 'right' }
      ]
      if (this.basicInfoData && this.basicInfoData.warehouseFlag == '1') {
        arr.splice(4, 0, { title: '仓库', dataIndex: 'warehouseName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
        arr.splice(5, 0, { title: '仓位', dataIndex: 'warehouseLocationName', width: '10%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true })
      }
      if (this.basicInfoData && this.basicInfoData.state == 'FINISH') {
        arr.push({ title: '盈亏成本', scopedSlots: { customRender: 'checkProfitLossCost' }, width: '6%', align: 'right' })
      }
      return arr
    }
  },
  methods: {
    // 保留两位小数（不四舍五入）
    formatDecimal,
    // 详情
    getDetail () {
      checkWarehouseDetail({ sn: this.itemSn }).then(res => {
        if (res.status == 200) {
          this.basicInfoData = res.data || null
        } else {
          this.basicInfoData = null
        }
      })
    },
    // 合计
    getDetailCount (params) {
      checkWarehouseDetailCount(params).then(res => {
        if (res.status == 200) {
          this.productTotal = res.data
          if (res.data && res.data.checkLossQty) {
            this.productTotal.checkLossQty = Math.abs(this.productTotal.checkLossQty || 0)
          }
        } else {
          this.productTotal = null
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.productName = ''
      this.queryParam.productCode = ''
      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') {
            downloadExcel(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()
      }
    }
  },
  watch: {
    //  父页面传过来的弹框状态
    openModal (newValue, oldValue) {
      this.isShow = newValue
    },
    //  重定义的弹框状态
    isShow (newValue, oldValue) {
      if (!newValue) {
        this.$emit('close')
        this.printerType = 'NEEDLE'
        this.$refs.table.clearTable()
        this.basicInfoData = null
      } else {
        const _this = this
        setTimeout(() => (
          _this.resetSearchForm()
        ), 300)
      }
    },
    itemSn (newValue, oldValue) {
      if (this.isShow && newValue) {
        this.isPrice = false
        this.getDetail()
        this.getWarehouseList()
      }
    },
    isPrice (newValue, oldValue) {
      this.$refs.table.refresh(true)
    }
  }
}
</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>
