<template>
    <view class="index-container">
		<view class="ic-header">
			<view class="ih-bar" :style="'padding-top:'+headerInfo.statusBarHeight+'px'">
				<view class="ib-title-bar" :style="titleStyle">
					<image class="itb-back-icon" @click="goBack()" src="../../static/images/arrow_back.png"></image>
					<text>欧轩智能商家助手</text>
				</view>
			</view>
			<store-name :theme="'light'"></store-name>
			<view class="ih-container">
				<view class="ic-title">欧轩智能中控</view>
				<view class="ic-info">
					<view class="ii-veiw">
						<view class="iv-view">
							<veiw class="iv-txt">设备id：{{ curStoreInfo.device_name || "-" }}</veiw>
							<view class="iv-btn" @click="copyDeviceID">复制</view>
						</view>
						<view class="iv-view">
							<veiw class="iv-txt">状态：{{ deviceInfo.Online == 1 ? '在线' : '离线' }}</veiw>
						</view>
					</view>
					<view class="ii-veiw">
						<view class="iv-view">
							<veiw class="iv-txt">最后上线时间：{{ deviceInfo.LastOfflineTimeStr || "-" }}</veiw>
						</view>
						<view class="iv-view" @click="goTimingList">
							<image class="iv-img" src="../../static/images/icon_clock.png" mode="aspectFit"></image>
							<veiw class="iv-txt" >定时列表</veiw>
						</view>
					</view>
				</view>
				<view 
					v-if="oxAcInfo.extension&&oxAcInfo.extension.switch_device_name"
					class="ic-btn" 
					hover-class="hover-active" 
					@click="restartBtn"
				>重启</view>
			</view>
		</view>
		
        <view class="ic-section">
            <view class="is-list">
				<block v-for="(e,i) in tabArr" :key="i">
					<view class="il-item" @click="routeTo(e)" v-if="isShowHardwareTab(e)">
						<view><image mode="aspectFit" :src="getImgPath(e.id) || ''"></image></view>
						<view>{{e.name || ''}}</view>
					</view>
				</block>
                
            </view>
        </view>
    </view>
</template>

<script>
import util from '../../../../utils/util';
import store_name from '../../components/store_name/store_name';
import deviceServer from '../../js/device_server';
import deviceApi from '../../js/device_api';

