<template>
  <div>
    <a-card size="small" :bordered="false" class="searchBoxNormal">
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="categoryList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam"
          @keyup.enter.native="handleSearch">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="统计月份" prop="months">
                <a-input id="categoryList-months" :value="queryParam.months?queryParam.months.join(','):''" placeholder="请选择月份(多选)" style="width: 100%;">
                  <span style="cursor: pointer;" slot="addonAfter" @click="openMonth">
                    点击选择
                  </span>
                </a-input>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="费用归属品类(二级)" prop="productTypeSn2">
                <ProductType
                  id="categoryList-productTypeSn2"
                  v-model="productType"
                  :changeOnSelect="false"
                  :level="2"
                  @change="changeProductType"
                  placeholder="请选择费用归属品类"></ProductType>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="categoryList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="categoryList-reset">重置</a-button>
              <a-button
                style="margin-left: 5px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_expenseCollectExportByPtype')"
                id="categoryList-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <!-- 列表 -->
    <a-card>
      <a-spin :spinning="spinning" tip="Loading...">
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :defaultLoadData="false"
          :rowKey="(record) => record.id"
          :columns="columns"
          :showPagination="false"
          :data="loadData"
          :style="{ height: tableHeight+84.5+'px' }"
          :scroll="{ y: tableHeight-30}"
          bordered>
          <template slot="footer">
            <table v-if="totalData">
              <tr>
                <th colspan="4" width="32%" style="text-align: right;">{{ totalData['PRODUCT_TYPE_NAME2'] }}汇总：</th>
                <th width="8%" style="text-align: center;"></th>
                <th v-for="item in totalMData" width="6%" style="text-align: center;">{{ toThousands(item) }}</th>
                <th width="6%" style="text-align: center;">{{ toThousands(totalData['COUNT_PRICE']) }}</th>
              </tr>
            </table>
          </template>
        </s-table>
      </a-spin>
      <!-- 导出提示框 -->
      <reportModal :visible="showExport" @close="showExport=false"></reportModal>
      <selectMonth ref="months" @ok="getDateValue"></selectMonth>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
// 组件
import { STable, VSelect } from '@/components'
import selectMonth from './selectMonth.vue'
import reportModal from '@/views/common/reportModal.vue'
import ProductType from '@/views/common/productType.js'
// 接口
import { expenseCollectReportQueryPageByProductType, expenseCollectReportQueryCountByProductType, expenseCollectReportExportByProductType } from '@/api/reportData'
export default {
  name: 'ExpenseAccountCategoryList',
  mixins: [commonMixin],
  components: { STable, VSelect, selectMonth, ProductType, reportModal },
  data () {
    return {
      spinning: false,
      showExport: false, // 导出弹窗初始值
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      tableHeight: 0, // 列表高度
      productType: [], // 产品分类
      queryParam: {
        months: undefined, // 月份
        productTypeSn2: undefined// 产品二级分类
      },
      rules: {
        'months': [{ required: true, message: '请选择月份', trigger: 'change' }],
        'productTypeSn2': [{ required: true, message: '请选择费用归属品类(二级)', trigger: 'change' }]
      },
      columns: [], // 表头数据
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const _this = this
        _this.disabled = true
        _this.spinning = true
        const paramsPage = Object.assign(parameter, this.queryParam)
        // 获取列表数据 无分页
        return expenseCollectReportQueryPageByProductType(paramsPage).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.spinning = false
          this.disabled = false
          // 统计
          this.getCount(paramsPage)
          return data
        })
      },
      totalData: null, // 统计数据
      totalMData: [] // 汇总数据
    }
  },
  methods: {
    // 获取列表表头
    getColumns () {
      const _this = this
      const arr = [
        {
          title: '单据类型',
          dataIndex: 'BILL_TYPE',
          width: '8%',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          }
        },
        {
          title: '费用类型',
          dataIndex: 'COST_TYPE_NAME',
          align: 'center',
          customRender: function (text) {
            return text || '--'
          },
          width: '8%',
          ellipsis: true
        },
        {
          title: '费用归属品牌',
          dataIndex: 'PRODUCT_BRAND_NAME',
          width: '8%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        },
        {
          title: '费用归属品类(二级)',
          dataIndex: 'PRODUCT_TYPE_NAME2',
          width: '8%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        },
        {
          title: '费用归属品类(三级)',
          dataIndex: 'PRODUCT_TYPE_NAME3',
          width: '8%',
          align: 'center',
          customRender: function (text) {
            return ((text || text == 0) ? text : '--')
          }
        }
      ]

      if (this.queryParam.months) {
        // 月份排序
        this.queryParam.months.sort((a, b) => {
          return a.replace('-', '') - b.replace('-', '')
        })
        for (let i = 0; i < this.queryParam.months.length; i++) {
          const item = this.queryParam.months[i]
          arr.push({
            title: item.replace('-', '年') + '月',
            dataIndex: 'M_' + item.replace('-', '_'),
            width: '6%',
            align: 'center',
            customRender: function (text) {
              return ((text || text == 0) ? _this.toThousands(text) : '--')
            }
          })
        }
      }
      arr.push({
        title: '总计',
        dataIndex: 'COUNT_PRICE',
        width: '6%',
        align: 'center',
        customRender: function (text) {
          return ((text || text == 0) ? _this.toThousands(text) : '--')
        }
      })
      this.columns = arr
    },
    // 选择月份
    openMonth () {
      this.$refs.months.showModal(this.queryParam.months, 'm1')
    },
    // 选择月份完成
    getDateValue (data) {
      this.queryParam.months = data
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.getColumns()
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择查询条件')
          return false
        }
      })
    },
    // 统计
    getCount (params) {
      this.totalData = null
      this.totalMData = []
      expenseCollectReportQueryCountByProductType(params).then(res => {
        this.totalData = res.data
        for (var key in res.data) {
          if (key.indexOf('M_') >= 0) {
            this.totalMData.push(res.data[key])
          }
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam = {
        months: undefined,
        productTypeSn2: undefined
      }
      this.totalData = null
      this.productType = []
      this.totalMData = []
      this.$refs.ruleForm.resetFields()
      this.$refs.table.clearTable()
      this.getColumns()
    },
    //  导出
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.showExport = true
          const params = _this.queryParam
          _this.$store.state.app.curActionPermission = 'B_expenseCollectExportByPtype'
          _this.exportLoading = true
          _this.spinning = true
          hdExportExcel(expenseCollectReportExportByProductType, params, '费用汇总报表（按品类）', function () {
            _this.exportLoading = false
            _this.spinning = false
            _this.$store.state.app.curActionPermission = ''
          })
        } else {
          return false
        }
      })
    },
    // 初始化
    pageInit () {
      this.getColumns()
      this.setTableH()
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 240
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>

<style style="less">

</style>
