<template>
  <div>
    <a-card size="small" :bordered="false" class="provinceFeeList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="provinceFeeList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :rules="rules"
          :model="queryParam">
          <a-row :gutter="15" type="flex">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="月份" prop="beginDate">
                <a-month-picker
                  id="provinceFeeList-monthBox"
                  class="monthBox"
                  :disabled-date="disabledDate"
                  v-model="monthVal"
                  placeholder="请选择月份"
                  @change="onChangeMonth" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="地区">
                <Area id="provinceFeeList-areaList" v-model="queryParam.provinceSn" placeholder="请选择省份"></Area>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="所在区域">
                <subarea id="provinceFeeList-subarea" ref="subarea" @change="subareaChange"></subarea>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="区域负责人">
                <BizUser id="provinceFeeList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="是否包含特价">
                <v-select
                  v-model="queryParam.discountFlag"
                  ref="discountFlag"
                  id="customerFeeList-discountFlag"
                  code="FLAG"
                  placeholder="请选择是否包含特价"
                ></v-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="新/老客户">
                <a-select id="customerFeeList-dealerNewFlag" v-model="queryParam.dealerNewFlag" placeholder="请选择" allowClear>
                  <a-select-option value="1">新客户</a-select-option>
                  <a-select-option value="0">老客户</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="provinceFeeList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="provinceFeeList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_promotionFeeExport')"
                id="provinceFeeList-export">导出</a-button>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <!-- 列表 -->
        <s-table
          class="sTable fixPagination"
          ref="table"
          size="small"
          :rowKey="(record) => record.id"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :scroll="{x:2200, y: tableHeight}"
          :defaultLoadData="false"
          :showPagination="false"
          bordered>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import moment from 'moment'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import Area from '@/views/common/area.js'
import BizUser from '@/views/common/bizUser.js'
import customerService from '@/views/common/customerService.vue'
// 接口
import { promoProvinceList, promoProvinceTableTitle, promoProvinceExport } from '@/api/reportData'
export default {
  name: 'ProvinceFeeList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, Area, BizUser, customerService },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      //  查询条件
      monthVal: moment().format('YYYY-MM'), // 初始化月份值
      queryParam: {
        beginDate: moment().startOf('month').format('YYYY-MM-DD') + ' 00:00:00', // 月份开始时间
        endDate: moment().endOf('month').format('YYYY-MM-DD') + ' 23:59:59', // 月份结束时间
        provinceSn: undefined, // 省
        discountFlag: '0', // 是否包含特价
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '', // 分区
          bizUserSn: undefined// 区域负责人
        },
        dealerNewFlag: undefined
      },
      countLabel: null, // 统计名称合集
      totalData: null, // 统计数据
      columns: [], // 表格列
      rules: {
        'beginDate': [{ required: true, message: '请选择查询月份', trigger: 'change' }]
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        const params = Object.assign(parameter, this.queryParam)
        // 获取列表数据  有分页
        return promoProvinceList(params).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            // 计算表格序号
            for (var i = 0; i < data.length; i++) {
              data[i].id = i + 1
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      }
    }
  },
  methods: {
    // 选择月份  禁用选择当月以后日期
    disabledDate (current) {
      return current && current >= moment().endOf('day')
    },
    // 选择月份 change
    onChangeMonth (date, dateString) {
      this.monthVal = dateString
      if (date && dateString != '') {
        this.queryParam.beginDate = this.getMonthRange(dateString).firstDay
        this.queryParam.endDate = this.getMonthRange(dateString).lastDay
      } else {
        this.queryParam.beginDate = undefined
        this.queryParam.endDate = undefined
      }
    },
    // 获取指定月份   第一天和最后一天
    getMonthRange (targetMonth) {
      // 获取指定月第一天（格式化为 YYYY-MM-DD）
      const firstDay = moment(targetMonth).startOf('month').format('YYYY-MM-DD') + ' 00:00:00'
      // 获取指定月最后一天（格式化为 YYYY-MM-DD）
      const lastDay = moment(targetMonth).endOf('month').format('YYYY-MM-DD') + ' 23:59:59'
      return { firstDay, lastDay }
    },
    // 获取表头
    async getTableTitle () {
      const _this = this
      const tableTitle = await promoProvinceTableTitle().then(res => res.data)
      this.columns = tableTitle.list
      this.countLabel = tableTitle.count
      this.columns.map(item => {
        item.titleNum = item.title
        let mw = 20
        if (item.customRender == 'amount') {
          mw = 15
          if (item.colour && item.colour === 'red') {
            item.title = <span style="color:red;">{item.titleNum}</span>
            item.customRender = (text) => { return <span style="color:red;">{(text || text == 0) ? _this.toThousands(text) : '--'}</span> }
          } else {
            item.customRender = function (text) { return (text || text == 0) ? _this.toThousands(text) : '--' }
          }
        } else {
          item.customRender = function (text) { return text || '--' }
        }
        const w = item.titleNum.length * mw
        const tw = w <= 80 ? mw * 5 : w
        item.width = tw + 'px'
        this.tableWidth = this.tableWidth + tw
      })
      this.resetSearchForm()
    },
    // 查询
    handleSearch () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.$refs.table.refresh(true)
        } else {
          _this.$message.error('请选择查询月份')
          return false
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.dealerEntity.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.dealerEntity.citySn = val[1] ? val[1] : undefined
      this.queryParam.dealerEntity.districtSn = val[2] ? val[2] : undefined
    },
    // 区域分区  change
    subareaChange (val) {
      this.queryParam.subareaArea.subareaSn = val[0] ? val[0] : ''
      this.queryParam.subareaArea.subareaAreaSn = val[1] ? val[1] : ''
    },
    //  重置
    resetSearchForm () {
      this.queryParam.beginDate = moment().startOf('month').format('YYYY-MM-DD') + ' 00:00:00'
      this.queryParam.endDate = moment().endOf('month').format('YYYY-MM-DD') + ' 23:59:59'
      this.monthVal = moment().format('YYYY-MM')
      this.queryParam.provinceSn = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.discountFlag = '0'
      this.queryParam.dealerNewFlag = undefined
      this.totalData = null
      this.$refs.subarea && this.$refs.subarea.clearData()
      this.$refs.areaList && this.$refs.areaList.clearData()
      this.$refs.table.clearTable()
      this.$refs.ruleForm.resetFields()
    },
    //  导出  必填判断
    handleExport () {
      const _this = this
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          _this.exportList()
        } else {
          _this.$message.error('请选择查询月份')
          return false
        }
      })
    },
    // 导出
    exportList () {
      const _this = this
      const params = JSON.parse(JSON.stringify(_this.queryParam))
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(promoProvinceExport, params, '促销费用报表（省份）', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
        this.resetSearchForm()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.getTableTitle()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.getTableTitle()
    }
  }
}
</script>
<style lang="less" scoped>
  .monthBox{
    width: 100%;
    /deep/.ant-calendar-picker-icon{
      display:none !important;
    }
    /deep/.ant-calendar-picker input{
      text-align:center;
    }
  }
</style>
