<template>
  <div>
    <el-row>
      <el-col :span="24">
        <third-register></third-register>
      </el-col>
    </el-row>
    <el-row>
      <basic-container>
        <el-col :span="24">
          <avue-form :option="agentInfo.accountInfo.option" v-model="agentInfo.accountInfo.agentData">
            <template slot-scope="scope" slot="avatar">
              <avue-avatar :size="50" shape="circle" icon="el-icon-circle-plus-outline"
                           :src="agentInfo.accountInfo.agentData.avatar"
                           style="border: 1px solid #eee"/>
              <span class="mallName">{{ agentInfo.accountInfo.agentData.accountName }}</span>
            </template>
            <template slot-scope="scope" slot="totalBalance">
              <span>{{ agentInfo.accountInfo.agentData.totalBalance }} 元</span>
            </template>
            <template slot-scope="scope" slot="availableValance">
              <span>{{ agentInfo.accountInfo.agentData.availableValance }} 元</span>
            </template>
          </avue-form>
        </el-col>
      </basic-container>
    </el-row>
    <el-row>
      <el-col :span="24">
        <basic-container>
          <el-card class="box-card">
            <avue-data-panel :option="optionTotal"></avue-data-panel>
          </el-card>
          <div style="margin-top: 30px;">
            <h3>今日新增</h3>
            <avue-data-display :option="optionToday"></avue-data-display>
          </div>
          <div style="margin-top: 30px;">
            <h3>新增趋势
              <el-date-picker
                size="mini"
                :picker-options="tenantAddTrend.pickerOptions"
                v-model="tenantAddTrend.time"
                type="month"
                @change="getTenantAddTrend"
                value-format="yyyy-MM"
                placeholder="选择月"
                style="float: right">
              </el-date-picker>
            </h3>
            <div ref="tenantAddTrend" style="height: 500px;width: 100%"></div>
          </div>
          <div style="margin-top: 30px;">
            <h3>代理账单
              <el-date-picker
                size="mini"
                :picker-options="tenantPlatformBills.pickerOptions"
                v-model="tenantPlatformBills.time"
                type="month"
                @change="getTenantPlatformBills"
                value-format="yyyy-MM"
                placeholder="选择月"
                style="float: right">
              </el-date-picker>
            </h3>
            <div ref="tenantPlatformBills" style="height: 500px;width: 100%"></div>
          </div>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import moment from "moment";
import {mapGetters} from "vuex";
import * as echarts from 'echarts';
import {
  getAgentInfo,
  getAgentTenantAddTrend,
  getAgentTenantCensusCount,
  getTenantAgentBills,
  getAgentTenantTodayCensusCount,
} from '@/api/census/census';

