<template>
  <div>
    <a-card size="small" :bordered="false" class="customerCountList-wrap searchBoxNormal">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper" ref="tableSearch">
        <a-form-model
          id="customerCountList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="销售月份" required>
                <a-range-picker
                  id="customerCountList-monthBox"
                  class="monthBox"
                  :placeholder="['开始月份', '结束月份']"
                  format="YYYY-MM"
                  v-model="monthVal"
                  :mode="mode"
                  @panelChange="handlePanelChange"
                />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户名称">
                <dealerSubareaScopeList ref="dealerSubareaScopeList" id="customerCountList-dealerName" @change="custChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="客户级别">
                <v-select
                  v-model="queryParam.dealerLevel"
                  ref="dealerLevel"
                  id="customerCountList-dealerLevel"
                  code="DEALER_LEVEL"
                  placeholder="请选择客户级别"
                  allowClear></v-select>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="所在区域">
                  <subarea id="customerCountList-subarea" ref="subarea" @change="subareaChange"></subarea>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-model-item label="区域负责人">
                  <BizUser id="customerCountList-bizUserSn" v-model="queryParam.subareaArea.bizUserSn"></BizUser>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="地区">
                  <AreaList id="customerCountList-areaList" changeOnSelect ref="areaList" @change="areaChange" defValKey="id"></AreaList>
                </a-form-model-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-model-item label="客服">
                  <customerService ref="customerName" id="customerCountList-customerName" v-model="queryParam.subareaArea.kfSn"></customerService>
                </a-form-model-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-model-item label="实售/开单金额">
                  <a-select placeholder="请选择">
                    <a-select-option value="1">实售金额</a-select-option>
                    <a-select-option value="2">开单金额</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24">
              <a-button
                type="primary"
                @click="handleSearch"
                :disabled="disabled"
                id="customerCountList-refresh">查询</a-button>
              <a-button
                style="margin-left: 8px"
                @click="resetSearchForm"
                :disabled="disabled"
                id="customerCountList-reset">重置</a-button>
              <a-button
                style="margin-left: 10px"
                type="primary"
                class="button-warning"
                @click="handleExport"
                :disabled="disabled"
                :loading="exportLoading"
                v-if="$hasPermissions('B_billingStatisticsExport')"
                id="customerCountList-export">导出</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'" />
              </a>
            </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.no"
          rowKeyName="no"
          :style="{ height: tableHeight+70+'px' }"
          :columns="columns"
          :data="loadData"
          :scroll="{x:2200, y: tableHeight-130}"
          :defaultLoadData="false"
          bordered>
          <template slot="footer" v-if="totalData&&totalData.length">
            <a-row :gutter="15">
              <a-col span="24">合计:</a-col>
              <a-col span="24">
                <a-col span="4" v-for="item in totalData" :key="item.key">
                  {{ item.title }}:{{ item[item.key] ||item[item.key] ==0?toThousands(item[item.key]) :'--' }}
                </a-col>
              </a-col>
            </a-row>
          </template>
        </s-table>
      </a-spin>
    </a-card>
  </div>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { hdExportExcel } from '@/libs/exportExcel'
