<template>
  <a-card size="small" :bordered="false" class="receivedSendStorageReport-wrap">
    <div ref="tableSearch" class="table-page-search-wrapper newTableSearchName">
      <a-form-model
        layout="inline"
        ref="ruleForm"
        :rules="rules"
        :model="form">
        <a-row :gutter="15">
          <a-col :md="5" :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"
                  placeholder="开始月份"
                  @openChange="handleStartOpenChange"
                  @change="getStartDate"
                />
                <span>~</span>
                <a-month-picker
                  :disabled-date="disabledEndDate"
                  format="YYYY-MM"
                  placeholder="结束月份"
                  :open="endOpen"
                  @openChange="handleEndOpenChange"
                  @change="getEndDate"
                />
              </div>
            </a-form-model-item>
          </a-col>
          <a-col :md="5" :sm="24">
            <a-form-model-item label="产品名称">
              <a-input id="receivedSendStorageReport-name" v-model.trim="queryParam.productName" allowClear placeholder="请输入产品名称"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-model-item label="产品编码">
              <a-input id="receivedSendStorageReport-queryWord" v-model.trim="queryParam.productCode" allowClear placeholder="请输入产品编码"/>
            </a-form-model-item>
          </a-col>
          <a-col :md="5" :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="5" :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="24" :sm="24" style="margin-bottom: 10px;display:flex;align-item:center;justify-content:center;">
            <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="productInfoList-export">导出</a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <a-tabs default-active-key="1" @change="handleChange" :style="{ height: tableHeight+84.5+'px' }">
      <a-tab-pane key="1" tab="明细">
        <!-- 列表 -->
        <s-table
          class="sTable"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight-120 }"
          :defaultLoadData="false"
          bordered>
          <template slot="footer">
            <a-row>
              <a-col span="2">合计：</a-col>
              <a-col span="22">
                <a-row>
                  <a-col span="4">期初结存数量：{{ (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="4">期初结存金额：{{ (totalData && (totalData.beginAmount || totalData.beginAmount==0)) ? toThousands(totalData.beginAmount) : '--' }}</a-col>
                  <a-col span="4">本期收入数量：{{ (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="4">本期收入金额：{{ (totalData && (totalData.putAmount || totalData.putAmount==0)) ? toThousands(totalData.putAmount) : '--' }}</a-col>
                  <a-col span="4">本期发出数量：{{ (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="4">本期发出金额：{{ (totalData && (totalData.outAmount || totalData.outAmount==0)) ? toThousands(totalData.outAmount) : '--' }}</a-col>
                  <a-col span="4">本期结存数量：{{ (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="4">本期结存金额：{{ (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" :queryParam="queryParam"></gatherList>
      </a-tab-pane>
    </a-tabs>
    <!-- 导出提示框 -->
    <reportModal :visible="showExport" @close="showExport=false"></reportModal>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import ProductBrand from '@/views/common/productBrand.js'
import productTypeAll from '@/views/common/productTypeAll.js'
import { STable, VSelect } from '@/components'
import reportModal from '@/views/common/reportModal.vue'
import { queryDetailReportPage, exportDetailReport, exportGroupByProductTypeReport, queryReportCount } from '@/api/reportData'
import { hdExportExcel } from '@/libs/exportExcel'
import gatherList from './list'
import moment from 'moment'
export default {
  name: 'PriceDifferenceDetailReportList',
  mixins: [commonMixin],
  components: { STable, VSelect, ProductBrand, gatherList, productTypeAll, reportModal },
  data () {
    return {
      moment,
      queryParam: {
        beginDate: undefined,
        endDate: undefined,
        productCode: '', // 产品编码
        productName: '', // 产品名称
        productBrandSn: undefined,
        productTypeSn1: undefined,
        productTypeSn2: undefined,
        productTypeSn3: undefined
      },
      form: {
        time: []
      },
      totalData: null,
      tabVal: 1,
      rules: {
        time: [{ required: true, message: '请选择月份', trigger: 'change' }]
      },
      productType: [],
      disabled: false,
      tableHeight: 0,
      endOpen: false,
      showExport: false,
      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: '20%', 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: '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.getCount(params)
          }
          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.endMonthVal
      if (!startValue || !endValue) {
        return startValue.valueOf() > this.moment().valueOf()
      }
      return startValue.valueOf() >= endValue.valueOf()
    },
    disabledEndDate (endValue) {
      const startValue = this.startMonthVal
      if (!startValue) {
        return endValue.valueOf() > this.moment().valueOf()
      }
      return endValue.valueOf() < startValue.valueOf() || endValue.valueOf() > this.moment().valueOf()
    },
    // 开始时间
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    getStartDate (date, dateString) {
      this.form.time[0] = dateString
      this.queryParam.beginDate = 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 = this.moment(dateString).endOf('month').format('YYYY-MM-DD') + ' 59: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] : ''
    },
    handleChange (val) {
      this.tabVal = val
    },
    // 导出
    handleExport () {
      const _this = this
      const params = this.queryParam
      _this.exportLoading = true
      _this.spinning = true
      _this.showExport = true
      if (this.tabVal == 1) {
        hdExportExcel(exportDetailReport, params, '进销存明细报表', function () {
          _this.exportLoading = false
          _this.spinning = false
        })
      } else {
        hdExportExcel(exportGroupByProductTypeReport, params, '进销存明细报表', function () {
          _this.exportLoading = false
          _this.spinning = false
        })
      }
    },
    // 验证表单 type值  search查询 export导出
    testForm (type) {
      const _this = this
      if (_this.form.time.length != 2) {
        _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
      if (_this.tabVal == 1) {
        _this.$refs.table.refresh(true)
      } else {
        _this.$refs.gatherBox.resetCurForm()
      }
    },
    // 重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.queryParam.productCode = undefined
      this.queryParam.productName = undefined
      this.queryParam.productBrandSn = undefined
      this.queryParam.productTypeSn1 = undefined
      this.queryParam.productTypeSn2 = undefined
      this.queryParam.productTypeSn3 = undefined
      this.$refs.table.clearTable()
      this.productType = []
      this.$refs.table.refresh(true)
      this.$refs.gatherBox.resetCurForm()
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 200
    }
  },
  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>
