<template>
    <view class="container">
        <view class="main-container">
            <view class="nav-tab"></view>

            <view class="main-body">
                <view class="panel">
                    <view class="stat-pannel flex-row flex-between">
                        <view class="stat-item">
                            <view class="stat-des">
                                <image class="des-icon" src="/static/resource/images/device.png"></image>
                                <text>设备</text>
                            </view>
                            <view class="stat-data">{{ tools.showMoney(device_count) }}</view>
                        </view>
                        <view class="stat-item">
                            <view class="stat-des">
                                <image class="des-icon" src="/static/resource/images/my-yes.png"></image>
                                <text>客户</text>
                            </view>
                            <view class="stat-data">{{ tools.showMoney(user_count) }}</view>
                        </view>
                        <view class="stat-item" style="border: none">
                            <view class="stat-des">
                                <image class="des-icon" src="/static/resource/images/b-j.png"></image>
                                <text>今日报警</text>
                            </view>
                            <view class="stat-data">{{ tools.showMoney(alarm_count) }}</view>
                        </view>
                    </view>
                    <view class="flex-row flex-between">
                        <view class="chart-pannel topbar-pannel">
                            <view class="chart-desc">设备地区排行</view>
                            <view class="chart-container">
                                <ec-canvas id="mychart-dom-top-bar" canvas-id="mychart-top-bar" :ec="ecTopBar"></ec-canvas>
                            </view>
                        </view>
                        <view class="chart-pannel percent-pannel">
                            <view class="chart-desc">设备状态</view>
                            <view class="chart-container">
                                <!-- <ec-canvas id="mychart-dom-percent-pie" canvas-id="mychart-percent-pie" :ec="ecPercentPie"></ec-canvas> -->
                            </view>
                        </view>
                    </view>
                    <view class="chart-pannel">
                        <view class="flex-row flex-between">
                            <view class="chart-desc">每月设备增长数</view>
                        </view>
                        <view class="chart-container">
                            <ec-canvas id="mychart-dom-dynamics" canvas-id="mychart-dynamics" :ec="ecDynamics"></ec-canvas>
                        </view>
                    </view>
                    <view class="chart-pannel">
                        <view class="flex-row flex-between">
                            <view class="chart-desc">实时报警</view>
                            <view class="chart-desc" @tap="loadAlarmAll">
                                <image class="fresh-icon" src="/static/resource/images/fr-icon.png"></image>
                                <text>刷新</text>
                            </view>
                        </view>
                        <view>
                            <van-cell-group>
                                <van-cell :label="tools.formatTime(item.send_time)" clickable v-for="(item, index) in alarmlist" :key="index">
                                    <view slot="title">
                                        <view class="van-cell-text">{{ item.macid }}</view>
                                    </view>

                                    <view>
                                        <view class="van-cell-text">{{ item.alarm_desc }}</view>
                                        <view class="van-cell-text"></view>
                                    </view>
                                </van-cell>
                            </van-cell-group>
                            <!-- i-load-more tip="{{orderLoading?'正在加载 ...':'没有更多信息啦'}}" loading="{{isLoading}}" / -->
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>
<script module="tools" lang="wxs" src="@/pages/common/wxs/tools.wxs"></script>
<script>
// import ecCanvas from './ec-canvas';
import iLoadMore from '@/component/iview/load-more/index';
// pages/index/index.js
var config = require('../../common/config.js');
var http = require('../../common/http.js');
var common = require('../../common/common.js');
var storage = require('../../common/storage.js');
// import * as echarts from 'ec-canvas/echarts';
var areaList = require('../../common/area.js');
function LocationCodeToName(code, tail = 3, suffix = true) {
    if (!code) {
        return '';
    }
    if (code < 100) {
        code *= 10000;
    }
    if (code < 10000) {
        code *= 100;
    }
    var area = [];
    var province = areaList.province_list[code.toString().substring(0, 2) + '0000'];
    if (province) {
        if (!suffix) {
            province = province.replace('省', '').replace('市', '').replace('特别行政区', '').replace('自治区', '').replace('壮族', '').replace('回族', '').replace('维吾尔', '');
        }
        area.push(province);
    }
    var city = areaList.city_list[code.toString().substring(0, 4) + '00'];
    if (city && city != area[area.length - 1]) {
        area.push(city);
    }
    var county = areaList.county_list[code];
    if (county && county != area[area.length - 1]) {
        area.push(county);
    }
    return area.slice(-tail).join(' ');
}
export default {
    components: {
        // ecCanvas,
        iLoadMore
    },
    data() {
        return {
            ecTopBar: {
                lazyLoad: true
            },
            ecPercentPie: {
                lazyLoad: true
            },
            ecDynamics: {
                lazyLoad: true
            },
            message: '0',
            statisList: {},
            selectShop: {
                id: 0,
                name: '',
                head: ''
            },
            timeUnit: 'date',
            selectTime: new Date().getTime(),
            formatSelectTime: common.DateFormat(new Date(), 'yyyy年MM月dd日'),
            totalDynamicsData: {},
            shopDynamicsData: {},
            topNum: 5,
            showNum: 20,
            typeTitle: '营收',
            typeName: 'income',
            orderType: true,
            orderList: [],
            orderLoading: false,
            start_page: 1,
            limit_page: 10,
            orderNum: 0,
            orderTotal: 0,
            device_count: 0,
            user_count: 0,
            alarm_count: 0,
            unread_alarm_count: 0,
            areaList: [],
            deviceStatis: {},
            deviceMonthly: {},
            alarmlist: []
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.loadUserInfo();
        this.loadStatisTop();
        this.loadStatisArea();
        this.loadStatisDevice();
        this.loadDeviceMonthly();
        this.loadAlarmAll();
        //
    },
    onReady: function () {
        console.log('ready');
        //this.drawChart([{ value: '', year: '', country: '' }])
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        console.log('pull');
        this.loadStatisTop();
        this.loadStatisArea();
        this.loadStatisDevice();
        this.loadDeviceMonthly();
        this.loadAlarmAll();
    },
    onReachBottom: function () {
        /*if (this.data.orderLoading) return
  this.setData({
    orderLoading: true
  })
  this.data.start_page++*/
        //common.loading()
        //this.loadOrderList()
    },
    methods: {
        loadStatisTop: function () {
            const that = this;
            http.postApi(config.API_STATIS_TOP, {}, function (resp) {
                uni.stopPullDownRefresh();
                if (resp.data.code === 200) {
                    that.setData({
                        device_count: resp.data.data.device_count,
                        user_count: resp.data.data.user_count,
                        alarm_count: resp.data.data.alarm_count,
                        unread_alarm_count: resp.data.data.unread_alarm_count
                    });
                } else {
                    common.simpleToast(resp.data.msg);
                }
            });
        },

        loadStatisArea: function () {
            const that = this;
            http.postApi(
                config.API_AREA_STATIS,
                {
                    scope: 0
                },
                function (resp) {
                    uni.stopPullDownRefresh();
                    if (resp.data.code === 200) {
                        that.setData({
                            areaList: resp.data.data.list
                        });
                        that.initTopBar();
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        loadStatisDevice: function () {
            const that = this;
            http.postApi(config.API_DEVICE_STATIS, {}, function (resp) {
                uni.stopPullDownRefresh();
                if (resp.data.code === 200) {
                    that.setData({
                        deviceStatis: resp.data.data
                    });
                    that.initPercentPie();
                } else {
                    common.simpleToast(resp.data.msg);
                }
            });
        },

        loadDeviceMonthly: function () {
            const that = this;
            http.postApi(config.API_DEVICE_MONTH, {}, function (resp) {
                uni.stopPullDownRefresh();
                if (resp.data.code === 200) {
                    that.setData({
                        deviceMonthly: resp.data.data.list
                    });
                    that.initDynamicsChart();
                } else {
                    common.simpleToast(resp.data.msg);
                }
            });
        },

        loadAlarmAll: function () {
            const that = this;
            http.postApi(
                config.API_ALARM_ALL,
                {
                    status: 0,
                    size: 20
                },
                function (resp) {
                    uni.stopPullDownRefresh();
                    if (resp.data.code === 200) {
                        that.setData({
                            alarmlist: resp.data.data.list
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        initTopBar() {
            // this.topBarComponent = this.zpSelectComponent('#mychart-dom-top-bar');
            // this.topBarComponent.init((canvas, width, height) => {
            //     const chart = echarts.init(canvas, null, {
            //         width: width,
            //         height: height
            //     });
            //     this.topBarChart = chart;
            //     this.setTopBarOptions();
            //     return chart;
            // });
        },

        setTopBarOptions() {
            // this.topBarChart.setOption({
            //     color: ['#409EFF'],
            //     xAxis: {
            //         type: 'value',
            //         axisLine: {
            //             show: false
            //         },
            //         axisLabel: {
            //             show: false
            //         },
            //         axisTick: {
            //             show: false
            //         },
            //         splitLine: {
            //             show: false
            //         }
            //     },
            //     grid: {
            //         top: 0,
            //         left: '5%',
            //         right: '2%',
            //         bottom: '2%',
            //         containLabel: true
            //     },
            //     yAxis: {
            //         type: 'category',
            //         axisLine: {
            //             show: false
            //         },
            //         axisLabel: {
            //             show: false
            //         },
            //         axisTick: {
            //             show: false
            //         },
            //         splitLine: {
            //             show: false
            //         },
            //         data: this.areaList
            //             .filter((p) => p.area != 0)
            //             .sort((a, b) => {
            //                 return b.count - a.count;
            //             })
            //             .slice(0, 8)
            //             .map((p) => LocationCodeToName(p.area, 1, false))
            //             .reverse()
            //     },
            //     series: [
            //         {
            //             name: '',
            //             smooth: true,
            //             type: 'bar',
            //             label: {
            //                 normal: {
            //                     show: true,
            //                     fontSize: 10,
            //                     position: 'insideLeft',
            //                     formatter: (obj) => {
            //                         var name = obj.name;
            //                         if (name.length > 6) {
            //                             name = name.slice(0, 5) + '..';
            //                         }
            //                         var value = obj.value;
            //                         if (value >= 10000) {
            //                             value = (value / 10000).toFixed(1) + '万';
            //                         }
            //                         return name + ':' + value;
            //                     } //'{b}: {c}'
            //                 }
            //             },
            //             itemStyle: {
            //                 color: '#409EFF'
            //             },
            //             data: this.areaList
            //                 .filter((p) => p.area != 0)
            //                 .sort((a, b) => {
            //                     return b.count - a.count;
            //                 })
            //                 .slice(0, 8)
            //                 .map((p) => p.count)
            //                 .reverse(),
            //             animationDuration: 2800,
            //             animationEasing: 'cubicInOut'
            //         }
            //     ]
            // });
        },

        initPercentPie() {
            // this.percentPieComponent = this.zpSelectComponent('#mychart-dom-percent-pie');
            // this.percentPieComponent.init((canvas, width, height) => {
            //     const chart = echarts.init(canvas, null, {
            //         width: width,
            //         height: height
            //     });
            //     this.percentPieChart = chart;
            //     this.percentPieConvertData = {};
            //     this.setPercentPieOptions();
            //     return chart;
            // });
        },

        setPercentPieOptions() {
            this.percentPieChart.setOption({
                series: [
                    {
                        name: '设备',
                        type: 'pie',
                        radius: '80%',
                        data: [
                            {
                                value: this.deviceStatis.immobility_count,
                                name: '静止',
                                itemStyle: {
                                    color: '#409EFF'
                                }
                            },
                            {
                                value: this.deviceStatis.driving_count,
                                name: '行驶',
                                itemStyle: {
                                    color: '#67C23A'
                                }
                            },
                            {
                                value: this.deviceStatis.offline_count,
                                name: '离线',
                                itemStyle: {
                                    color: '#E6A23C'
                                }
                            },
                            {
                                value: this.deviceStatis.expire_count,
                                name: '到期',
                                itemStyle: {
                                    color: '#909399'
                                }
                            },
                            {
                                value: this.deviceStatis.disabled_count,
                                name: '未启用',
                                itemStyle: {
                                    color: '#F56C6C'
                                }
                            }
                        ]
                            .filter((p) => p.value != 0)
                            .sort((a, b) => {
                                return a.value - b.value;
                            }),
                        label: {
                            position: 'outer',
                            alignTo: 'none',
                            bleedMargin: 5
                        },
                        roseType: 'radius',
                        labelLine: {
                            smooth: 0.2,
                            length: 0,
                            length2: 5
                        },
                        animationType: 'scale',
                        animationEasing: 'elasticOut',
                        animationDelay: function (idx) {
                            return Math.random() * 200;
                        }
                    }
                ]
            });
        },

        initDynamicsChart() {
            // this.dynamicsComponent = this.zpSelectComponent('#mychart-dom-dynamics');
            // this.dynamicsComponent.init((canvas, width, height) => {
            //     const chart = echarts.init(canvas, null, {
            //         width: width,
            //         height: height
            //     });
            //     this.dynamicsChart = chart;
            //     this.setDynamicsOptions();
            //     return chart;
            // });
        },

        setDynamicsOptions() {
            this.dynamicsChart.setOption({
                color: ['#67C23A'],
                grid: {
                    left: '3%',
                    right: '3%',
                    top: '5%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: this.deviceMonthly.map((p) => p.time).reverse(),
                    axisTick: {
                        alignWithLabel: true
                    }
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '设备增长',
                        type: 'line',
                        data: this.deviceMonthly.map((p) => p.count).reverse(),
                        smooth: true
                    }
                ]
            });
        },

        loadUserInfo: function () {
            const userInfo = storage.getUserInfo();
            if (!userInfo) {
                http.postApi(config.API_USER_INFO, {}, (resp) => {
                    if (resp.data.code === 200) {
                        //this.setUserInfo(resp.data.data)
                        storage.setUserInfo(resp.data.data);
                        //this.loadDynamicsData()
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            } else {
                //this.setUserInfo(userInfo)
                //this.loadDynamicsData()
            }
        },

        setUserInfo(userInfo) {
            var selectShop = {};
            selectShop.id = userInfo.userInfo.user_id;
            selectShop.name = userInfo.userInfo.shop_name;
            selectShop.head = userInfo.userInfo.shop_head;
            this.setData({
                selectShop: selectShop
            });
        },

        formatTime(time) {
            switch (this.timeUnit) {
                case 'date':
                    return common.DateFormat(new Date(time), 'yyyy年MM月dd日');
                case 'month':
                    return common.DateFormat(new Date(time), 'yyyy年MM月');
                case 'year':
                    return common.DateFormat(new Date(time), 'yyyy年');
                default:
                    return '';
            }
        },

        bindTimeSelectDate() {
            this.setData({
                timeUnit: 'date'
            });
            this.setData({
                formatSelectTime: this.formatTime(this.selectTime)
            });
            this.totalDynamicsData = {};
            this.shopDynamicsData = {};
            this.loadDynamicsData();
            this.refreshLoadOrderList();
        },

        bindTimeSelectMonth() {
            this.setData({
                timeUnit: 'month'
            });
            this.setData({
                formatSelectTime: this.formatTime(this.selectTime)
            });
            this.totalDynamicsData = {};
            this.shopDynamicsData = {};
            this.loadDynamicsData();
            this.refreshLoadOrderList();
        },

        bindTimeSelectYear() {
            this.setData({
                timeUnit: 'year'
            });
            this.setData({
                formatSelectTime: this.formatTime(this.selectTime)
            });
            this.totalDynamicsData = {};
            this.shopDynamicsData = {};
            this.loadDynamicsData();
            this.refreshLoadOrderList();
        },

        bindTimeSelectChange(event) {
            this.setData({
                selectTime: new Date(event.detail.value).getTime(),
                formatSelectTime: this.formatTime(new Date(event.detail.value).getTime())
            });
            this.totalDynamicsData = {};
            this.shopDynamicsData = {};
            this.loadDynamicsData();
            this.refreshLoadOrderList();
        },

        bindOrderSelectTotal() {
            this.setData({
                orderType: true
            });
            this.refreshLoadOrderList();
        },

        bindOrderSelectShop() {
            this.setData({
                orderType: false
            });
            this.refreshLoadOrderList();
        },

        refreshLoadOrderList: function () {
            if (this.orderLoading) {
                return;
            }
            this.setData({
                orderLoading: true
            });
            this.orderList = [];
            this.limit_page = 10;
            this.start_page = 1;
            this.loadOrderList();
        },

        loadOrderList: function () {
            var time = this.timeSelect();
            http.postApi(
                config.API_INCOME_USER,
                {
                    limit: this.limit_page,
                    page: this.start_page,
                    shop_id: this.orderType ? '' : this.selectShop.id,
                    begin_date: common.formatTime(time.begin_date / 1000),
                    end_date: common.formatTime(time.end_date / 1000)
                },
                (resp) => {
                    uni.stopPullDownRefresh();
                    if (resp.data.code === 200) {
                        let orderList = this.orderList;
                        orderList.push.apply(orderList, resp.data.data.statisList.list);
                        this.setData({
                            orderList: orderList,
                            orderNum: resp.data.data.statisList.total,
                            orderTotal: resp.data.data.statisList.sum,
                            orderLoading: false
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        bindOrderClick(event) {
            uni.navigateTo({
                url: '/pages/searchOrder/searchOrder?type=2&search=' + event.target.dataset.phone
            });
        }
    }
};
</script>
<style>
@import './index.css';
</style>