const rootPage = '/subpackage/device'
const tabArr = [
    {id: 1, name: '照明', path: `/pages/switch_manage/switch_manage`},
    {id: 2, name: '空调', path: `/pages/switch_manage/switch_manage`},
    {id: 3, name: '风扇', path: `/pages/switch_manage/switch_manage`},
    {id: 4, name: '门禁', path: `/pages/switch_manage/switch_manage`},
    {id: 5, name: '门闸', path: `/pages/switch_manage/switch_manage`},
    // {id: 6, name: '平板', path: `/pages/switch_manage/switch_manage`},
    {id: 7, name: '售货柜', path: `/pages/device_manage/device_manage`},
    {id: 8, name: '租售柜', path: `/pages/device_manage/device_manage`},
    {id: 9, name: '储物柜', path: `/pages/device_manage/device_manage`},
    {id: 10, name: '咖啡机', path: `/pages/device_manage/device_manage`},
    {id: 11, name: '水阀', path: `/pages/switch_manage/switch_manage`},
    // {id: 12, name: '互动设备', path: `/pages/switch_manage/switch_manage`},
    // {id: 13, name: '监控', path: `/pages/switch_manage/switch_manage`},
    {id: 14, name: '音响', path: `/pages/audio_manage/audio_manage`}, //audio_manage
    // {id: 15, name: '机器人', path: ``},
    // {id: 16, name: '租球机', path: ``},
    // {id: 17, name: '窗帘', path: `/pages/switch_manage/switch_manage`},
	{id: 18, name: '路由器', path: `/pages/switch_manage/switch_manage`},
	{id: 19, name: '物联卡', path: `/pages/switch_manage/switch_manage`},
];
import { mapState } from 'vuex'
export default {
    components: {
        'store-name': store_name
    },
	computed: {
	    ...mapState({
	        storeList: state => state.device.storeList,
	        curStoreInfo: state => state.device.curStoreInfo,
	    }),
		// 
		showHardwareIdLs(){
			let { hardwareTypeList } = this;
			let _ls = hardwareTypeList || [];
			let _fls = _ls.filter(ele => ele.stadium_has);
			let _idLs = _fls.map(el => el.mini_local_menu_id);
			return _idLs || [];
		},
		titleStyle(){
			let { statusBarHeight, titleBarHeight } = this.headerInfo;
			let _styleStr = `
				line-height:${titleBarHeight}px;
			`
			return _styleStr
		},
	},
	watch: {
		curStoreInfo(nw, od){
			this.getOuxuanacInfo(nw.device_name);
			this.getHardwareTypeList();
		}
	},
    data(){
        return {
            tabArr: [],
			deviceInfo:"",
			hardwareTypeList: [],
			headerInfo: {
				statusBarHeight: 0,
				titleBarHeight: 0
			},
			oxAcInfo: {},
		}
    },
    async onLoad(options){
        try{
            util.showLoad();
            let _brandInfo = await this.$store.dispatch('getBrandInfo');
            await this.$store.dispatch('getStoreList', { stadium_id: +options.stadium_id || '' });
			let { curStoreInfo } = this;
			this.updateAC();
			await this.getHardwareTypeList();
			await this.getOuxuanacInfo(curStoreInfo.device_name);
            util.hideLoad();
        }catch(err){
			console.warn('onLoad err--->', err)
            util.hideLoad();
        }
        
    },
	onShow() {
		this.updateAC() // 更新中控信息
	},
	onReady() {
		this.initSysBarInfo();
	},
    methods: {
		
		initSysBarInfo(){
			let wxBtn = uni.getMenuButtonBoundingClientRect();
			let sysInfo = uni.getSystemInfoSync();
			let statusBarHeight = sysInfo.statusBarHeight || 0;
			let titleBarHeight = (wxBtn?.height || 0) + (((wxBtn?.top || 0) - statusBarHeight) *2);
			this.headerInfo = {
				statusBarHeight,
				titleBarHeight,
			}
		},
		isShowHardwareTab(e){
			let { showHardwareIdLs } = this;
			return showHardwareIdLs.includes(e.id);
		},
		getHardwareTypeList(){
			let { curStoreInfo } = this;
			this.tabArr = [];
			return deviceServer.get({
			    url: deviceApi.hardwareTypeList,
			    data: { stadium_id: curStoreInfo.id },
			    failMsg: '加载设备类型列表失败！'
			})
			.then(res=>{
				let _ls = res || [];
				if(_ls&&_ls.length)this.tabArr = tabArr;
			    return this.hardwareTypeList = _ls || [];
			})
		},
		copyDeviceID(){
			let that = this
			uni.setClipboardData({
			    data: that.curStoreInfo.device_name,
			    success: function () {
					util.showNone(`复制成功！`);
			        console.log('复制成功',that.curStoreInfo.device_name);
			    }
			});
		},
		updateAC(){
			if(!this.curStoreInfo.device_name)return
			util.showLoad();
			// 	id:"00-de-47-e9-3a-fc"
			deviceServer.get({
			    url: deviceApi.acUpdate,
			    data: {id:this.curStoreInfo.device_name},
			    failMsg: '加载失败！'
			})
			.then(res=>{
			    util.hideLoad()
			    this.deviceInfo = res
				uni.setStorageSync("deviceInfo",res)
			})
			.catch(util.hideLoad)
		},
		goBack(){
			uni.navigateBack({
				delta:1
			})
		},
		goTimingList(){
			let timing_list = "/subpackage/device/pages/timing/timing_list"
			util.routeTo(`${timing_list}`, 'nT');
		},
        getImgPath(id){
            if(!id)return '';
            return `/subpackage/device/static/images/devices/${id || 14}.png`
        },
        routeTo(e){
			let { curStoreInfo } = this;
            if(e.path == '')return util.showNone('开发中！');
			util.routeTo(`${rootPage}${e.path}?sid=${e?.id || ''}&stadium_id=${curStoreInfo?.id || ''}`, 'nT');
        },
		// 获取中控重启参数
		getOuxuanacInfo(id_ouxuanac){
			if(!id_ouxuanac){
				console.log('中控id不存在 id_ouxuanac ->', id_ouxuanac);
				return Promise.resolve([]);
			}
			return deviceServer.get({
			    url: deviceApi.ouxuanacList,
			    data: { id_ouxuanac },
			    failMsg: '加载中控信息失败！'
			})
			.then(res=>{
				console.log('id_ouxuanac', res);
				this.initOuxuancInfo({ oxacLs: res?.list || [], id_ouxuanac });
				return res
			})
		},
		// 初始化中控信息
		initOuxuancInfo({ oxacLs, id_ouxuanac }){
			this.oxAcInfo = oxacLs.find(e=>e.id_ouxuanac == id_ouxuanac) || {};
		},
		restartBtn(){
			let { curStoreInfo, oxAcInfo } = this;
			let _dvName = oxAcInfo?.extension?.switch_device_name;
			this.operateReq({ deviceName: _dvName, op: 'off', })
			.then(code=>{
				if(code === 0){
					setTimeout(_=>{ this.operateReq({ deviceName: _dvName, op: 'on', }) }, 1000)
				}
			})
			
			// util.showNone('调试开发中！');
		},
		// 操作接口请求
        operateReq({deviceName, op, isTip=true}){
			// let _query = {
			// 	is_delay: true,
			// 	name: "gate-switch",
			// 	queue_group: "gate",
			// 	value: { tcp: "", cid: "", op},
			// 	device: deviceName,
			// 	hardware_id: "",
			// }
			let _query = {
				"data": {
						"name": "gate-switch", 
						"value":{
							"op": op
						},
				"is_async":true
				},
				"device": deviceName
			}
            util.showLoad();
            return deviceServer.post({
                url: deviceApi.ouxuanac,
                data: _query,
                isDefaultGet: false,
            })
            .then(res=>{
                util.hideLoad();
                if(res.data.code == 0){
                    if(isTip)util.showNone(res.data.message || '操作成功！');
					return 0
                }else{
                    util.showModal({
						title: '提示',
						content: res.data.message || '操作失败！',
						showCancel: false,
					})
					return 1
                }
            })
            .catch(err=>{
				util.hideLoad();
				return Promise.reject(err);
			})
        },
    }
}
</script>

