<template>
  <div>
    <a-spin :spinning="spinning" tip="Loading...">
      <a-card size="small" class="card-table">
        <!-- 搜索条件 -->
        <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"
                    :allowClear="false"
                    @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="tableData.length==0"
                  v-if="$hasPermissions('B_National_Sales_Daily_Export')&&activeKey==0
                    ||$hasPermissions('B_Project_Sales_Daily_Export')&&activeKey==1
                    ||$hasPermissions('B_Project_Sales_Daily_Export_2')&&activeKey==2
                    ||$hasPermissions('M_Regional_Sales_Daily_Export')&&activeKey==3"
                  :loading="exportLoading"
                  id="dayReportList-export">导出</a-button>
              </a-col>
            </a-row>
          </a-form-model>
        </div>
        <!-- 列表 -->
        <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 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: { 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.tableData = []
      this.totalNums = 0
      this.totalNums = []
    },
    // 导出表格excel，dom 表格对象，title 导出表格名称
    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)
      // console.log(ws)
      // 设置样式
      Object.keys(ws).forEach(cell => {
        if (cell[0] !== '!') {
          // 设置表头样式
          if (cell === 'A1') {
            ws[cell].s = {
              font: { bold: true, color: { rgb: 'FFFFFF' } },
              fill: { fgColor: { rgb: '4472C4' } },
              alignment: { horizontal: 'center' }
            }
          } else {
            ws[cell].s = {
              alignment: {
                horizontal: 'center',
                vertical: 'center'
              }
            }
          }
        }
      })
      // 设置百分比格式
      // 表格0
      if (this.activeKey == 0) {
        const ri = [6, 11, 20, 23]
        this.columns.forEach((item, i) => {
          if (i > 1) {
            const cols = zim[i]
            ri.forEach((row, j) => {
              const a = ws[cols + row]
              if (a) {
                a.v = Number(a.v * 100).toFixed(2) + '%' // 设置单元格格式为百分比
                a.t = 's'
              }
            })
          }
        })
      }
      // 表格1表格2
      if (this.activeKey == 1 || this.activeKey == 2) {
        const cols = zim[this.columns.length - 1]
        Array(this.totalNums).fill().forEach((item, i) => {
          const a = ws[cols + (i + 3)]
          console.log(a)
          if (a) {
            a.v = Number(a.v * 100).toFixed(2) + '%' // 设置单元格格式为百分比
            a.t = 's'
          }
        })
      }
      // 表格3
      if (this.activeKey == 3) {
        const ci = [6, 8]
        ci.forEach((row) => {
          const cols = zim[row]
          Array(this.totalNums).fill().forEach((item, i) => {
            const a = ws[cols + (i + 4)]
            if (a) {
              a.v = Number(a.v * 100).toFixed(2) + '%' // 设置单元格格式为百分比
              a.t = 's'
            }
          })
        })
      }
      // 4. 设置列宽
      ws['!cols'] = Array(this.columns.length).fill().map(() => ({ wch: this.activeKey == 3 ? 15 : 35 }))
      const timeStr = moment().format('YYYYMMDDHHmmss')
      // 创建工作簿并导出
      var wb = XLSX.utils.book_new()
      // 5. 写入文件
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
      XLSX.writeFile(wb, this.queryParam.month.split('-')[1] + '月' + title + '-' + timeStr + '.xlsx')
    },
    //  点击导出
    handleExport () {
      const excelTitle = this.tabsList.find(item => item.id == this.activeKey)
      if (this.$refs.table0 && this.activeKey == 0) {
        this.totalNums = this.$refs.table0.list.length
        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.totalNums = this.$refs.table2.list.length
        this.exportTable(this.$refs.table2.getTable(), excelTitle.name)
      } else if (this.$refs.table3 && this.activeKey == 3) {
        this.totalNums = this.$refs.table3.list.length
        this.exportTable(this.$refs.table3.getTable(), excelTitle.name)
      }
    },
    // 获取表格数据
    async getTableData () {
      const reportType = ['COUNTRY_SALES_DAY', 'DailyPL', 'DailyPLJL', 'AREA_SALES_DAY'][this.activeKey]
      const reportDate = this.queryParam.month + '-01 00:00:00'
      this.nowDate = moment().format('DD日HH点mm分')
      this.spinning = true
      const data = await salesReportDailyList({ reportType, reportDate }).then(res => res.data)
      if (data && data.length) {
        this.tableData = data
        // 全国销售日报
        if (this.activeKey == 0) {
          this.columns = ['', '']
          data.forEach(item => {
            this.columns.push(item.subareaName)
          })
        }
        // 项目销售日报1
        if (this.activeKey == 1) {
          this.columns = this.getColumns()
        }
        // 项目销售日报2
        if (this.activeKey == 2) {
          this.columns = [1, 2, 3, 4, 5]
        }
        // 分区销售报表
        if (this.activeKey == 3 && this.$refs.table3) {
          this.columns = this.$refs.table3.columns
        }
        // 初始化页面
        this.$nextTick(() => {
          if (this.$refs['table' + this.activeKey]) {
            this.$refs['table' + this.activeKey].pageInit()
          }
        })
      } else {
        this.tableData = []
      }
      this.spinning = false
    },
    // 项目销售日报1列数据
    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 (activeKey) {
      this.activeKey = activeKey
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  }
}
</script>
<style lang="less" scoped>
.card-table{
  height: calc(100vh - 140px);
  overflow: auto;
}
</style>
