<template>
  <div>
    <a-card size="small" :bordered="false" class="receivedSendStorageReport-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
        <a-form-model
          layout="inline"
          ref="ruleForm"
          id="receivedSendStorageReport-form"
          :rules="rules"
          :model="form">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="选择周期" prop="time">
                <div class="monthBox" style="display:flex;align-item:center;">
                  <a-month-picker
                    :disabled-date="disabledStartDate"
                    format="YYYY-MM"
                    v-model="startValue"
                    placeholder="开始月份"
                    id="receivedSendStorageReport-startTime"
                    @openChange="handleStartOpenChange"
                    @change="getStartDate"
                  />
                  <span>~</span>
                  <a-month-picker
                    :disabled-date="disabledEndDate"
                    format="YYYY-MM"
                    v-model="endValue"
                    id="receivedSendStorageReport-endTime"
                    placeholder="结束月份"
                    :open="endOpen"
                    @openChange="handleEndOpenChange"
                    @change="getEndDate"
                  />
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品编码">
                <a-input id="receivedSendStorageReport-queryWord" v-model.trim="queryParam.product.code" allowClear placeholder="请输入产品编码"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品名称">
                <a-input id="receivedSendStorageReport-name" v-model.trim="queryParam.product.name" allowClear placeholder="请输入产品名称"/>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品品牌">
                <ProductBrand id="receivedSendStorageReport-productBrandSn" v-model="queryParam.productBrandSn"></ProductBrand>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品分类">
                <productTypeAll placeholder="请选择产品分类" @change="changeProductType" v-model="productType" id="receivedSendStorageReport-productType"></productTypeAll>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="仓库">
                <chooseWarehouse ref="warehouse" id="receivedSendStorageReport-warehouseSn" v-model="queryParam.warehouseSn"></chooseWarehouse>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="testForm('search')" :disabled="disabled" id="receivedSendStorageReport-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="receivedSendStorageReport-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="testForm('export')"
                :disabled="disabled"
                v-if="$hasPermissions('B_ProductPriceExoprt')"
                id="receivedSendStorageReport-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-tabs default-active-key="1" @change="handleChange">
        <a-tab-pane key="1" tab="明细">
          <!-- 列表 -->
          <s-table
            class="sTable fixPagination"
            ref="table"
            size="small"
            :rowKey="(record) => record.no"
            rowKeyName="no"
            :columns="columns"
            :data="loadData"
            :pageSize="30"
            :style="{ height: tableHeight+70+'px' }"
            :scroll="{ y: tableHeight-50 }"
            :defaultLoadData="false"
            bordered>
            <template slot="footer">
              <a-row>
                <a-col span="2">合计：</a-col>
                <a-col span="22">
                  <a-row>
                    <a-col span="3">期初结存数量：{{ (totalData && (totalData.beginQty || totalData.beginQty==0)) ? totalData.beginQty : '--' }}</a-col>
                    <!-- <a-col span="4">期初结存单价：{{ (totalData && (totalData.beginPrice || totalData.beginPrice==0)) ? toThousands(totalData.beginPrice) : '--' }}</a-col> -->
                    <a-col span="3">期初结存金额：{{ (totalData && (totalData.beginAmount || totalData.beginAmount==0)) ? toThousands(totalData.beginAmount) : '--' }}</a-col>
                    <a-col span="3">本期收入数量：{{ (totalData && (totalData.putQty || totalData.putQty==0)) ?totalData.putQty : '--' }}</a-col>
                    <!-- <a-col span="4">本期收入单价：{{ (totalData && (totalData.putPrice || totalData.putPrice==0)) ? toThousands(totalData.putPrice) : '--' }}</a-col> -->
                    <a-col span="3">本期收入金额：{{ (totalData && (totalData.putAmount || totalData.putAmount==0)) ? toThousands(totalData.putAmount) : '--' }}</a-col>
                    <a-col span="3">本期发出数量：{{ (totalData && (totalData.outQty || totalData.outQty==0)) ? totalData.outQty : '--' }}</a-col>
                    <!-- <a-col span="4">本期发出单价：{{ (totalData && (totalData.outPrice || totalData.outPrice==0)) ? toThousands(totalData.outPrice) : '--' }}</a-col> -->
                    <a-col span="3">本期发出金额：{{ (totalData && (totalData.outAmount || totalData.outAmount==0)) ? toThousands(totalData.outAmount) : '--' }}</a-col>
                    <a-col span="3">本期结存数量：{{ (totalData && (totalData.endQty || totalData.endQty==0)) ? totalData.endQty : '--' }}</a-col>
                    <!-- <a-col span="4">本期结存单价：{{ (totalData && (totalData.endPrice || totalData.endPrice==0)) ? toThousands(totalData.endPrice) : '--' }}</a-col> -->
                    <a-col span="3">本期结存金额：{{ (totalData && (totalData.endAmount || totalData.endAmount==0)) ? toThousands(totalData.endAmount) : '--' }}</a-col>
                  </a-row>
                </a-col>
              </a-row>
            </template>
          </s-table>
        </a-tab-pane>
        <a-tab-pane key="2" tab="汇总" force-render>
          <gatherList ref="gatherBox" :tableHeight="tableHeight" :totalData="totalData" :queryParam="queryParam"></gatherList>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import moment from 'moment'
