<template>
  <div class="page-header-index-wide">
    <template v-if="pageRoleNum >= 2">
      <a-empty description="请联系管理员，当前角色权限设置有误或者当前账户无权限" style="height: 210px;margin-top: 200px;"/>
    </template>
    <template v-else>
      <a-row :gutter="24">
        <a-col :sm="24" :md="12" :xl="6" :style="{ marginBottom: '24px', cursor: 'pointer' }" v-for="(item, index) in zhibiaoTotal" :key="index" @click="clickItemTotal(item, index)">
          <chart-card :loading="loading" :title="item.title+' (万元) / 当月'" :total="totalPrice(item.monthTotal)">
            <a-tooltip :title="`点击查看${item.title}明细`" slot="action">
              <a-icon type="info-circle-o" />
            </a-tooltip>
            <div>
              <trend :flag="setJiantou(item.monthTb)" style="margin-right: 16px;">
                <span slot="term">月同比</span>
                {{comTbHb(item.monthTb)}}%
              </trend>
              <trend :flag="setJiantou(item.monthHb)">
                <span slot="term">月环比</span>
                {{comTbHb(item.monthHb)}}%
              </trend>
            </div>
            <template slot="footer">年{{item.title}}<span> {{totalPriceYear(item.yearTotal)}}</span>
              <trend :flag="setJiantou(item.yearTb)"  style="float: right;">
                <span slot="term">同比</span>
                {{comTbHb(item.yearTb)}}%
              </trend>
            </template>
          </chart-card>
        </a-col>
        
      </a-row>

      <!-- 第二级模块：折/柱形图 -->
      <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}">
        <div class="salesCard">
          <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
            <div class="extra-wrapper" slot="tabBarExtraContent">
              <div class="extra-item">
                <a-button :type="searchType==='month'?'primary':'link'" @click="searchTypeChange('month')">按月查询</a-button>
                <a-button :type="searchType==='year'?'primary':'link'" @click="searchTypeChange('year')">按年查询</a-button>
              </div>
              <!-- <a-range-picker :style="{width: '256px'}" /> -->
              <a-range-picker
                :placeholder="searchPlaceholder"
                :format="searchFormat"
                :mode="searchMode"
                :value="dateValue"
                :open="datePickShow"
                @panelChange="handlePanelChange"
                @openChange="datePickShow = !datePickShow"
              >
                <template slot="renderExtraFooter">
                  <div style="width: 540px;">
                    <a-button type="primary" style="float: right;margin: 8px;" @click="handleDateSure">确定</a-button>
                  </div>
                </template>
              </a-range-picker>
            </div>
            <a-tab-pane loading="true" :tab="chartTitle+'图表'" key="1">
              <a-row>
                <template v-if="chooseValue !== 'chb'">
                  <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                  <!-- <a-col :xl="chooseValue === 'chb'?16:24" :lg="chooseValue === 'chb'?16:24" :md="chooseValue === 'chb'?16:24" :sm="24" :xs="24"> -->
                    <!-- <bar title="销售额排行" :dataSource="barData"/> -->
                    <twoYAxisChart v-if="chooseValue === 'hte'" ref="twoYAxisChartRef" :twoYAxisData="twoYAxisData"
                    style="height: 360px;"
                    class="line-timePrice common-layout"></twoYAxisChart>
                    <lineBarChart v-else ref="lineBarChartRef" :xAxisData="lineBarXAxisData" :seriesData="lineBarSeriesData" :title="chartTitle" 
                    style="height: 360px;"
                    class="line-timePrice common-layout"></lineBarChart>
                  </a-col>
                </template>
                <template v-if="chooseValue === 'chb'">
                  <a-col :xl="16" :lg="16" :md="16" :sm="24" :xs="24">
                    <lineBarChartChb ref="lineBarChartChbRef" :xAxisData="chbXAxisData" :seriesData="chbSeriesData" :title="chartTitle" 
                      style="height: 360px;"
                      class="line-timePrice common-layout"></lineBarChartChb>
                  </a-col>
                  <a-col :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
                    <rank-list title="详情" :list="rankList"/>
                    <!-- <pieContentChart style="height: 360px;"></pieContentChart> -->
                  </a-col>
                </template>
              </a-row>
            </a-tab-pane>
            <!-- <a-tab-pane tab="销售趋势" key="2">
              <a-row>
                <a-col :xl="16" :lg="12" :md="12" :sm="24" :xs="24">
                  <bar title="销售额趋势" :dataSource="barData"/>
                </a-col>
                <a-col :xl="8" :lg="12" :md="12" :sm="24" :xs="24">
                  <rank-list title="门店销售排行榜" :list="rankList"/>
                </a-col>
              </a-row>
            </a-tab-pane> -->
          </a-tabs>
        </div>
      </a-card>

      <!-- 第三级模块：部门指标排行 -->
      <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}" style="margin-top: 20px;" v-if="pageRoleNum===0">
        <div class="salesCard">
          <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
            <div class="extra-wrapper" slot="tabBarExtraContent">
              <div class="extra-item">
                <a-button :type="zbPhParams.time==='month'?'primary':'link'" @click="searchZbphChange('month')">按月查询</a-button>
                <a-button :type="zbPhParams.time==='year'?'primary':'link'" @click="searchZbphChange('year')">按年查询</a-button>
              </div>
              <a-month-picker v-if="zbPhParams.time === 'month'" placeholder="请选择月" :disabled-date="disabledYear" :value="zbPhParams.beginDate" @change="zbphSearchChange" />
              <!-- <a-date-picker  v-if="zbPhParams.time === 'year'"
                @Change=zbphSearchChange
                placeholder="请选择年"
                mode="year"
                v-model="zbPhParams.beginDate"
                format="YYYY"
                allowClear="false"
              /> -->
              <a-date-picker
                v-if="zbPhParams.time === 'year'"
                mode="year"
                format="YYYY"
                :value="zbPhParams.yearValue"
                :open="zbphYearIsopen"
                :disabled-date="disabledYear"
                placeholder="请选择年份"
                @focus="changeopen"
                @panelChange="handlePanelChange1">
              </a-date-picker>

            </div>
            <a-tab-pane loading="true" tab="下达部门指标排行" key="1">
              <a-row>
                <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                  <deptZbphTable :dataSource="zbPhDataSource.jycsCharts" :loading="zhbLoading" deptType="xd" class="dept-zbph-table"></deptZbphTable>
                </a-col>
              </a-row>
            </a-tab-pane>
            <a-tab-pane loading="true" tab="责任部门指标排行" key="2">
              <a-row>
                <a-col :xl="24" :lg="24" :md="24" :sm="24" :xs="24">
                  <deptZbphTable :dataSource="zbPhDataSource.zrbmCharts" :loading="zhbLoading" deptType="zr" class="dept-zbph-table"></deptZbphTable>
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-card>
      
      <!-- <a-card :loading="loading" :bordered="false" :body-style="{padding: '0'}" :style="{ marginTop: '24px' }">
        <div class="salesCard">
          <a-tabs default-active-key="1" size="large" :tab-bar-style="{marginBottom: '24px', paddingLeft: '16px'}">
            <div class="extra-wrapper" slot="tabBarExtraContent">
              <div class="extra-item">
                <a>本月</a>
                <a>本季</a>
                <a>本年</a>
              </div>
              <a-range-picker :style="{width: '256px'}" />
            </div>
            <a-tab-pane loading="true" :tab="'部门'+chartTitle+'排行'" key="1">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="12" :md="12" :sm="24" :xs="24">
                  <rankingChart :title="chartTitle" :seriesData="rankingSeriesData" :yAxisNames="rankingYAxisNames" :yAxisNumbers="yAxisNumbers" style="height: 360px;"></rankingChart>
                </a-col>
                <a-col :xl="18" :lg="12" :md="12" :sm="24" :xs="24">
                  <a-table
                    ref="table"
                    size="middle"
                    :scroll="{x:true}"
                    bordered
                    rowKey="id"
                    :columns="columns"
                    :dataSource="dataSource"
                    :pagination="ipagination"
                    :loading="loading"
                    class="j-table-force-nowrap"
                    :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                    @change="handleTableChange"
                    >
                  </a-table>
                </a-col>
              </a-row>
            </a-tab-pane>
          </a-tabs>
        </div>
      </a-card> -->
    </template>
    


  </div>
