<template>
	<div class="index-wrap">
        
	</div>
</template>
<script>
import { findOneUser} from "@/api/login";
import * as echarts from 'echarts';
export default {
	name: "homeIndex",
	components: {
		
  	},
    watch: {
        drowMenuShow(n){
            var body = document.getElementsByTagName('body')[0]
            if(n){
                body.classList.add('over-hidden')
            } else {
                body.classList.remove('over-hidden')
            }
        },
        activeKey(n){
            this.loadChildren()
        }
    },
    computed:{
        selcommunityName(){
            if(this.selcommunity){
                if(this.selcommunity.hospital === ''){
                    var item = this.townList[this.activeKey]
                    return item.town === ''? "全部" : item.townName
                } else {
                    return this.selcommunity.hospitalName
                }
            } 
            return "全部"
        }
    },
  	data() {
    	return {
            medicineBag:'1',
            medicineData:false,
            medicineShow:true,
            sales:true,
            prescriptionBag:'1',
            salesBag:'1',
            count:[],
            date:[],
            amount:'- -',
			overview:{
                total:'- -', // 总台数
                noOnlineTotal:'- -', // 不在线数
                onlineRate:'- -', // 在线率
                onlineTotal:'- -', // 在线台数
            },
            maintain:{
                hcWaringTotalNum:'- -', // 温湿度异常警告
                noOnlineTotal1WithUserId:'- -', // 不在线数
                noGetDrugNum:'- -', // 待取药订单数
                addTotal:'- -', // 缺货设备数
            },
            shippingType:{
                saomaTotal:'- -',
                total:'- -',
                yibaoTotal:'- -'
            },
            prescriptionStatics:{
                total:'- -',
                drugTotal:'- -'
            },

            drowMenuShow: false,
            townList: [],
            communityList: [],
            selcommunity: '',
            activeKey: 0,
            defaultOption: [
                { townName: '全部', town: "", children: [{hospital: '', hospitalName: '全部'}] },
            ],
            first: false
    	}
  	},
	created(){
        this.first = true
		this.refreshData()
        this.getOrgList()
        console.log('this.$store.user.state',this.$store.state.user.curRoleCode)
        if(this.$store.state.user.curRoleCode =='replenisher'){
            this.medicineShow = false;
            this.sales = false;
        }
    },
    activated(){
        if(this.first){
            this.first = false
        } else {
            this.refreshData()
        }
    },
    mounted(){
        this.echartsData();
    },
  	methods: {
        // 设备概况 运营数据
		countall(){
            var p = this.getTownParams()
			medicineAbinetApi
				.countAllDevice(p)
				.then(res=>{
                    // console.log('countall', res);
                    this.overview = res.obj.overview;
                    this.maintain = res.obj.maintain;
				})
				.catch(err=>{
					console.error(err)
				})
        },
        //跳转
        gotoDevice(active){
            var p = this.getTownUrlParams()
            p.active = active
            this.$router.push({
                path: '/device/index',
                query: p
            })
        },
        // 取药次数
        medicine(){
            var p = this.getTownParams()
            p.day = this.medicineBag
            console.log('medicine', p)
            medicineAbinetApi
				.getmedicine(p)
				.then(res=>{
                    console.log('medicine', res)
                    this.medicineData = true;
                    this.shippingType = res.obj;
				})
				.catch(err=>{
                    console.error(err)
                    this.medicineData = true;
				})
        },
        // 电子处方单
        prescriptions(){
            var p = this.getTownParams()
            p.day = this.prescriptionBag
            medicineAbinetApi
				.getprescriptions(p)
				.then(res=>{
                    // console.log('prescriptions', res)
                    this.prescriptionStatics = res.obj;
				})
				.catch(err=>{
					console.error(err)
				})
        },
        // 取药时间查询
        medicineTime(val){
            if(this.medicineData){
                if(val == '全部'){
                    this.medicineBag = '';
                    console.log('全部')
                }else{
                    this.medicineBag = val;
                    console.log('1,3,7,9')
                }
                this.medicineData = false;
                this.medicine();
                
            }
        },
        // 电子处方单查询
        prescriptionTime(val){
            if(val == '全部'){
                this.prescriptionBag = '';
                this.prescriptions();
                console.log('全部')
            }else{
                this.prescriptionBag = val;
                this.prescriptions();
                console.log('1,3,7,9')
            }
        },
        // 销售额查询
        salesTime(val){
            if(val == '全部'){
                this.salesBag = '';
                console.log('全部')
            }else{
                this.salesBag = val;
                console.log('1,3,7,9')
            }
            this.echartsData();
        },
        echartsData(){
            if(this.sales){
                var p = this.getTownParams()
                p.day = this.salesBag
                medicineAbinetApi
                    .getechartsData(p)
                    .then(res=>{
                        // console.log('echartsData', res);
                        this.amount = res.obj.amount;
                        this.count = res.obj.amountdateList.map((item) =>{
                            return item.count
                        });
                        this.date = res.obj.amountdateList.map((item) =>{
                            return item.date
                        });

                        // 基于准备好的dom，初始化echarts实例
                        var myChart;
                        if (myChart != null && myChart != "" && myChart != undefined){
                            // chartDom.clear();
                            myChart.dispose();
                            // document.getElementById('sales-chart').innerHTML = '';
                        }
                        var chartDom = document.getElementById('sales-chart');
                        myChart = echarts.init(chartDom);
                        var option;

                        option = {
                            grid:{
                                left: '3%',
                                right: '4%',
                                bottom: '2%',
                                top:'5%',
                                containLabel: true
                            },
                            tooltip: {
                                trigger: 'axis'
                            },
                            xAxis: {
                                type: 'category',
                                boundaryGap: false,
                                data: this.date,
                                axisTick:{
                                    show:false, // X轴刻度隐藏
                                },
                                axisLabel:{
                                    fontSize:'8', // X轴文字字体大小
                                }
                            },
                            yAxis: {
                                type: 'value'
                            },
                            series: [
                                {
                                data: this.count,
                                type: 'line'
                                }
                            ]
                        };
                        // if (myChart != null && myChart != "" && myChart != undefined) {
                        //     myChart.dispose();
                        // }
                        option && myChart.setOption(option);
                    })
                    .catch(err=>{
                        console.error(err)
                    })
            }
        },

        refreshData(){
            this.countall();
            this.medicine();
            this.prescriptions();
        },
        getTownParams(){
            var p = {
                userId: this.user.id,
            }
            if(this.selcommunity){
                if(this.selcommunity.hospital===''){
                    var item = this.townList[this.activeKey]
                    if(item.town === ''){
                        p.level = ''; 
                        p.area = '';
                    } else {
                        p.level = 2; 
                        p.area = item.town;
                    }
                } else {
                    p.level = 3; //(name = "level", value = "1、市级、2、区级、3、社区", required = false)
                    p.area = this.selcommunity.hospital
                }
            }
            return p
        },

        getOrgList(){
            findOneUser({
                id: this.user.id
            }).then(async res => {
                // "saasAdmin"： "管理员"； regionAdmin" "区域管理员" ; communityAdmin "社区管理员" ; "replenisher"： "补货员"
                var role = this.user.curRoleCode
                var userArea = res.obj.userArea
                var townList = [].concat(this.defaultOption)
                if(role=='communityAdmin' || role=="replenisher"){
                    var g = _.groupBy(userArea, 'town')
                    for(var k in g){
                        var tmp = JSON.parse(JSON.stringify(g[k][0]))
                        tmp.children = [{hospital: '', hospitalName: '全部'}].concat( g[k])
                        townList.push(tmp)
                    }
                    this.townList = townList
                } else {
                    if(role == 'regionAdmin'){
                        userArea.forEach(v => {
                            v.children = []
                        });
                        this.townList = townList.concat(userArea) 
                    } else if(role=='saasAdmin'){
                        await medicineAbinetApi
                            .baseTownList({ filters: "city=350200"})//写死厦门市
                            .then(res => {
                                console.log('baseTownList', res)
                                if (res.status == 200) {
                                    var detailModelList = res.detailModelList;
                                    detailModelList.forEach((item) => {
                                        item.town = item.code
                                        item.townName = item.name
                                        item.children = [];
                                    });
                                    this.townList = townList.concat(detailModelList) 
                                }
                            });
                    }
                }
                this.loadChildren()
            });
        },
        async loadChildren(){
            var item = this.townList[this.activeKey]
            if(!item.children || !item.children.length){
                await medicineAbinetApi
                    .findOrgList({ code: item.town, paeg: 1, pageSize: 999 })
                    .then(res => {
                        console.log('findOrgList', res)
                        if (res.status == 200) {
                            res.detailModelList.forEach(v=>{
                                v.hospitalName = v.name
                                v.hospital = v.code
                            })
                            item.children = [{hospital: '', hospitalName: '全部'}] .concat (res.detailModelList)
                        }
                    })
                    .catch(err=>{
                        item.children = []
                    })
            }

            this.communityList = item.children
        },
        onSelect(item){
            console.log('this.selcommunity', item)
            this.selcommunity = item;
            this.drowMenuShow = false;
            this.refreshData()
        },
        gotoDeviceList(networkStatus){
            var p = this.getTownUrlParams()
            p.networkStatus = networkStatus
            this.gotoUrl('/device/index', p)
        },
        toOrderPage(){
            var p = this.getTownUrlParams()
            p.sellState = 0
            this.gotoUrl('/order/list', p)
        },
        getTownUrlParams(){
            var p = {}
            if(this.selcommunity){
                if(this.selcommunity.hospital===''){
                    var item = this.townList[this.activeKey]
                    if(item.town === ''){

                    } else {
                        p.town = item.town;
                        p.townName = item.townName;
                    }
                } else {
                    var item = this.townList[this.activeKey]
                    p.town = item.town;
                    p.townName = item.townName;
                    p.hospital = this.selcommunity.hospital
                    p.hospitalName = this.selcommunity.hospitalName
                }
            }
            return p 
        }
    },
}
</script>
<style lang="scss" scoped>
@import "./scss/index.scss";
</style>