<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 选项卡切换 -->
      <a-tabs v-model="activeKey" @change="callback" :tabBarStyle="{'background':'#fff'}">
        <a-tab-pane :key="item.id" :tab="item.name" v-for="item in tabsList">
        </a-tab-pane>
      </a-tabs>
      <a-card size="small">
        <!-- 搜索条件 -->
        <div class="table-page-search-wrapper newTableSearchName" ref="tableSearch">
          <a-form-model
            id="dayReportList-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="month">
                  <a-month-picker
                    placeholder="请选择月份"
                    locale="zh-cn"
                    id="dayReportList-month"
                    v-model="queryParam.month"
                    @change="onChange"
                    :disabled-date="disabledDate"
                    style="width: 100%;"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="handleSearch" :disabled="disabled" id="dayReportList-refresh">查询</a-button>
                <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="dayReportList-reset">重置</a-button>
                <a-button
                  style="margin-left: 5px"
                  type="primary"
                  class="button-warning"
                  @click="handleExport"
                  :disabled="disabled"
                  :loading="exportLoading"
                  id="dayReportList-export">导出</a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
      </a-card>
      <!-- 列表 -->
      <a-card size="small" style="margin-top:4px!important">
        <table0
          v-if="activeKey == 0"
          ref="table0"
          :month="queryParam.month"
          :columns="columns"
          :tableData="tableData"
          :nowDate="nowDate"
        ></table0>
        <table1
          v-if="activeKey == 1"
          ref="table1"
          :month="queryParam.month"
          :columns="columns"
          :tableData="tableData"
          :nowDate="nowDate"
        ></table1>
        <table2
          v-if="activeKey == 2"
          ref="table2"
          :month="queryParam.month"
          :columns="columns"
          :tableData="tableData"
          :nowDate="nowDate"
        ></table2>
        <table3
          v-if="activeKey == 3"
          ref="table3"
          :month="queryParam.month"
          :columns="columns"
          :tableData="tableData"
          :nowDate="nowDate"
        ></table3>
      </a-card>
    </a-spin>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import XLSX from 'xlsx-js-style'
// 组件
import rangeDate from '@/views/common/rangeDate.vue'
import moment from 'moment'
import table0 from './table0'
import table1 from './table1'
import table2 from './table2'
import table3 from './table3'
// 接口
import { salesReportDailyList } from '@/api/reportData.js'
export default {
  name: 'RegionTypeSalesReportList',
  mixins: [commonMixin],
  components: { rangeDate, table0, table1, table2, table3 },
  data () {
    return {
      spinning: false,
      activeKey: 0, // 切换显示页面值 0 各分区品类实售明细 1各区域品类实售明细
      advanced: true, // 高级搜索 展开/关闭
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false, // 导出按钮加载状态
      tableHeight: 0, // 表格高度
      tabsList: [{ id: 0, name: '全国销售日报' }, { id: 1, name: '项目销售日报1' }, { id: 2, name: '项目销售日报2' }, { id: 3, name: '分区销售日报' }], // tab切换data
      columns: [], // 表头数据
      tableData: [], // 表格数据
      totalNums: 0, // 总条数
      // 查询参数
      queryParam: {
        month: moment().format('YYYY-MM') // 月份默认值
      },
      rules: {
        'month': [{ required: true, message: '请选择月份', trigger: 'change' }]
      },
      nowDate: ''
    }
  },
  methods: {
    // 月份 change
    onChange (date, dateString) {
      this.queryParam.month = dateString
    },
    // 月份选择范围
    disabledDate (current) {
      return current && current > moment().endOf('day')
    },
    // tabs切换  change时间
    callback (key) {
      this.activeKey = key
      const _this = this
      _this.$nextTick(() => {
        this.resetSearchForm()
      })
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.getTableData()
        } else {
          _this.$message.error('请选择月份')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.$refs.ruleForm.resetFields()
      this.queryParam.time = []
      this.$refs.rangeDate.resetDate(this.queryParam.time)
      this.tableData = []
    },
    exportTable (dom, title) {
      const zim = 'A、B、C、D、E、F、G、H、I、J、K、L、M、N、O、P、Q、R、S、T、U、V、W、X、Y、Z‌'.split('、')
      var ws = XLSX.utils.table_to_sheet(dom)
      var wb = XLSX.utils.book_new()
      console.log(ws)
      // 设置样式
      Object.keys(ws).forEach(cell => {
        if (cell[0] !== '!') {
          ws[cell].s = {
            alignment: {
              horizontal: 'center',
              vertical: 'center'
            }
          }
        }
      })
      // 表格1
      if (this.activeKey == 1) {
        const cols = zim[this.columns.length - 1]
        Array(this.totalNums).fill().forEach((item, i) => {
          const a = ws[cols + (i + 2)]
          console.log(cols + (i + 2))
          if (a) {
            a.z = (a.v * 100) + '%' // 设置单元格格式为百分比
          }
        })
      }
      // 4. 设置列宽
      ws['!cols'] = Array(this.columns.length).fill().map(() => ({ wch: 35 }))

      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      XLSX.writeFile(wb, this.queryParam.month + title + '.xlsx')
    },
    //  导出
    handleExport () {
      const excelTitle = this.tabsList.find(item => item.id == this.activeKey)
      if (this.$refs.table0 && this.activeKey == 0) {
        this.exportTable(this.$refs.table0.getTable(), excelTitle.name)
      } else if (this.$refs.table1 && this.activeKey == 1) {
        this.totalNums = this.$refs.table1.list.length
        this.exportTable(this.$refs.table1.getTable(), excelTitle.name)
      } else if (this.$refs.table2 && this.activeKey == 2) {
        this.exportTable(this.$refs.table2.getTable(), excelTitle.name)
      } else if (this.$refs.table3 && this.activeKey == 3) {
        this.exportTable(this.$refs.table3.getTable(), excelTitle.name)
      }
    },
    // 获取表格数据
    async getTableData () {
      const url = [salesReportDailyList, salesReportDailyList, salesReportDailyList, salesReportDailyList]
      const reportType = ['DailyPL', 'DailyPL', 'DailyPL', 'DailyPL'][this.activeKey]
      const reportDate = this.queryParam.month + '-01 00:00:00'
      this.nowDate = moment().format('DD日HH点mm分')
      this.spinning = true
      const data = await url[this.activeKey]({ reportType, reportDate }).then(res => res.data)
      if (data) {
        this.tableData = data
        this.columns = this.getColumns()
        this.spinning = false
      }
    },
    getColumns () {
      const row = this.tableData[0]
      const ret = []
      if (row) {
        row.detailList[0].forEach(item => {
          ret.push(item)
        })
        ret.push(row.bymb)
        ret.push(row.wcl)
      }
      return ret
    },
    // 初始化
    pageInit () {
      this.activeKey = 0
      this.tableData = []
    }
  },
  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 lang="less" scoped>

</style>