</template>

<script>
  import moment from 'moment'
  import { getZhibiaoCollect, getdataByHt, getdataBySk,  getdataByChb, getdataByLr, deptZhibiaoPaihang, } from '@/api/kzksApi'

  import ChartCard from '@/components/ChartCard'
  import RankList from '@/components/chart/RankList'
  import Trend from '@/components/Trend'

  import lineBarChart from './components/lineBarChart.vue'
  import lineBarChartChb from './components/lineBarChartChb.vue'
  import rankingChart from './components/rankingChart.vue'
  import pieContentChart from './components/pieContentChart.vue'
  import twoYAxisChart from './components/twoYAxisChart.vue'

  import deptZbphTable from './components/deptZbphTable.vue'

  import { getLoginfo,getVisitInfo } from '@/api/api'

  const chb8Names = [
    { name: '外协费', value: 'wxf' },
    { name: '材料费', value: 'clf' },
    { name: '专用费', value: 'zyf' },
    { name: '事务费', value: 'swf' },
    { name: '燃动费', value: 'rldlf' },
    { name: '工时费', value: 'gzjlwf' },
    { name: '固资费', value: 'gdzczj' },
    { name: '管理费', value: 'glf' },
    { name: '工资费', value: 'gzjlwf' },
  ]
  export default {
    name: "dashboardAnalysis",
    components: {
      ChartCard,
      Trend,
      RankList,

      lineBarChart,
      lineBarChartChb,
      rankingChart,
      pieContentChart,
      twoYAxisChart,

      deptZbphTable,
    },
    data() {
      return {
        loading: true,
        rankList: [],
        loginfo:{},
        visitInfo:[],

        pageRoleNum: 0,
        // 顶部n项指标
        zhibiaoTotal: [
          // {
          //   value: 'hte',
          //   title: '合同数量',
          //   totalMoney: '53',
          //   lineBarSeriesData: [
          //     {
          //       name: '合同数量',
          //       data: [32, 22, 21, 45, 23, 32, 34],
          //     },
          //   ],
          // },
          {
            value: 'hte',
            hdValue: 'hte',
            title: '合同额',
            data: {},
          },
          {
            value: 'ske',
            hdValue: 'ske',
            title: '收款额',
            data: {},
          },
          {
            value: 'chb',
            hdValue: 'zce',
            title: '成本额',
            data: {},
          },
          {
            value: 'lre',
            hdValue: 'lre',
            title: '利润额',
            data: {},
          },
        ],


        // 日期区间选择模块
        searchType: 'month',
        searchPlaceholder: ['开始月份', '结束月份'],
        searchFormat: 'YYYY-MM', // 日期区间选择器format（页面数据显示格式）
        dateValue: [null, null], // 日期区间选择器format（页面显示的数据）
        searchMode: ['month', 'month'], // 日期区间选择器mode（选择器形式）
        datePickShow: false,
        // 日期区间选择传参数据
        searchParams: {
          time: '',
          beginDate: null,
          endDate: null,
        },

        // 选择指标
        chooseValue: 'hte',
        chartTitle: '合同',

        // 折线柱形总览图
        lineBarXAxisData: [],
        lineBarSeriesData: [],
        chbXAxisData: [],
        chbSeriesData: {
          seriesData: [],
          sumZcbData: [],
        },
        // 排行
        rankingSeriesData: [50, 42, 26, 20, 15, 14, 12, 8, 5, 1],
        rankingYAxisNames: ["部门06", "部门01", "部门05", "部门10", "部门07", "部门04", "部门03", "部门08", "部门09", "部门02"],
        yAxisNumbers: [50, 42, 26, 23, 15, 14, 12, 8, 5, 1],

        // 双y轴总览图
        twoYAxisData: {},
        // 排行

        // 部门指标排行
        zhbLoading: true,
        zbPhParams: {
          beginDate: null,
          yearValue: null, // 因为dataPick是moment格式，所以加一个进行转化显示用
          time: ''
        },
        columns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'部门',
            align:"center",
            dataIndex: 'wlbm'
          },
          {
            title:'已收款',
            align:"center",
            dataIndex: 'ggxh'
          },
          {
            title:'成本',
            align:"center",
            dataIndex: 'zlLevel'
          },
          {
            title:'利润',
            align:"center",
            dataIndex: 'pici'
          },
          // {
          //   title:'利润率',
          //   align:"center",
          //   dataIndex: 'pici'
          // },
          {
            title:'合同数量',
            align:"center",
            dataIndex: 'danjia'
          },
          {
            title:'合同金额',
            align:"center",
            dataIndex: 'htDate'
          },
        ],
        zbphYearIsopen: false,
        zbPhDataSource: {
          jycsCharts: [],
          zrbmCharts: [],
        },

      }
    },
    computed: {
      // 判断箭头样式
      setJiantou(){
        // 闭包实现computed中传参
        return function (value) {
          var item = Number(value) > 0 ? 'up' : 'down'
          return item
        }
      },
      totalPrice(){
        return function (value) {
          var item = (Number(value) / 10000).toFixed(2)
          // console.log(item)
          return '￥'+item
        }
      },
      totalPriceYear(){
        return function (value) {
          var item = (Number(value) / 10000).toFixed(2)
          console.log(item)
          return item + ' 万元'
        }
      },
      // 将后端数据准换成整数%显示
      comTbHb(){
        return function (value) {
          // console.log(Math.abs('-0.35'))
          var item = (Math.abs(value) * 100).toFixed(0)
          return item
        }
      },
    },
    created() {
      this.initLogInfo();
      this.getZhibiaoCollect()
      this.setNowDate()
      // 部门指标排行
      // this.deptZhibiaoPaihang()
      this.searchZbphChange('month')
    },
    methods: {
      //限制选择年份
      disabledYear(current){
        // 不可以选择之前的日期,今天包括之后可以选，控制大于小于来实现选择之前的日期还是之后的日期
        // return current < moment().subtract(1, 'year');
        var timeYear = current.get('year');  // 当前年
        return timeYear < '2023';
      },
      getZhibiaoCollect(){
        this.loading = true
        getZhibiaoCollect().then(res => {
          console.log(res)
          if (res.success) {
            // 0:所领导，1：部门领导，2：员工；3：未赋值或选了多个前面所说角色
            // 如果是管理员，默认显示所领导的
            this.pageRoleNum = res.result.auth
            if(res.result.auth >= 2){
              return
            }
            var arr = []
            for (let i = 0; i < this.zhibiaoTotal.length; i++) {
              const element = this.zhibiaoTotal[i];
              // element.data = res.result[element.hdValue]
              arr[i] = {...element, ...res.result.data[element.hdValue]}
            }
            this.zhibiaoTotal = arr
            this.loading = false
          }else{
            this.$message.warning(res.message)
            this.loading = false
          }
        }).finally(() => {
          this.loading = false
        })
      },
      setNowDate(type){
        const now = new Date()
        const year = now.getFullYear(); // 年
        const month = now.getMonth() + 1; // 月
        const monthBetter = month >= 10 ? month : '0' + month
        const beginDate = `${year}-01`
        const endDate = `${year}-${monthBetter}`
        this.dateValue = [beginDate, endDate]
        var sType = this.searchType ? this.searchType : type
        
        if(sType === 'month'){
          this.searchParams = {
            time: 'month',
            beginDate: beginDate,
            endDate: endDate,
          }
        } else if (sType === 'year') {
          this.searchParams = {
            time: 'year',
            beginDate: year,
            endDate: year,
          }
        }
        this.getDataByDate()
      },
      // 点击指标转换下方数据
      clickItemTotal(item, index){
        // console.log(item, index)
        this.chooseValue = item.value
        this.chartTitle = item.value === 'hte' ? '合同' : item.title
        // 调用showLoading方法--解决卡顿和数据闪等问题
        setTimeout(() => {
          // 定时器解决v-if下第一时间无法获取ref的问题
          if(this.$refs.lineBarChartRef){this.$refs.lineBarChartRef.uEcharts.showLoading({text: '加载中...'});}
          // 取消设置，因为一开始就很快
          if(this.$refs.twoYAxisChartRef){this.$refs.twoYAxisChartRef.uEcharts.showLoading({text: '加载中...'});}
          if(this.$refs.lineBarChartChbRef){this.$refs.lineBarChartChbRef.uEcharts.showLoading({text: '加载中...'});}
        }, 1);
        // this.lineBarSeriesData = item.lineBarSeriesData
        // console.log(this.dateValue)
        this.getDataByDate()
      },
      // 获取时间变化图表数据
      getDataByDate(){
        switch (this.chooseValue) {
          case 'hte':
            getdataByHt(this.searchParams).then(res => {
              console.log(res)
              if (res.success) {
                this.twoYAxisData = res.result
              }else{
                this.$message.warning(res.message)
              }
            }).finally(() => {
              // this.loading = false
            })
            break;
          case 'lre':
            getdataByLr(this.searchParams).then(res => {
              console.log(res)
              if (res.success) {
                this.lineBarXAxisData = res.result.xaxisData
                this.lineBarSeriesData = [
                  {
                    name: '利润额',
                    data: res.result.seriesData,
                  }
                ]
              }else{
                this.$message.warning(res.message)
              }
            }).finally(() => {
              // this.loading = false
            })
            break;
          case 'ske':
            getdataBySk(this.searchParams).then(res => {
              console.log(res)
              if (res.success) {
                this.lineBarXAxisData = res.result.xaxisData
                this.lineBarSeriesData = [
                  {
                    name: '收款额',
                    data: res.result.seriesData,
                  }
                ]
              }else{
                this.$message.warning(res.message)
              }
            }).finally(() => {
              // this.loading = false
            })
            break;
          case 'chb':
            getdataByChb(this.searchParams).then(response => {
              console.log(response)
              var chartsData = response.result[0].chartInfoList[0]
              var chbRankingData = response.result[0].eightCostPaiHang
              this.rankList = chbRankingData.map(res => {
                var findItem = chb8Names.find(item => item.value === res.name)
                return{
                  name: findItem.name + ' ' + res.proportion + '%',
                  total: (Number(res.value) / 10000).toFixed(2)+'万元'
                }
              })
              if(response){
                this.chbXAxisData = chartsData.xaxisData
                this.chbSeriesData.seriesData = chartsData.seriesData.map(res => {
                  var findItem = chb8Names.find(item => item.value === res.name)
                  return{
                    name: findItem.name,
                    data: res.values
                  }
                })
                this.chbSeriesData.sumZcbData = chartsData.sumZcbData
              }
            }).finally(() => {
              // this.loading = false
            })
            break;
          default:
            break;
        }
      },
      // 查询类型选择：按年、按月
      searchTypeChange(type){
        // this.resetParams()
        this.searchType = type
        this.searchFormat = type === 'month' ? 'YYYY-MM' : 'YYYY'
        this.searchPlaceholder = type === 'month' ? ['开始月份', '结束月份'] : ['开始年份', '结束年份']
        this.searchMode = [type, type]
        this.setNowDate(type)
      },
      handlePanelChange(value, mode) {
        // console.log(value, this.searchMode)
        // console.log(moment(value[0]).format('YYYY-MM'))
        this.dateValue = value;
        if(this.searchMode[0] === 'month'){
          this.searchParams = {
            time: 'month',
            beginDate: moment(value[0]).format('YYYY-MM'),
            endDate: moment(value[1]).format('YYYY-MM'),
          }
        }
        if(this.searchMode[0] === 'year'){
          this.searchParams = {
            time: 'year',
            beginDate: moment(value[0]).format('YYYY'),
            endDate: moment(value[1]).format('YYYY'),
          }
        }
        // this.modeMonth = [mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]];
      },
      handleDateSure(){
        console.log(this.searchParams)
        this.getDataByDate()
        this.datePickShow = false
      },
      initLogInfo () {
        getLoginfo(null).then((res)=>{
          if(res.success){
            Object.keys(res.result).forEach(key=>{
              res.result[key] =res.result[key]+""
            })
            this.loginfo = res.result;
          }
        })
        getVisitInfo().then(res=>{
          if(res.success){
             this.visitInfo = res.result;
           }
         })
      },
      // 获取部门指标排行数据
      deptZhibiaoPaihang(){
        this.zhbLoading = true
        deptZhibiaoPaihang(this.zbPhParams).then(res => {
          if (res.success) {
            console.log(res)
            this.zbPhDataSource = res.result
            // this.$message.success(res.message)
            // this.$emit('ok')
            this.zhbLoading = false
          } else {
            this.$message.warning(res.message)
            this.zhbLoading = false
          }
        }).finally(() => {
        })
      },
      // 部门指标排行搜索
      searchZbphChange(type){
        this.zbPhParams.time = type
        const now = new Date()
        const year = now.getFullYear(); // 年
        const month = now.getMonth() + 1; // 月
        const monthBetter = month >= 10 ? month : '0' + month
        const endDate = `${year}-${monthBetter}`
        if(type === 'month'){
          this.zbPhParams.yearValue = ''
          this.zbPhParams.beginDate = endDate
        }
        if(type === 'year'){
          this.zbPhParams.yearValue = moment(year, 'YYYY')
          this.zbPhParams.beginDate = year
          console.log(this.zbPhParams)
        }
        this.deptZhibiaoPaihang()
      },
      // 部门指标排行按月选择确事件
      zbphSearchChange(date, dateString){
        // console.log(date, dateString)
        this.zbPhParams.beginDate = dateString
        this.deptZhibiaoPaihang()
      },
      handlePanelChange1(value, mode) {
        // console.log(value);
        // console.log(mode);
        // console.log(moment(value).format('YYYY'))
        this.zbPhParams.yearValue = value
        this.zbPhParams.beginDate = moment(value).format('YYYY')
        this.deptZhibiaoPaihang()
        this.zbphYearIsopen = false
      },
      changeopen() {
        this.zbphYearIsopen = true;
      },
    }
  }
</script>

<style lang="less" scoped>
  .circle-cust{
    position: relative;
    top: 28px;
    left: -100%;
  }
  .extra-wrapper {
    line-height: 55px;
    padding-right: 24px;

    .extra-item {
      display: inline-block;
      margin-right: 24px;

      a {
        margin-left: 24px;
      }
    }
  }

  /* 首页访问量统计 */
  .head-info {
    position: relative;
    text-align: left;
    padding: 0 32px 0 0;
    min-width: 125px;

    &.center {
      text-align: center;
      padding: 0 32px;
    }

    span {
      color: rgba(0, 0, 0, .45);
      display: inline-block;
      font-size: .95rem;
      line-height: 42px;
      margin-bottom: 4px;
    }
    p {
      line-height: 42px;
      margin: 0;
      a {
        font-weight: 600;
        font-size: 1rem;
      }
    }
  }
  .dept-zbph-table{
    padding: 0 20px 20px;
  }
</style>