import moment from 'moment'
import tableTitle from './dataCustomer.js'
// 组件
import { STable, VSelect } from '@/components'
import subarea from '@/views/common/subarea.js'
import AreaList from '@/views/common/areaList.js'
import dealerSubareaScopeList from '@/views/common/dealerSubareaScopeList.vue'
import BizUser from '@/views/common/bizUser.js'
import customerService from '@/views/common/customerService.vue'
// 接口
import { salesStatsDealerList, salesStatsDealerCount, salesStatsDealerExport } from '@/api/reportData'
export default {
  name: 'CustomerCountList',
  mixins: [commonMixin],
  components: { STable, VSelect, subarea, AreaList, dealerSubareaScopeList, BizUser, customerService },
  data () {
    return {
      spinning: false,
      disabled: false, //  查询、重置按钮是否可操作
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0, // 表格高度
      exportLoading: false, // 导出按钮加载状态
      monthVal: [moment().format('YYYY-MM'), moment().format('YYYY-MM')], // 初始化月份值
      mode: ['month', 'month'],
      //  查询条件
      queryParam: {
        beginDate: '', // 月份开始时间
        endDate: '', // 月份结束时间
        dealerLevel: undefined, // 客户等级
        dealerSnOwner: undefined, // 客户sn
        dealerName: undefined, // 客户名称
        provinceSn: undefined, // 省
        citySn: undefined, // 市
        districtSn: undefined, // 区
        subareaArea: {
          subareaSn: '', // 区域
          subareaAreaSn: '', // 分区
          bizUserSn: undefined, // 区域负责人
          kfSn: undefined// 客服
        }
      },
      columns: [], // 表格  列数据
      totalData: null, // 合计
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        if (this.monthVal) {
          this.queryParam.beginDate = this.getMonthRange(this.monthVal[0]).firstDay
          this.queryParam.endDate = this.getMonthRange(this.monthVal[1]).lastDay
        } else {
          this.queryParam.beginDate = undefined
          this.queryParam.endDate = undefined
        }
        const params = Object.assign(parameter, this.queryParam)
        params.removeReportFlag = 1
        // 获取列表数据  有分页
        return salesStatsDealerList(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
        })
      }
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时,需同时更改表格高度
      this.setTableH()
    }
  },
  methods: {
    handlePanelChange (value, mode) {
      this.monthVal = value
      this.mode = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]]
    },
    // 获取指定月份   第一天和最后一天
    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
      this.columns = tableTitle.list
      this.countLabel = tableTitle.count
      this.columns.map(item => {
        const mw = item.type == 'amount' ? 15 : 17
        const textLen = typeof item.title === 'string' ? item.title.length : item.txtLen
        const w = textLen * mw
        const tw = w <= 80 ? mw * 5 : w
        if (item.type == 'amount') {
          if (item.colour && item.colour === 'red') {
            item.title = <span style="color:red;">{ item.title }</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 || '--' }
        }
        item.width = tw + 'px'
        this.tableWidth = this.tableWidth + tw
      })
      this.resetSearchForm()
    },
    // 查询
    handleSearch () {
      const date = this.monthVal
      if (date && date[0] && date[1]) {
        this.$refs.table.refresh(true)
      } else {
        this.$message.error('请选择查询月份')
      }
    },
    // 客户名称 change
    custChange (val) {
      this.queryParam.dealerName = val.name
      this.queryParam.dealerSnOwner = val.key
    },
    // 统计
    getCount (params) {
      salesStatsDealerCount(params).then(res => {
        if (res.status == 200 && res.data) {
          const mergedList = this.countLabel.map(item => {
            const key = item.key
            return key in res.data
              ? { ...item, [key]: res.data[key] }
              : item
          })
          this.totalData = mergedList
        } else {
          this.totalData = null
        }
      })
    },
    // 地区
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.citySn = val[1] ? val[1] : undefined
      this.queryParam.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 = ''
      this.queryParam.endDate = ''
      this.monthVal = [moment().format('YYYY-MM'), moment().format('YYYY-MM')]
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.districtSn = undefined
      this.queryParam.dealerName = undefined
      this.queryParam.dealerSnOwner = undefined
      this.queryParam.bizUserSn = undefined
      this.queryParam.subareaArea.subareaSn = ''
      this.queryParam.subareaArea.subareaAreaSn = ''
      this.queryParam.subareaArea.bizUserSn = undefined
      this.queryParam.subareaArea.kfSn = undefined
      this.queryParam.dealerLevel = undefined
      if (this.advanced) {
        this.$refs.subarea.clearData()
        this.$refs.dealerSubareaScopeList.resetForm()
        this.$refs.areaList.clearData()
      }
      this.totalData = null
      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))
      params.removeReportFlag = this.removeReportFlag
      _this.exportLoading = true
      _this.spinning = true
      hdExportExcel(salesStatsDealerExport, params, this.removeReportFlag == 0 ? '开单统计报表(客户)' : '未统计销售退货(客户)', function () {
        _this.exportLoading = false
        _this.spinning = false
      })
    },
    // 初始化
    pageInit () {
      this.$nextTick(() => { // 页面渲染完成后的回调
        this.setTableH()
        this.resetSearchForm()
        this.getTableTitle()
      })
    },
    // 计算表格高度
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 280
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
    }
  },
  activated () {
    // 如果是新页签打开,则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
    }
  }
}
</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>