<template>
  <div class="activeuser-baseInfo">
    <a-page-header :ghost="false" title="活跃用户" :backIcon="false" class="activeuser-back">
      <template slot="subTitle">
        <a href="javascript:;" @click="handleBack" id="activeuser-handleBack">
          <a-icon type="left"></a-icon> 返回上页
        </a>
      </template>
    </a-page-header>
    <a-card size="small" :bordered="false" style="margin-bottom: 6px;">
      <div style="padding:0 10px;color: #00aaff;cursor: pointer;" slot="extra" @click="showSetModal=true"><a-icon type="setting" /> 参数设置</div>
      <div class="gard-box">
        <div v-for="(card,i) in getShelfLeveData" :key="i" @click="chooseCard(i)" :class="cardIndex == i? 'chooseCard':''">
          <a-card size="small">
            <h4>{{ card.levelName }}</h4>
            <p v-if="card.levelName == 'LV1'">近{{ card.dayLimit }}天销售金额 ≤ {{ card.amountMax }}元</p>
            <p v-if="card.levelName == 'LV2'">{{ card.amountMin }}元 < 近{{ card.dayLimit }}天销售金额 ≤ {{ card.amountMax }}元</p>
            <p v-if="card.levelName == 'LV3'">{{ card.amountMin }}元 < 近{{ card.dayLimit }}天销售金额 ≤ {{ card.amountMax }}元</p>
            <p v-if="card.levelName == 'LV4'">{{ card.amountMin }}元 < 近{{ card.dayLimit }}天销售金额 ≤ {{ card.amountMax }}元</p>
            <p v-if="card.levelName == 'LV5'">{{ card.amountMin }}元 < 近{{ card.dayLimit }}天销售金额</p>
            <div>
              <div>
                <span>门店数量</span>
                <span>{{ card.shelfCount }}个</span>
              </div>
              <div>
                <span>累计销售金额</span>
                <span>{{ card.amountSum }}元</span>
              </div>
              <div>
                <span>门店数量占比</span>
                <span>{{ card.shelfRate? card.shelfRate : 0 }}</span>
              </div>
              <div>
                <span>累计销售金额占比</span>
                <span>{{ card.amountRate? card.amountRate : 0 }}</span>
              </div>
            </div>
          </a-card>
        </div>
      </div>
    </a-card>
    <a-card size="small" :bordered="false">
      <a-spin :spinning="spinning" tip="Loading...">
        <div ref="tableSearch" class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
            <a-row :gutter="15">
              <a-col :md="5" :sm="24">
                <a-form-item label="货架创建时间">
                  <rangeDate ref="rangeDate" :value="time" @change="dateChange" />
                </a-form-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-item label="汽车修理厂">
                  <storeList ref="storeList" @change="storeChange" id="activeuser-storeChange"></storeList>
                </a-form-item>
              </a-col>
              <a-col :md="5" :sm="24">
                <a-form-item label="配件经销商">
                  <dealerList ref="dealerList" @change="dealerChange" id="activeuser-dealerChange"></dealerList>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="所在地">
                  <areaList level="2" placeholder="请选择所在地" v-model="areaArr" @change="areaChange"></areaList>
                </a-form-item>
              </a-col>
              <template v-if="advanced">
                <a-col :md="4" :sm="24">
                  <a-form-item label="货架状态">
                    <v-select id="activeuser-state" code="SHELF_STATE" v-model="queryParam.shelfState" allowClear placeholder="请选择状态"></v-select>
                  </a-form-item>
                </a-col>
              </template>
              <a-col :md="4" :sm="24" style="margin-bottom: 10px;">
                <a-button type="primary" @click="$refs.table.refresh(true)" id="activeuser-refresh">查询</a-button>
                <a-button type="" @click="reset" style="margin-left: 10px;" id="activeuser-reset">重置</a-button>
                <a-button type="primary" @click="exportFile" class="button-warning" style="margin-left: 10px;" id="activeuser-reset">导出</a-button>
                <a @click="advanced=!advanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div class="table-operator" v-if="statisticsObj">
          <a-alert type="info">
            <div slot="message" class="total-bar">
              <div>
                门店数量：<strong>{{ statisticsObj.shelfCount || 0 }}</strong>；
                近30天货架取货数量合计：<strong>{{ statisticsObj.totalOrderQty || 0 }}</strong>；
                近30天货架取货金额合计：<strong>{{ statisticsObj.totalOrderAmount || 0 }}</strong>；
                近30天销售数量合计：<strong>{{ statisticsObj.saleOrderQty || 0 }}</strong>；
                近30天销售金额合计：<strong>{{ statisticsObj.saleOrderAmount || 0 }}</strong>；
              </div>
            </div>
          </a-alert>
        </div>
        <s-table
          class="sTable fixPagination"
          ref="table"
          :style="{ height: tableHeight+84.5+'px', wordBreak: 'break-all' }"
          size="small"
          :rowKey="(record,index)=>{return index}"
          :columns="columns"
          :data="loadData"
          :scroll="{ y: tableHeight }"
          :defaultLoadData="false"
          bordered>
          <div slot="area" slot-scope="text, record">
            {{ record.dealerProvinceName }} {{ record.dealerCityName }}
          </div>
        </s-table>
      </a-spin>
    </a-card>
    <!-- 参数设置 -->
    <setModal :openModal="showSetModal" :nowData="itemData" @ok="getShelfLeve" @close="showSetModal=false"></setModal>
  </div>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { queryShelfActiveUserPage, queryShelfLevelReport, exportShelfActiveUser, statistics } from '@/api/report.js'
