<template>
  <div class="page-header-index-wide">
    <template v-if="pageRoleNum > 2">
      <a-empty :description="false" 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="item.monthTotal+''">
            <a-tooltip :title="`点击查看${item.title}明细`" slot="action">
              <a-icon type="info-circle-o" />
            </a-tooltip>
            <div>
              <trend flag="up" style="margin-right: 16px;">
                <span slot="term">月同比</span>
                {{(Number(item.monthTb)*100).toFixed(2)}}%
              </trend>
              <trend flag="down">
                <span slot="term">月环比</span>
                {{(Number(item.monthHb)*100).toFixed(2)}}%
              </trend>
            </div>
            <template slot="footer">年{{item.title}}<span> {{item.yearTotal}}0</span>
              <trend flag="up" style="float: right;">
                <span slot="term">同比</span>
                {{(Number(item.yearTb)*100).toFixed(2)}}%
              </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=searchTypeMonth @click="searchTypeChange('month')">按月查询</a-button>
                <a-button :type="searchTypeYear" @click="searchTypeChange('year')">按年查询</a-button>
              </div>
              <!-- <a-range-picker :style="{width: '256px'}" /> -->
              <a-range-picker
                :placeholder="searchPlaceholder"
                :format="searchFormat"
                :mode="searchMode"
                :value="dateValue"
                @panelChange="handlePanelChange"
                @openChange="handleChange"
              >
                <template slot="renderExtraFooter">
                  extra footer
                </template>
              </a-range-picker>
            </div>
            <a-tab-pane loading="true" :tab="chartTitle+'图表'" key="1">
              <a-row>
                <a-col :xl="16" :lg="16" :md="16" :sm="24" :xs="24">
                  <!-- <bar title="销售额排行" :dataSource="barData"/> -->
                  <twoYAxisChart v-if="chooseValue === 'hte'"  :xAxisData="twoYAxisXAxisData" :seriesData="twoYAxisSeriesData" :title="chartTitle"
                  style="height: 360px;"
                  class="line-timePrice common-layout"></twoYAxisChart>
                  <lineBarChart v-else :xAxisData="lineBarXAxisData" :seriesData="lineBarSeriesData" :title="chartTitle" 
                  style="height: 360px;"
                  class="line-timePrice common-layout"></lineBarChart>
                </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>
              </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="{ 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, } 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 rankingChart from './components/rankingChart.vue'
  import pieContentChart from './components/pieContentChart.vue'
  import twoYAxisChart from './components/twoYAxisChart.vue'

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

  const rankList = []
  for (let i = 0; i < 7; i++) {
    rankList.push({
      name: '费用 ' + (i+1) + '5%',
      total: 1234.56 - i * 100
    })
  }
  export default {
    name: "IndexChart",
    components: {
      ChartCard,
      Trend,
      RankList,

      lineBarChart,
      rankingChart,
      pieContentChart,
      twoYAxisChart,
    },
    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: {},
          },
        ],


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

        // 选择指标
        chooseValue: 'hte',
        chartTitle: '成本',

        // 折线柱形总览图
        lineBarXAxisData: [],
        lineBarSeriesData: [],
        // 排行
        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轴总览图
        twoYAxisXAxisData: [],
        twoYAxisSeriesData: [],
        // 排行


        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'
          },
        ],
        dataSource: [],
        ipagination: {},

      }
    },
    created() {
      this.initLogInfo();
      this.getZhibiaoCollect()
      this.setNowDate()
    },
    methods: {
      getZhibiaoCollect(){
        this.loading = true
        getZhibiaoCollect().then(res => {
          console.log(res)
          if (res.success) {
            if(res.result.auth >2){
              // 0:所领导，1：部门领导，2：员工；3：未赋值或选了多个前面所说角色
              // 如果是管理员，默认显示所领导的
              this.pageRoleNum = res.result.auth
              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(){
        const now = new Date()
        const year = now.getFullYear(); // 年
        const month = now.getMonth() + 1; // 月
        const beginDate = `${year}-01`
        const endDate = `${year}-${month}`
        this.dateValue = [beginDate, endDate]
        this.searchParams = {
          time: 'month',
          beginDate: beginDate,
          endDate: endDate,
        }
        this.getDataByDate()
      },
      // 点击指标转换下方数据
      clickItemTotal(item, index){
        console.log(item, index)
        this.chooseValue = item.value
        this.chartTitle = item.value === 'hte' ? '合同' : item.title
        // 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.twoYAxisXAxisData = res.result.xaxisData
                this.twoYAxisSeriesData = [
                  {
                    name: '合同数量',
                    type: 'line',
                    data: res.result.contractTotal,
                  },
                  {
                    name: '合同额',
                    type: 'bar',
                    barWidth: '30%',
                    data: res.result.contractAmount,
                  }
                ]
              }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 'chb':
            getdataByChb(this.searchParams).then(res => {
              console.log(res)
              if(res){
                this.lineBarXAxisData = res[0].xaxisData
                this.lineBarSeriesData = [
                  {
                    name: '成本额',
                    data: res[0].seriesData,
                  }
                ]
              }
            }).finally(() => {
              // this.loading = false
            })
            break;
          default:
            break;
        }
      },
      // 查询类型选择：按年、按月
      searchTypeChange(type){
        this.searchTypeMonth = type === 'month' ? 'primary' : 'link'
        this.searchTypeYear = type === 'year' ? 'primary' : 'link'
        this.searchFormat = type === 'month' ? 'YYYY-MM' : 'YYYY'
        this.searchPlaceholder = type === 'month' ? ['开始月份', '结束月份'] : ['开始年份', '结束年份']
        this.searchMode = [type, 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]];
      },
      handleChange(status){
        console.log(status)
      },
      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;
           }
         })
      },

    }
  }
</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;
      }
    }
  }
</style>