<template>
  <a-modal
    centered
    class="inventoryCheckingDetail-modal"
    :footer="null"
    :maskClosable="false"
    title="详情"
    v-model="isShow"
    @cancel="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" id="inventoryCheckingDetail-pd-print-opts">
            <a-radio value="NEEDLE" id="inventoryCheckingDetail-pd-print-needle">针式</a-radio>
            <a-radio value="INK" id="inventoryCheckingDetail-pd-print-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="handleExport('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 v-if="productTotal">
                <div>
                  总款数： <strong>{{ (productTotal.totalCategory || productTotal.totalCategory==0) ? productTotal.totalCategory : '--' }}</strong> ，
                  总数量： <strong>{{ (productTotal.stockQty || productTotal.stockQty==0) ? productTotal.stockQty : '--' }}</strong> ，
                  <div style="display: inline-block;" v-if="$hasPermissions('M_ShowAllCost')">
                    总成本： <strong>{{ (productTotal.checkCost || productTotal.checkCost==0) ? toThousands(productTotal.checkCost) : '--' }}</strong>
                  </div>
                </div>
                <div>
                  盘盈总数量： <strong>{{ (productTotal.checkProfitQty || productTotal.checkProfitQty==0) ? productTotal.checkProfitQty : '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盘盈总成本： <strong>{{ (productTotal.checkProfitCost || productTotal.checkProfitCost==0) ? toThousands(productTotal.checkProfitCost) : '--' }}</strong>，</span>
                  盘亏总数量： <strong>{{ (productTotal.checkLossQty||productTotal.checkLossQty==0)?productTotal.checkLossQty>0?('-'+productTotal.checkLossQty):productTotal.checkLossQty: '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盘亏总成本： <strong>{{ (productTotal.checkLossCost || productTotal.checkLossCost==0) ? toThousands(productTotal.checkLossCost) : '--' }}</strong>，</span>
                  盈亏总数量： <strong>{{ (productTotal.totalCheckProfitLossQty || productTotal.totalCheckProfitLossQty==0) ? productTotal.totalCheckProfitLossQty : '--' }}</strong>，
                  <span v-if="basicInfoData&&basicInfoData.state=='FINISH'">盈亏总成本： <strong>{{ (productTotal.totalCheckProfitLossCost || productTotal.totalCheckProfitLossCost==0) ? toThousands(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="inventoryCheckingDetail-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="inventoryCheckingDetail-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="inventoryCheckingDetail-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="inventoryCheckingDetail-warehouseSn" allowClear placeholder="请选择仓库" v-model="queryParam.warehouseSn" >
                        <a-select-option v-for="item in warehouseList" :id="'inventoryCheckingDetail-warehouseSn-'+item.warehouseSn" :key="item.warehouseSn" :value="item.warehouseSn">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </template>
                <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                  <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="inventoryCheckingDetail-refresh">查询</a-button>
                  <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="inventoryCheckingDetail-reset">重置</a-button>
                  <a @click="advanced=!advanced" style="margin-left: 5px" v-if="basicInfoData&&basicInfoData.warehouseFlag=='1'" id="inventoryCheckingDetail-advanced">
                    {{ advanced ? '收起' : '展开' }}
                    <a-icon :type="advanced ? 'up' : 'down'"/>
                  </a>
                </a-col>
              </a-row>
            </a-form>
            <div style="flex-shrink: 0;margin-left: 5px;">
              <a-checkbox id="inventoryCheckingDetail-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) ? toThousands(record.checkProfitLossCost) : '--' }}</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>
    <!-- 导出选择弹框 -->
    <exportModal :openModal="exportShow" :itemData="basicInfoData" :nowType="nowType" @ok="handlePrint" @close="exportShow=false" />
  </a-modal>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdPrint } from '@/libs/JGPrint.js'
import { STable } from '@/components'
import printModal from './printModal.vue'
import exportModal from './exportModal.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, exportModal },
  mixins: [commonMixin],
  props: {
    openModal: { //  弹框显示状态
      type: Boolean,
      default: false
    },
    itemSn: { // 单据sn
      type: String || Number,
      default: ''
    }
  },
  data () {
    return {
      spinning: false,
      isShow: this.openModal, //  是否打开弹框
      disabled: false,
      advanced: false, // 展开收起
      exportShow: false, // 打开导出选项弹框
      queryParam: {
        productName: '', // 产品名称
        productCode: '', // 产品编码
        productTypeSn1: undefined, // 产品分类1
        productTypeSn2: undefined, // 产品分类2
        productTypeSn3: undefined, // 产品分类3
        warehouseSn: undefined// 仓库sn
      },
      // 加载数据方法 必须为 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, // 打印or导出
      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: {
    // 详情
    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 = []
        }
      })
    },
    // 导出弹框
    handleExport () {
      this.exportShow = true
    },
    // 打印导出
    handlePrint (type, data) {
      if (type == 'export') {
        this.exportShow = false
        this.nowType = type
        this.handleOk(data)
      } else {
        this.nowType = type
        this.openPrintModal = true
      }
    },
    // 开始打印or导出
    handleOk (objs) {
      const _this = this
      let params, type
      let url = checkWarehouseDetailPrint //  打印
      if (this.nowType == 'export') { //  导出
        url = checkWarehouseDetailExport
        params = { checkWarehouseSn: this.itemSn, ...objs }
        type = 'export'
      } else { //  打印
        params = JSON.parse(JSON.stringify(objs))
        params.printType = this.printerType
        type = params.type
        delete params.type
      }
      _this.spinning = true
      // 打印或导出
      hdPrint(this.printerType, type, url, params, '库存盘点', function () {
        _this.spinning = false
      })
    }
  },
  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>