import areaList from '@/views/common/areaList.js'
import dealerList from '@/views/common/dealerList.vue'
import storeList from '@/views/common/storeList.vue'
import { toThousands } from '@/libs/tools.js'
import { hdExportExcel } from '@/libs/exportExcel'
import setModal from './setModal.vue'
export default {
  name: 'UserList',
  components: { STable, VSelect, rangeDate, dealerList, storeList, areaList, setModal },
  data () {
    return {
      spinning: false,
      advanced: false,
      showSetModal: false,
      tableHeight: 0,
      activeKey: ['1'],
      time: [],
      orderTime: [],
      // 查询参数
      queryParam: {
        endDate: '',
        beginDate: '',
        storeSn: undefined,
        dealerSn: undefined,
        shelfState: undefined,
        dealerProvinceSn: undefined,
        dealerCitySn: undefined
      },
      showModal: false,
      itemData: null, // 编辑行数据
      openStatusModal: false, // 货架状态弹窗初始状态
      getShelfLeveData: [], // 货架等级数据
      statisticsObj: null,
      cardIndex: null,
      areaArr: [],
      // 表头
      columns: [
        { title: '序号', dataIndex: 'no', width: '5%', align: 'center' },
        { title: '货架创建时间', dataIndex: 'shelfCreateDate', width: '10%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '汽车修理厂', dataIndex: 'storeName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '配件经销商', dataIndex: 'dealerName', width: '15%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '所在地', scopedSlots: { customRender: 'area' }, width: '11%', align: 'center' },
        { title: '货架状态', dataIndex: 'shelfStateDictValue', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '近30天货架取货数量', dataIndex: 'totalOrderQty', width: '11%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') }, sorter: true },
        { title: '近30天货架取货金额', dataIndex: 'totalOrderAmount', width: '11%', align: 'center', customRender: function (text) { return ((text || text == 0) ? toThousands(text, 2) : '--') }, sorter: true },
        { title: '近30天销售数量', dataIndex: 'saleOrderQty', width: '11%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') }, sorter: true },
        { title: '近30天销售金额', dataIndex: 'saleOrderAmount', width: '11%', align: 'center', customRender: function (text) { return ((text || text == 0) ? toThousands(text, 2) : '--') }, sorter: true }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.spinning = true
        return queryShelfActiveUserPage(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {// eslint-disable-line
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (let i = 0; i < data.list.length; i++) {
              const _item = data.list[i]
              _item.no = no + i + 1
            }
          }
          this.spinning = false
          this.getShelfLeve()
          this.getStatistics(this.queryParam)
          return data
        })
      }
    }
  },
  methods: {
    handleBack () {
      this.$router.go(-1)
    },
    //  时间  change
    dateChange (date) {
      this.queryParam.beginDate = date[0]
      this.queryParam.endDate = date[1]
    },

    // 经销商 change
    dealerChange (obj) {
      this.queryParam.dealerSn = obj.key || undefined
    },
    // 汽车修理厂 change
    storeChange (obj) {
      this.queryParam.storeSn = obj.key || undefined
    },
    // 地区
    areaChange (val, opts) {
      this.queryParam.dealerProvinceSn = val && val[0] ? val[0] : ''
      this.queryParam.dealerCitySn = val && val[1] ? val[1] : ''
    },
    // 导出
    exportFile () {
      const _this = this
      this.spinning = true
      hdExportExcel(exportShelfActiveUser, this.queryParam, '用户分析(活跃用户)详情', function () {
        _this.spinning = false
      })
    },
    // 重置
    reset () {
      this.cardIndex = null
      this.queryParam = {
        endDate: '',
        beginDate: '',
        storeSn: undefined,
        dealerSn: undefined,
        shelfState: undefined,
        dealerProvinceSn: undefined,
        dealerCitySn: undefined
      }
      this.areaArr = []
      this.$refs.rangeDate.resetDate()
      this.$refs.dealerList.resetForm()
      this.$refs.storeList.resetForm()
      this.$refs.table.refresh(true)
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 255
    },
    // 获取货架等级
    getShelfLeve () {
      const _this = this
      queryShelfLevelReport().then(res => {
        if (res.status == 200) { // eslint-disable-line
          _this.getShelfLeveData = res.data
        } else {
          _this.$message.error(res.message)
        }
      })
    },
    // 获取活跃用户统计数据
    getStatistics (ajaxData) {
      statistics(ajaxData).then(res => {
        if (res.status == 200) { // eslint-disable-line
          this.statisticsObj = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 选中盒子
    chooseCard (num) {
      if (this.cardIndex == num) { // eslint-disable-line
        this.cardIndex = null
        var { lvCode, dealerSnList, customerSnList, ...newObj } = this.queryParam
        this.queryParam = newObj
      } else {
        this.cardIndex = num
        const obj = {
          lvCode: this.getShelfLeveData[num].levelName,
          dealerSnList: this.getShelfLeveData[num].dealerSnList || [],
          customerSnList: this.getShelfLeveData[num].customerSnList || []
        }
        Object.assign(this.queryParam, obj)
      }
      this.$refs.table.refresh(true)
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.reset()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.reset()
    }
  }
}
</script>
<style lang="less">
  .activeuser-baseInfo{
    .activeuser-back{
      margin-bottom: 6px;
    }
    .gard-box{
      display: flex;
      > div{
        width: 20%;
        padding:0 10px;
        .ant-card-body{
          > h4,p{
            text-align: center;
          }
          > h4{
            font-size: 18px;
            margin: 0 0 5px;
          }
          > div{
            > div{
              display: flex;
              align-items: center;
              justify-content: space-between;
              padding: 2px 0;
              > span{
                &:first-child{
                  color:#999;
                }
              }
            }
          }
        }
      }
    }
  }
  .chooseCard .ant-card-bordered{
    border:1px solid #91d5ff !important;
    background:#e6f7ff !important;
  }
</style>