export default {
  data() {
    return {
      agentInfo: {
        isLimitHeight: true,
        accountInfo: {
          agentData: {},
          option: {
            detail: true,
            labelPosition: "left",
            group: [
              {
                label: '代理信息',
                prop: 'agentInfo',
                icon: 'el-icon-s-custom',
                column: [
                  {
                    prop: "avatar",
                    span: 24,
                    slot: true,
                    labelWidth: 0,
                  },
                  {
                    label: '账户总余额',
                    span: 8,
                    prop: 'totalBalance',
                    slot: true,
                  },
                  {
                    label: '可提现余额',
                    span: 8,
                    prop: 'availableValance',
                    slot: true,
                  },
                  {
                    label: '用户身份',
                    span: 8,
                    prop: 'userType',
                  },
                ]
              }
            ]
          }
        },
      },
      optionTotal: {
        span: 12,
        data: [
          {
            click: () => {
              this.$router.push({path: "/ldt_agent/agentrecord"});
            },
            title: '商店总数',
            count: 0,
            icon: 'el-icon-s-shop',
            color: 'rgb(27, 201, 142)',
          },
          {
            click: () => {
              this.$router.push({path: "/ldt_agent/agentbills"});
            },
            title: '收入总额',
            count: 0,
            decimals: 2,
            icon: 'el-icon-s-marketing',
            color: '#f37b1d',
          },
        ]
      },
      optionToday: {
        span: 12,
        data: [
          {
            click: () => {
              this.$router.push({path: "/ldt_shop/shop"});
            },
            count: 0,
            title: '新增商户',
          },
          {
            click: () => {
              this.$router.push({path: "/ldt_bills/platformbills"});
            },
            count: 0,
            decimals: 2,
            title: '今日收入',
          },
        ]
      },
      tenantAddTrend: {
        dom: null,
        time: moment(Date.now()).format("yyyy-MM"),
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          }
        },
        option: {
          legend: {},
          tooltip: {
            trigger: 'axis',
            showContent: false
          },
          dataset: {
            source: [
              ['trend'],
              ['商户新增'],
            ],
            path: [ "/ldt_agent/agentrecord"]
          },
          xAxis: {type: 'category'},
          yAxis: {gridIndex: 0, splitNumber: 2},
          // grid: {top: '55%'},
          series: [
            {
              type: 'line',
              smooth: true,
              seriesLayoutBy: 'row',
              emphasis: {focus: 'series'},
            },
            // {
            //   type: 'pie',
            //   id: 'pie',
            //   radius: '30%',
            //   center: ['50%', '25%'],
            //   emphasis: {
            //     focus: 'self'
            //   },
            //   label: {
            //     formatter: '{b}: {@2012} ({d}%)'
            //   },
            //   encode: {
            //     itemName: 'trend',
            //     value: moment(Date.now()).format("yyyy-MM-DD"),
            //     tooltip: moment(Date.now()).format("yyyy-MM-DD")
            //   }
            // }
          ]
        }
      },
      tenantPlatformBills: {
        dom: null,
        time: moment(Date.now()).format("yyyy-MM"),
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          }
        },
        option: {
          legend: {},
          tooltip: {
            trigger: 'axis',
            showContent: true
          },
          xAxis: [{
            data: []
          }],
          yAxis: {gridIndex: 0, splitNumber: 10},
          grid: {top: '15%'},
          series: [
            {
              name: '代理收益',
              type: 'line',
              smooth: true,
              seriesLayoutBy: 'row',
              data: []
            },
          ]
        }
      },
    }
  },
  computed: {
    ...
      mapGetters(["userInfo"]),
  },
  mounted() {
    this.init();
  },
  methods: {
    //初始化方法
    init() {
      this.getAgentInfo();
      this.getTenantCensusCount();
      this.getTenantTodayCensusCount();
      this.getTenantAddTrend();
      this.getTenantPlatformBills();
    },
    //删除数组的某个元素
    deleteArrayByObj(arr,attrName,...value){
      value.forEach(ele=>{
        for (let i = 0;i < arr.length; i++){
          const column = arr[i];
          if (ele === column[attrName]){
            arr.splice(i,1);
          }
        }
      });
    },
    //获取租户数据统计
    getTenantCensusCount() {
      //获取租户数量
      getAgentTenantCensusCount().then(res => {
        this.setArrayObjAttrByObj(this.optionTotal.data,"title","商店总数","count",res.data.data.shopCount);
        this.setArrayObjAttrByObj(this.optionTotal.data,"title","收入总额","count",res.data.data.incomeTotal);
      });
    },
    //获取租户当日数据统计
    getTenantTodayCensusCount() {
      //获取租户数量
      getAgentTenantTodayCensusCount().then(res => {
        this.setArrayObjAttrByObj(this.optionToday.data,"title","新增商户","count",res.data.data.shopCount);
        this.setArrayObjAttrByObj(this.optionToday.data,"title","今日收入","count",res.data.data.incomeTotal);
      });
    },
    //设置数组对象属性值
    setArrayObjAttrByObj(arr,attrName,attrValue,key,value){
      arr.forEach(ele=>{
        if(ele[attrName]===attrValue){
          ele[key] = value;
          return;
        }
      });
    },
    //获取租户平台新增趋势
    getTenantAddTrend() {
      let time = moment(this.tenantAddTrend.time);
      //获取租户数量
      getAgentTenantAddTrend({
        time: time.format("yyyy-MM-DD HH:mm:ss")
      }).then(res => {
        //清空内容
        for(let i=0;i<this.tenantAddTrend.option.dataset.source.length;i++){
          this.tenantAddTrend.option.dataset.source[i].splice(1);
        }

        //获取某月总天数
        const day = time.format("yyyy-MM") === moment(Date.now()).format("yyyy-MM") ? Number(moment(Date.now()).format("DD"))
          : new Date(time.format("yyyy"), time.format("MM"), 0).getDate();

        for (let i = 0; i < day; i++) {
          //添加日期X坐标
          const date = time.format("yyyy-MM-DD");
          this.tenantAddTrend.option.dataset.source[0].push(date);

          //添加Y坐标
          //添加商户新增
          this.setAddTrend(res.data.data.shopAddCount,date,"商户新增");

          //加上一天
          time.add(1, 'days');
        }

        //第一次渲染
        if (this.tenantAddTrend.dom === null) {
          this.tenantAddTrend.dom = echarts.init(this.$refs.tenantAddTrend);

          //添加坐标点击
          this.tenantAddTrend.dom.on('updateAxisPointer', (event) => {
            const xAxisInfo = event.axesInfo[0];
            if (xAxisInfo) {
              const dimension = xAxisInfo.value + 1;
              this.tenantAddTrend.dom.setOption({
                series: {
                  id: 'pie',
                  label: {
                    formatter: '{b}: {@[' + dimension + ']} ({d}%)'
                  },
                  encode: {
                    value: dimension,
                    tooltip: dimension
                  }
                }
              });
            }
          });

          //添加饼图点击
          this.tenantAddTrend.dom.on('click', (params) => {
            if (params.componentSubType === "pie") {
              this.$router.push({path: this.tenantAddTrend.option.dataset.path[params.dataIndex]});
            }
          });

          //适应屏幕变化
          window.addEventListener("resize", () => {
            this.tenantAddTrend.dom.resize()
          });
        }

        this.tenantAddTrend.dom.setOption(this.tenantAddTrend.option);
      });
    },
    //设置趋势
    setAddTrend(arr,date,attrName){
      //添加Y坐标
      let count = 0;
      //添加用户新增
      arr.forEach(ele => {
        if (ele.time === date) {
          count = ele.count;
        }
      });
      this.tenantAddTrend.option.dataset.source.forEach(ele=>{
        if(ele[0]===attrName){
          ele.push(count);
        }
      });
    },
    //获取租户代理收益趋势
    getTenantPlatformBills() {
      let time = moment(this.tenantPlatformBills.time);
      //获取租户数量
      getTenantAgentBills({
        time: time.format("yyyy-MM-DD HH:mm:ss")
      }).then(res => {
        //清空内容
        this.tenantPlatformBills.option.xAxis[0].data = [];
        this.tenantPlatformBills.option.series.forEach(ele => {
          ele.data = [];
        });

        //获取某月总天数
        const day = time.format("yyyy-MM") === moment(Date.now()).format("yyyy-MM") ? Number(moment(Date.now()).format("DD"))
          : new Date(time.format("yyyy"), time.format("MM"), 0).getDate();

        for (let i = 0; i < day; i++) {
          //添加日期X坐标
          const date = time.format("yyyy-MM-DD");
          this.tenantPlatformBills.option.xAxis[0].data.push(date);

          //添加金额Y坐标
          this.tenantPlatformBills.option.series[0].data.push(this.getPriceByDate(res.data.data.agentIncomeBills, date));

          //加上一天
          time.add(1, 'days');
        }

        //第一次渲染
        if (this.tenantPlatformBills.dom === null) {
          this.tenantPlatformBills.dom = echarts.init(this.$refs.tenantPlatformBills);
          //适应屏幕变化
          window.addEventListener("resize", () => {
            this.tenantPlatformBills.dom.resize()
          });
        }

        this.tenantPlatformBills.dom.setOption(this.tenantPlatformBills.option);
      });
    },
    /**
     * 根据日期获取金额
     */
    getPriceByDate(array, date) {
      let price = 0;
      array.forEach(ele => {
        if (ele.time === date) {
          price = ele.price;
        }
      });
      return price;
    }
    ,
    getAgentInfo() {
      getAgentInfo({}).then(res => {
        this.agentInfo.accountInfo.agentData = res.data.data;
      });
    },
    changeAccountType(res) {
      switch (res) {
        case 'SETTLE_ACCOUNT':
          return "待结算账户";
        case 'FUND_ACCOUNT':
          return "商户资金账户";
        case 'MARKET_ACCOUNT':
          return "营销账户";
        case 'DIVIDE_ACCOUNT':
          return "待分账账户";
        case 'FEE_ACCOUNT':
          return "手续费账户";
        default:
          return "";
      }
    },
    changeAccountStatus(res) {
      switch (res) {
        case 'AVAILABLE':
          return "可用";
        case 'FROZEN':
          return "冻结";
        case 'FROZEN_CREDIT':
          return "冻结止收";
        case 'FROZEN_DEBIT':
          return "冻结止付";
        case 'CANCELLATION':
          return "销户";
        default:
          return "";
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    rechargeSubmit(row, done) {
      rechargeSubmit(row).then((res) => {
        //回显账单
        this.rechargeTable.data = res.data.data;
        this.rechargeTable.data.remark = row.remark;
        this.rechargeTable.status = true;

        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        done();
      });
    },
  }
}
</script>
<style scoped="scoped">
.recharge-btn {
  color: deepskyblue;
  margin-left: 10px;
}

.recharge-btn:hover {
  cursor: pointer;
  color: red;
  text-decoration: underline;
  font-weight: bold;
  font-size: medium;
}

.mallName {
  font-family: inherit;
  font-size: inherit;
  border-color: #E4E7ED;
  color: #606266;
  margin-left: 15px;
  text-align: center;
}
</style>