<style lang="scss">
    @import '~style/public.scss';
	.ic-header{
		width: 100%;
		height: 620upx;
		background-image: linear-gradient(160deg, #89D499 0%, #33CCA9 81%);
		.ih-bar{
			.ib-title-bar{
				position: relative;
				padding: 0 12px;
				text-align: center;
				font-size: 19px;
				font-weight: 500;
				color: #fff;
				.itb-back-icon{
					position: absolute;
					left: 12px;
					top: 50%;
					margin-top: -10px;
					width: 20px;
					height: 20px;
				}
			}
		}
		.ih-container{
			padding: 4upx 50upx 38upx;
			.ic-title{
				text-align: center;
				line-height: 56upx;
				font-size: 40upx;
				font-weight: 500;
				color: #1A1A1A;
			}
			.ic-info{
				margin-top: 42upx;
				.ii-veiw{
					@include centerFlex(space-between);
					&:not(:first-child){
						margin-top: 14upx;

					}
					.iv-view{
						min-width: 30%;
						@include centerFlex(flex-start);
						.iv-img{
							flex-shrink: 0;
							flex-grow: 0;
							margin-right: 8upx;
							height: 24upx;
							width: 24upx;
						}
						.iv-txt{
							font-size: 24upx;
							line-height: 34upx;
							color: #1A1A1A;
							@include textHide(1);
						}
						.iv-btn{
							flex-shrink: 0;
							margin-left: 14upx;
							line-height: 28upx;
							font-size: 20upx;
							padding: 2upx 6upx;
							border-radius: 4upx;
							background-color: rgba($color: #ADFF2C, $alpha: .5);
							color: $themeColor;
							
						}
						&+.iv-view{
							@include centerFlex(flex-end);
						}
					}
				}
			}
			.ic-btn{
				margin: 44upx auto 0;
				width: 200upx;
				height: 68upx;
				line-height: 68upx;
				text-align: center;
				border: .5px solid #fff;
				background-image: linear-gradient(180deg, #ffffff6b 0%, #ffffffc9 100%);
				box-shadow: 0 6upx 16upx 0 #18b48fb0, inset 0 2upx 12upx 0 #ffffff80;
				border-radius: 6upx;
				font-size: 28upx;
				font-weight: 500;
				color: $themeColor;
				text-shadow: 0 0.3upx 1upx rgba($color: #005F49, $alpha: .5);
			}
		}
	}
    .ic-section{
        padding: 54upx 30upx 0;
        .is-list{
            display: flex;
            flex-wrap: wrap;
            .il-item{
                margin-bottom: 60upx;
                flex-shrink: 0;
                flex-grow: 0;
                width: 25%;
                >view{
                    &:first-child{
                        margin: 0 auto 18upx;
                        width: 108upx;
                        height: 108upx;
                        border-radius: 30upx;
                        background-color: #fff;
                        @include centerFlex(center);
                        >image{
                            width: 80upx;
                            height: 80upx;
                        }
                    }
                    &:nth-child(2){
                        padding: 0 10upx;
                        line-height: 40upx;
                        text-align: center;
                        font-size: 28upx;
                        color: #1A1A1A;
                        @include textHide(1);
                    }
                }
            }
        }
    }
</style>