// 组件
import { STable, VSelect } from '@/components'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
import reportModal from '@/views/common/reportModal.vue'
import gatherList from './list'
import chooseWarehouse from '@/views/common/chooseWarehouse'
// 接口
import { queryDetailReportPage, exportDetailReport, queryReportCount } from '@/api/reportData'
export default {
  name: 'ReceivedSendStorageReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, ProductBrand, gatherList, productTypeAll, reportModal, chooseWarehouse },
  data () {
    return {
      moment,
      disabled: false, // 查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      showExport: false, // 导出提示框
      queryParam: {
        beginDate: undefined, // 开始周期
        endDate: undefined, // 结束周期
        product: {
          name: '', // 产品名称
          code: ''// 产品编码
        },
        productBrandSn: undefined, // 产品品牌
        productTypeSn1: undefined, // 产品一级分类
        productTypeSn2: undefined, // 产品二级分类
        productTypeSn3: undefined, // 产品三级分类
        warehouseSn: undefined// 出库仓库
      },
      form: {
        time: []// 选择周期
      },
      totalData: null, // 统计数据
      tabVal: 1, // tabs  切换值
      productType: [], // 产品分类
      rules: {
        time: [{ required: true, message: '请选择月份', trigger: 'change' }]
      },
      endOpen: false, // 结束月份弹窗
      startValue: null, // 开始月份有效值
      endValue: null, // 结束月份有效值
      columns: [
        { title: '产品编码', dataIndex: 'productCode', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productName', width: '30%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '原厂编码', dataIndex: 'productOrigCode', width: '15%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '品牌', dataIndex: 'productBrandName', width: '15%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '二级分类', dataIndex: 'productTypeName2', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '三级分类', dataIndex: 'productTypeName3', width: '20%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productUnit', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '仓库', dataIndex: 'warehouseName', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '期初结存数量', dataIndex: 'beginQty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '期初结存单价', dataIndex: 'beginPrice', width: '12%', align: 'center', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '期初结存金额', dataIndex: 'beginAmount', width: '12%', align: 'center', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '本期收入数量', dataIndex: 'putQty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本期收入单价', dataIndex: 'putPrice', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '本期收入金额', dataIndex: 'putAmount', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '本期发出数量', dataIndex: 'outQty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '本期发出单价', dataIndex: 'outPrice', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '本期发出金额', dataIndex: 'outAmount', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '期末结存数量', dataIndex: 'endQty', width: '12%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '期末结存单价', dataIndex: 'endPrice', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') },
        { title: '期末结存金额', dataIndex: 'endAmount', width: '12%', align: 'right', customRender: text => ((text || text == 0) ? this.toThousands(text) : '--') }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        // 获取列表数据  有分页
        return queryDetailReportPage(params).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.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 统计
    getCount (params) {
      queryReportCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    // 选择月份限制
    disabledStartDate (startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return startValue.valueOf() > this.moment().month(this.moment().month() - 1).valueOf()
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    disabledEndDate (endValue) {
      const startValue = this.startValue
      if (!startValue) {
        return endValue.valueOf() > this.moment().month(this.moment().month() - 1).valueOf()
      }
      return endValue.valueOf() < startValue.valueOf() || endValue.valueOf() > this.moment().month(this.moment().month() - 1).valueOf()
    },
    // 开始时间
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    getStartDate (date, dateString) {
      this.form.time[0] = dateString
      this.queryParam.beginDate = date ? this.moment(dateString).startOf('month').format('YYYY-MM-DD') + ' 00:00:00' : ''
    },
    // 结束时间
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    getEndDate (date, dateString) {
      this.form.time[1] = dateString
      this.queryParam.endDate = date ? this.moment(dateString).endOf('month').format('YYYY-MM-DD') + ' 23:59:59' : ''
    },

    //  产品分类  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] : ''
    },
    // 选项卡 change
    handleChange (val) {
      this.tabVal = val
    },
    // 导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      _this.exportLoading = true
      _this.spinning = true
      _this.showExport = true
      hdExportExcel(exportDetailReport, params, '收发存报表', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 验证表单 type值  search查询 export导出
    testForm (type) {
      const _this = this
      if (!_this.form.time[0] || !_this.form.time[1]) {
        _this.$message.error('请选择月份')
        return
      }
      _this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (type == 'search') {
            _this.handleSearch()
          } else {
            _this.handleExport()
          }
        } else {
          _this.$message.error('请选择月份')
          return false
        }
      })
    },
    // 查询
    handleSearch () {
      const _this = this
      // 总计
      _this.getCount(this.queryParam)
      _this.$refs.table.refresh(true)
      _this.$refs.gatherBox.resetCurForm()
    },
    // 重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.startValue = null
      this.endValue = null
      this.time = []
      this.queryParam.beginDate = undefined
      this.queryParam.endDate = undefined
      this.queryParam.product.code = ''
      this.queryParam.product.name = ''
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.queryParam.warehouseSn = undefined
      this.$refs.table.clearTable()
      this.productType = []
      this.totalData = null
      this.$refs.gatherBox.resetTable()
    },
    // 初始化
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}

</script>

<style lang="less" scoped>
  .monthBox{
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
</style>
