<template>
	<view class="container">
		<view class="man-body">
			<view v-if="selectedTabIndex == 1" class="box-body">
				<view class="section-head">
					<view class="fresh-area flex-row flex-between">
						<view>
							<text>更新时间:</text>
							<text
								class="fresh-time">{{ tools.formatTime(btBmsInfo ? btBmsInfo.time : bmsInfo.time) }}</text>
						</view>
						<view @tap="refreshData">
							<image class="fresh-icon" src="/static/resource/images/fr-icon.png"></image>
							<text>刷新</text>
						</view>
					</view>
					<view class="battery-model">
						<!-- <image class="battery-model-icon" src="/resource/images/b3.png"></image> -->
						<com-ele-quantity
							:quantity="tools.toFixed(btBmsInfo ? btBmsInfo.state.soc : bmsInfo.state.soc, 2)"></com-ele-quantity>
						<text></text>
					</view>
				</view>
				<view v-if="btBmsInfo ? btBmsInfo.state_v2 : bmsInfo.state_v2">
					<view class="section-body"
						v-for="(item, index) in btBmsInfo ? btBmsInfo.state_v2 : bmsInfo.state_v2" :key="index">
						<view v-if="item.class" class="param-item flex-row flex-between">
							<view class="param">{{ item.class }}</view>
							<view @tap="refreshData">
								<image class="fresh-icon" src="/static/resource/images/fr-icon.png"></image>
								<text>刷新</text>
							</view>
						</view>

						<view class="param-item flex-row flex-between" v-for="(varx,i) in (tools.filterHalf(item.vars))"
							:key="i">
							<view class="param">
								{{ item.vars[i * 2].label }}：
								<text class="param-value">{{ item.vars[i * 2].value }}</text>
							</view>

							<view v-if="item.vars.length > i * 2 + 1" class="param">
								{{ item.vars[i * 2 + 1].label }}：
								<text class="param-value">{{ item.vars[i * 2 + 1].value }}</text>
							</view>
						</view>
					</view>
				</view>
				<view v-else class="section-body">
					<view class="param-item flex-row flex-between">
						<view class="param">
							电池数量：
							<text class="param-value">{{ btBmsInfo ? btBmsInfo.state.count : bmsInfo.state.count  + '串'}}</text>
						</view>
						<view class="param">
							剩余容量：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.socAH : bmsInfo.state.socAH, 2) }}AH</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							总电压：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.voltageAll : bmsInfo.state.voltageAll, 3) }}V</text>
						</view>
						<view class="param">
							电流数据：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.current : bmsInfo.state.current, 3) }}A</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							最低电压：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.minVoltage : bmsInfo.state.minVoltage, 3) }}V</text>
						</view>
						<view class="param">
							最高电压：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.maxVoltage : bmsInfo.state.maxVoltage, 3) }}V</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							相差电压：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.voltagDifference : bmsInfo.state.voltagDifference, 3) }}V</text>
						</view>
						<view class="param">
							平均电压：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.averageVoltage : bmsInfo.state.averageVoltage, 3) }}V</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							温度数量：
							<text
								class="param-value">{{ btBmsInfo ? btBmsInfo.state.tempCount : bmsInfo.state.tempCount }}个</text>
						</view>
						<view class="param">
							标称容量：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.capacity : bmsInfo.state.capacity, 3) }}AH</text>
						</view>
					</view>
					<!-- <view class="param-item flex-row flex-between">
          <view class="param">温度：
            <text wx:for="{{btBmsInfo ? btBmsInfo.state.temp : bmsInfo.state.temp}}" wx:for-item="item" wx:for-index="index" wx:key="unique" class="param-value">[{{item}}°C]</text>
          </view>
        </view> -->
					<view class="param-item flex-row flex-between">
						<view class="param">
							温度：
							<text class="param-value"
								v-for="(item, index) in btBmsInfo ? btBmsInfo.state.temp : bmsInfo.state.temp"
								:key="index">[{{ item }}°C]</text>
						</view>
						<view class="param">
							功率：
							<text
								class="param-value">{{ tools.toFixed(btBmsInfo ? btBmsInfo.state.power : bmsInfo.state.power, 3) }}KW</text>
						</view>
					</view>
					<view v-if="(btBmsInfo ? btBmsInfo.state.temp_v2.length : bmsInfo.state.temp_v2.length) != 0"
						class="param-item flex-row flex-between">
						<view class="param"
							v-for="(item, index) in btBmsInfo ? btBmsInfo.state.temp_v2 : bmsInfo.state.temp_v2"
							:key="index">
							{{ item.label }}：

							<text class="param-value">[{{ item.value }}°C]</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							充电 继电器/MOS：
							<text
								class="param-value">{{ (btBmsInfo ? btBmsInfo.state.chargingMOS : bmsInfo.state.chargingMOS) == 0 ? '关闭' : '开启' }}</text>
						</view>
						<view class="param">
							放电 继电器/MOS：
							<text
								class="param-value">{{ (btBmsInfo ? btBmsInfo.state.dischargeMOS : bmsInfo.state.dischargeMOS) == 0 ? '关闭' : '开启' }}</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view v-if="bmsInfo.third_device_type != 'KYYWJT'" class="param">
							充电状态：
							<text class="param-value">
								{{
                                    (btBmsInfo ? btBmsInfo.state.chargeState : bmsInfo.state.chargeState) == 0
                                        ? '静止'
                                        : (btBmsInfo ? btBmsInfo.state.chargeState : bmsInfo.state.chargeState) == 1
                                        ? '充电'
                                        : '放电'
                                }}
							</text>
						</view>
						<view v-if="bmsInfo.third_device_type == 'KYYWJT'" class="param">
							充电状态：
							<text class="param-value">
								{{
                                    bmsInfo.state.KYChargeState == 0
                                        ? '未充电'
                                        : bmsInfo.state.KYChargeState == 1
                                        ? '充电中'
                                        : bmsInfo.state.KYChargeState == 2
                                        ? '充电完成'
                                        : '充电故障'
                                }}
							</text>
						</view>

						<view class="param">
							均衡开闭：
							<text
								class="param-value">{{ (btBmsInfo ? btBmsInfo.state.equilibrium : bmsInfo.state.equilibrium) == 0 ? '关闭' : '开启' }}</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							循环次数：
							<text class="param-value">{{ btBmsInfo ? btBmsInfo.state.cycle : bmsInfo.state.cycle }}
								次</text>
						</view>
						<view class="param">
							固件版本：
							<text
								class="param-value">{{ btBmsInfo ? btBmsInfo.state.firmware : bmsInfo.state.firmware }}</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view v-if="bmsInfo.third_device_type != 'KYYWJT'" class="param">
							连接状态：
							<text
								class="param-value">{{ (btBmsInfo ? btBmsInfo.state.connectState : bmsInfo.state.connectState) == 0 ? '未连接' : '已连接' }}</text>
						</view>
						<view v-if="bmsInfo.third_device_type == 'KYYWJT'" class="param">
							电池状态：
							<text class="param-value">
								{{
                                    bmsInfo.state.chargeState == 0 ? '初始化' : bmsInfo.state.chargeState == 1 ? '高压断开' : bmsInfo.state.chargeState == 2 ? '预充电' : '高压连接'
                                }}
							</text>
						</view>
						<view class="param">
							设备编码：
							<text class="param-value">{{ battery_sn }}</text>
						</view>
					</view>
					<view class="param-item batterys-show">
						<view class="battery-row">
							<!-- <view class="battery-block" wx:for="{{bmsInfo.State.betList}}" wx:key="unique"> -->
							<view class="battery-block"
								v-for="(item, index) in btBmsInfo ? btBmsInfo.state.voltage : bmsInfo.state.voltage"
								:key="index">
								<view class="battery-bat">
									<view class="i-bat">
										<image v-if="isShowGreen" class="i-bat-icon"
											src="/static/resource/images/diancimr.png"></image>
										<image v-else class="i-bat-icon" :src="
                                                '/static/resource/images/' +
                                                ((btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index]) ==
                                                tools.max(btBmsInfo ? btBmsInfo.state.voltage : bmsInfo.state.voltage)
                                                    ? 'diancihs.png'
                                                    : (btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index]) ==
                                                      tools.min(btBmsInfo ? btBmsInfo.state.voltage : bmsInfo.state.voltage)
                                                    ? 'diancils.png'
                                                    : 'diancimr.png')
                                            "></image>
										<view class="i-bat-index">{{ index + 1 }}</view>
									</view>
									<view v-if="isShowGreen" class="i-vol" style="color: #303133">
										{{
                                            (btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index])
                                                ? tools.toFixed(btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index], 3)
                                                : 0
                                        }}
									</view>
									<view v-else class="i-vol" :style="
                                            'color: ' +
                                            ((btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index]) ==
                                            tools.max(btBmsInfo ? btBmsInfo.state.voltage : bmsInfo.state.voltage)
                                                ? '#ff3154'
                                                : (btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index]) ==
                                                  tools.min(btBmsInfo ? btBmsInfo.state.voltage : bmsInfo.state.voltage)
                                                ? '#1b88f6'
                                                : '#303133')
                                        ">
										{{
                                            (btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index])
                                                ? tools.toFixed(btBmsInfo ? btBmsInfo.state.voltage[index] : bmsInfo.state.voltage[index], 3)
                                                : 0
                                        }}
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-if="!(bmsInfo.close_alarm_data_tab && bmsInfo.close_alarm_data_tab == 1)" class="section-body">
					<view class="param-item flex-row flex-between">
						<view class="param">故障报警</view>
						<picker mode="date" :value="alarmDate" @change="bindAlarmDateChange">
							<view class="flex-row">
								<image class="fresh-icon" style="margin-right: 14rpx"
									src="/static/resource/images/time.png"></image>
								<text style="margin-right: 20rpx">{{ alarmDate }}</text>
								<image class="fresh-icon" src="/static/resource/images/youjiantou.png"></image>
							</view>
						</picker>
					</view>
					<view v-if="alarmList.length == 0" class="param-item" style="color: #ccc; text-align: center">没有数据
					</view>
					<view v-else>
						<view class="alarm-item flex-row flex-between" v-for="(item, index) in alarmList" :key="index">
							<view class="alarm-time">{{ tools.formatTime(item.time) }}</view>

							<view class="alarm-text">
								<view class="alarm-desc">{{ item.alarm_desc }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<view v-else-if="selectedTabIndex == 2" class="box-body">
				<view class="section-body" v-for="(item, index) in bmsInfo.sets" :key="index">
					<view class="param-item flex-row flex-between">
						<view class="param">{{ item.class }}</view>
						<view @tap="refreshData">
							<image class="fresh-icon" src="/static/resource/images/fr-icon.png"></image>
							<text>刷新</text>
						</view>
					</view>

					<view class="param-item flex-row flex-between" v-for="(varx,i) in (item.vars)" :key="i">
						<view class="param">
							{{ varx.label }}:
							<text class="param-value">
								{{varx.type=='radio'? (tools.getOption(varx.option, varx.value) ? tools.getOption(varx.option, varx.value).label : '') : varx.value}}
							</text>
						</view>

						<view v-if="varx.type!='readonly'" class="command-control">
							<picker v-if="varx.type=='radio'" @change="bindPickerChange" :data-data="varx"
								:value="tools.getOptionIndex(varx.option, varx.set ? varx.set : varx.value)"
								:range="varx.option" range-key="label">
								<view class="input-def">
									{{tools.getOption(varx.option, varx.set ? varx.set : varx.value) ? tools.getOption(varx.option, varx.set ? varx.set : varx.value).label : ''}}
								</view>
							</picker>
							<input v-else class="input-def" @input="bindInput" :data-data="varx"
								:value="varx.set ? varx.set : ''" />
							<text class="btn-def" @tap="bindSet" :data-data="varx">设置</text>
						</view>
					</view>
				</view>
			</view>

			<view v-else-if="selectedTabIndex == 3" class="box-body">
				<view class="section-head">
					<view class="fresh-area flex-row flex-between">
						<view>
							<text>更新时间:</text>
							<text
								class="fresh-time">{{ tools.formatTime(btBmsInfo ? btBmsInfo.time : bmsInfo.time) }}</text>
						</view>
						<view @tap="refreshData">
							<image class="fresh-icon" src="/static/resource/images/fr-icon.png"></image>
							<text>刷新</text>
						</view>
					</view>
				</view>
				<view class="section-body">
					<view class="param-item flex-row flex-between">
						<view class="param">
							充电开关:
							<text class="param-value">
								{{ btBmsInfo ? (btBmsInfo.state.chargingMOSOnOff == 0 ? '关闭' : '开启') : bmsInfo.state.chargingMOSOnOff == 0 ? '关闭' : '开启' }}
							</text>
						</view>
						<view class="command-control">
							<text class="btn-def" @tap="bindChargingMos" data-data="1">开启</text>
							<text class="btn-def" @tap="bindChargingMos" data-data="0">关闭</text>
						</view>
					</view>
					<view class="param-item flex-row flex-between">
						<view class="param">
							放电开关:
							<text class="param-value">
								{{ btBmsInfo ? (btBmsInfo.state.dischargeMOSOnOff == 0 ? '关闭' : '开启') : bmsInfo.state.dischargeMOSOnOff == 0 ? '关闭' : '开启' }}
							</text>
						</view>
						<view class="command-control">
							<text class="btn-def" @tap="bindDischargeMos" data-data="1">开启</text>
							<text class="btn-def" @tap="bindDischargeMos" data-data="0">关闭</text>
						</view>
					</view>
					<view
						v-if="!is_single_bt && !(bmsInfo.bms_control_hide && bmsInfo.bms_control_hide.restart_sys && bmsInfo.bms_control_hide.restart_sys == 1)"
						class="param-item flex-row flex-between">
						<view class="param">重启系统</view>
						<view class="command-control">
							<text class="btn-def" @tap="bindRestart">重启</text>
						</view>
					</view>
					<view
						v-if="!is_single_bt && !(bmsInfo.bms_control_hide && bmsInfo.bms_control_hide.close_sys && bmsInfo.bms_control_hide.close_sys == 1)"
						class="param-item flex-row flex-between">
						<view class="param">关闭系统</view>
						<view class="command-control">
							<text class="btn-def" @tap="bindClose">关闭</text>
						</view>
					</view>
					<view
						v-if="!is_single_bt && !(bmsInfo.bms_control_hide && bmsInfo.bms_control_hide.current_reset && bmsInfo.bms_control_hide.current_reset == 1)"
						class="param-item flex-row flex-between no-border">
						<view class="param">电流归零</view>
						<view class="command-control">
							<text class="btn-def" @tap="bindCurrentZero">归零</text>
						</view>
					</view>
				</view>
			</view>

			<!--view wx:elif="{{selectedTabIndex==4}}" class="box-body">
      <view wx:for="{{btBmsInfo.btsets}}" wx:for-item="item" wx:for-index="index" wx:key="unique" class="section-body">
        <view class="param-item flex-row flex-between">
          <view class="param">{{ item.class }}</view>
          <view>
            <text class="btn-def" bindtap="bindBTSet" data-data="{{item}}">设置</text>
          </view>
        </view>
        <view wx:for="{{item.vars}}" wx:for-item="var" wx:for-index="i" wx:key="unique" class="param-item flex-row flex-between">
          <view class="param">{{ var.label }}: <text class="param-value">{{ var.type=='radio'? (var.option[var.value] ? var.option[var.value].label : '') : var.value}}</text></view>
          <view wx:if="{{var.type!='readonly'}}" class="command-control">
            <picker wx:if="{{var.type=='radio'}}" bindchange="bindBTPickerChange" data-data="{{var}}" value="{{var.set ? var.set : var.value}}" range="{{var.option}}" range-key="label">
              <view class="input-def">
                {{var.option[var.set ? var.set : var.value] ? var.option[var.set ? var.set : var.value].label : ''}}
              </view>
            </picker>
            <input wx:else class="input-def" bindinput="bindBTInput" data-data="{{var}}" value="{{ var.set ? var.set : '' }}"></input>
          </view>
        </view>
      </view>
    </view-->
		</view>
		<view class="tab-container">
			<view class="tab-row flex-row flex-around">
				<view :class="'tab-item ' + (selectedTabIndex == 1 ? 'tab-selected' : '')" @tap="bindSelectedTab"
					data-idx="1">实时状态</view>
				<!-- <view wx:if="{{ userInfo.type=='group' && bmsInfo.sets && bmsInfo.sets.length != 0 }}" class="tab-item {{selectedTabIndex==2?'tab-selected':''}}" bindtap="bindSelectedTab" data-idx="2">参数设置</view>
      <view wx:if="{{ userInfo.type=='group' }}" class="tab-item {{selectedTabIndex==3?'tab-selected':''}}" bindtap="bindSelectedTab" data-idx="3">BMS控制</view>
       -->

				<view v-if="display_bms && bmsInfo.sets && bmsInfo.sets.length != 0"
					:class="'tab-item ' + (selectedTabIndex == 2 ? 'tab-selected' : '')" @tap="bindSelectedTab"
					data-idx="2">
					参数设置
				</view>
				<view v-if="display_bms" :class="'tab-item ' + (selectedTabIndex == 3 ? 'tab-selected' : '')"
					@tap="bindSelectedTab" data-idx="3">BMS控制</view>
			</view>
		</view>
	</view>
</template>
<script module="tools" lang="wxs" src="@/pages/common/wxs/tools.wxs"></script>
<script>
	import comEleQuantity from '@/component/comEleQuantityHorizontal/comEleQuantityHorizontal';
	// pages/bms/bms.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');
	var bluetooth = require('../../common/bluetooth.js');
	const ZXBTS = require('../../common/bluetooth/ZXBTS.js');
	const LSBTS = require('../../common/bluetooth/LSBTS.js');
	export default {
		components: {
			comEleQuantity
		},
		data() {
			return {
				curTime: 0,
				selectedTabIndex: 1,
				battery_sn: '',

				bmsInfo: {
					time: '',

					state: {
						soc: '',
						count: '',
						socAH: '',
						voltageAll: '',
						current: '',
						minVoltage: '',
						maxVoltage: '',
						voltagDifference: '',
						averageVoltage: '',
						tempCount: '',
						capacity: '',
						temp: '',
						power: '',
						temp_v2: [],
						chargingMOS: '',
						dischargeMOS: '',
						chargeState: '',
						KYChargeState: 0,
						equilibrium: '',
						cycle: '',
						firmware: '',
						connectState: '',
						voltage: '',
						chargingMOSOnOff: 0,
						dischargeMOSOnOff: 0
					},

					state_v2: '',
					third_device_type: '',
					close_alarm_data_tab: '',
					sets: [],

					bms_control_hide: {
						restart_sys: '',
						close_sys: '',
						current_reset: ''
					}
				},

				userInfo: {},

				// 后续用到
				bt_type: '',

				isShowModal: false,
				btid: '',
				btkey: '',
				bms: '',
				deviceType: '',
				alarmDate: common.DateFormat(new Date(), 'yyyy-MM-dd'),
				alarmList: [],
				btBmsInfo: false,
				is_single_bt: false,
				isShowGreen: false,
				display_bms: true,
				soc: '',
				i: '',
				count: '',
				socAH: '',
				voltageAll: '',
				current: '',
				minVoltage: '',
				maxVoltage: '',
				voltagDifference: '',
				averageVoltage: '',
				tempCount: '',
				capacity: '',
				temp: '',
				power: '',
				temp_v2: [],
				chargingMOS: '',
				dischargeMOS: '',
				chargeState: '',
				equilibrium: '',
				cycle: '',
				firmware: '',
				connectState: '',
				voltage: '',
				chargingMOSOnOff: 0,
				dischargeMOSOnOff: 0
			};
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			const battery_sn = options.macid;
			const userInfo = storage.getUserInfo();
			if (!battery_sn) {
				uni.navigateBack({
					delta: 1
				});
			}
			if (bluetooth.isConnected(battery_sn)) {
				bluetooth.onCharacteristicStateChange(battery_sn, 'bms', (data) => {
					if (bluetooth.bluetoothDeviceConfig && data != null) {
						const me = this;
						common.reportBms(battery_sn, data, function(success) {
							me.loadBmsInfo();
						});
					}
					var btBmsInfo = bluetooth.bmsInfo(battery_sn);
					if (btBmsInfo) {
						btBmsInfo.time = parseInt(new Date().getTime() / 1000);
					}
					if (btBmsInfo.btsets && this.btBmsInfo && this.btBmsInfo.btsets) {
						console.log(btBmsInfo)
						btBmsInfo.btsets.forEach((item, index) => {
							console.log(index)
							item.vars.forEach((v, i) => {
								this.btBmsInfo.btsets.forEach((p) => {
									var n = p.vars.find((u) => u.name == v.name && u
										.set);
									if (n != undefined) {
										btBmsInfo.btsets[index].vars[i].set = n.set;
									}
								});
							});
						});
					}
					console.log(btBmsInfo);
					this.setData({
						btBmsInfo: btBmsInfo
					});
				});
				bluetooth.stateUpdate(battery_sn);
			}
			this.setData({
				userInfo: userInfo,
				battery_sn: battery_sn,
				deviceType: options.deviceType,
				bt_type: options.bt_type,
				btid: options.btid,
				btkey: options.btkey,
				bms: options.bms
			});
			this.loadBmsInfo();
			this.loadAlarm();
			this.loadIsChild();
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow: function() {},
		/**
		 * 页面相关事件处理函数--监听用户下拉动作
		 */
		onPullDownRefresh: function() {},
		/**
		 * 页面上拉触底事件的处理函数
		 */
		onReachBottom: function() {},
		methods: {
			bindSelectedTab: function(e) {
				const idx = e.currentTarget.dataset.idx;
				this.setData({
					selectedTabIndex: idx
				});
			},

			loadIsChild: function() {
				const pData = {
					pid: '27669'
				};
				const that = this;
				http.postApi(config.API_IS_CHILD, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						that.setData({
							isShowGreen: resp.data.data.res
						});
					}
				});
			},

			refreshData: function() {
				const device = {
					bt_type: this.bt_type,
					mac_id: this.battery_sn,
					device_type: this.deviceType,
					btid: this.btid,
					btkey: this.btkey,
					bms: this.bms
				};
				console.log('1111');
				if (bluetooth.isUniversalBluetoothPlugin(device)) {
					console.log('2222');
					if (bluetooth.isConnected(this.battery_sn)) {
						bluetooth.onCharacteristicStateChange(this.battery_sn, 'home', (data) => {
							if (bluetooth.bluetoothDeviceConfig && data != null) {
								common.reportBms(device.mac_id, data, function(success) {});
							}
						});
						bluetooth.onConnectionStateChange(this.battery_sn, 'list', (res) => {});
						const me = this;
						bluetooth.stateUpdate(
							this.battery_sn,
							(res) => {
								me.loadBmsInfo();
							},
							(res) => {
								me.loadBmsInfo();
							}
						);
					} else {
						this.bluetoothConnect();
					}
				} else {
					this.loadBmsInfo();
				}
			},

			loadBmsInfo: function() {
				console.log('111');
				var endTime = new Date().getTime();
				if (endTime - this.curTime > 4000) {
					common.loading();
					const pData = {
						macid: this.battery_sn
					};
					const me = this;
					http.postApi(config.API_BMS_STATE, pData, function(resp) {
						uni.hideLoading();
						if (resp.data.code === 200) {
							const bmsInfo = resp.data.data;
							if (!bmsInfo) {
								common.simpleToast('BMS数据暂无');
								setTimeout(function() {
									uni.navigateBack({
										delta: 1
									});
								}, 1500);
							}
							me.setData({
								battery_sn: me.battery_sn,
								bmsInfo: resp.data.data
							});
							if (me.userInfo.type != 'group') {
								if (me.bmsInfo.display_bms - 0 === 0) {
									me.setData({
										display_bms: false
									});
								}
							}
						} else {
							setTimeout(function() {
								uni.navigateBack({
									delta: 1
								});
							}, 1500);
						}
					});
				}
			},

			bluetoothConnect() {
				const device = {
					bt_type: this.bt_type,
					mac_id: this.battery_sn,
					device_type: this.deviceType,
					btid: this.btid,
					btkey: this.btkey,
					bms: this.bms
				};
				const me = this;
				bluetooth.openBluetoothAdapter(
					(res) => {
						bluetooth.connectDevice(
							device,
							() => {
								bluetooth.onCharacteristicStateChange(device.mac_id, 'home', (data) => {
									if (bluetooth.bluetoothDeviceConfig && data != null) {
										common.reportBms(device.mac_id, data, function(success) {});
									}
								});
								bluetooth.onConnectionStateChange(device.mac_id, 'home', (res) => {});
								bluetooth.stateUpdate(
									me.battery_sn,
									(res) => {
										me.loadBmsInfo();
									},
									(res) => {
										me.loadBmsInfo();
									}
								);
							},
							(res) => {
								me.loadBmsInfo();
								if (me.isShowModal) {
									return;
								}
								me.setData({
									isShowModal: true
								});
								uni.showModal({
									content: '连接电池失败，请靠近电池重试',
									confirmText: '重试',
									success: (res) => {
										if (res.confirm) {
											console.log('点击链接1');
											me.setData({
												isShowModal: false
											});
											me.bluetoothConnect();
										} else {
											me.setData({
												isShowModal: false
											});
										}
									},
									fail: (res) => {}
								});
							}
						);
					},
					(res) => {
						me.loadBmsInfo();
						if (me.isShowModal) {
							return;
						}
						me.setData({
							isShowModal: true
						});
						uni.showModal({
							content: '需使用手机蓝牙功能，请打开蓝牙' + res.errCode,
							confirmText: '重试',
							success: (res) => {
								// var me = this
								if (res.confirm) {
									console.log('点击链接2');
									me.bluetoothConnect();
								} else {
									me.setData({
										isShowModal: false
									});
								}
							},
							fail: (res) => {}
						});
					}
				);
			},

			bindPickerChange: function(e) {
				var bmsInfo = this.bmsInfo;
				bmsInfo.sets.forEach((item, index) => {
					item.vars.forEach((v, i) => {
						if (v.name == e.currentTarget.dataset.data.name) {
							bmsInfo.sets[index].vars[i].set = bmsInfo.sets[index].vars[i].option[
								parseInt(e.detail.value)].value;
						}
					});
				});
				this.setData({
					bmsInfo: bmsInfo
				});
			},

			bindInput: function(e) {
				var bmsInfo = this.bmsInfo;
				bmsInfo.sets.forEach((item, index) => {
					item.vars.forEach((v, i) => {
						if (v.name == e.currentTarget.dataset.data.name) {
							bmsInfo.sets[index].vars[i].set = e.detail.value;
						}
					});
				});
				this.setData({
					bmsInfo: bmsInfo
				});
			},

			bindSet: function(e) {
				var item = e.currentTarget.dataset.data;
				//  var item = {
				//   name:"0xAA",
				//   set:"50"
				//  }
				if (!item.set) {
					common.simpleToast('请设置参数');
					return;
				}
				const device = {
					bt_type: this.bt_type,
					mac_id: this.battery_sn,
					device_type: this.deviceType,
					btid: this.btid,
					btkey: this.btkey,
					bms: this.bms,
					name: item.name,
					value: item.set
				};
				console.log(device);
				if (bluetooth.isUniversalBluetoothPlugin(device) && bluetooth.bmsSet(device)) {
					this.bindBTSet(device);
				}
				common.loading();
				const pData = {
					macid: this.battery_sn,
					name: item.name,
					value: item.set
				};
				http.postApi(config.API_BMS_SET, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindBTSet(device) {
				bluetooth.bmsSet(
					device,
					(res) => {
						common.simpleToast('发送成功');
					},
					() => {
						common.simpleToast('发送失败');
					}
				);
				// ZXBTS.bmsSet(device)
			},

			bindChargingMos: function(e) {
				var item = e.currentTarget.dataset.data;
				const pData = {
					macid: this.battery_sn,
					value: item
				};
				console.log(this.bmsInfo);
				const connection_state = bluetooth.getConnectionState(this.battery_sn);
				if (connection_state) {
					if (bluetooth.isConnected(this.battery_sn)) {
						// if(bluetooth.haveBMSForBT(connection_state.device)) {
						bluetooth.bmsChargingMOS(pData.macid, pData.value, () => {
							common.simpleToast('设置成功');
							var me = this;
							setTimeout(function() {
								bluetooth.stateUpdate(
									me.battery_sn,
									(res) => {},
									(res) => {}
								);
							}, 2000);
							// bluetooth.stateUpdate(this.data.battery_sn)
						});
						return;
					} else {
						common.simpleToast('蓝牙未连接');
					}
					// }
				}
				common.loading();
				http.postApi(config.API_BMS_CHARGING_MOS, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindDischargeMos: function(e) {
				var item = e.currentTarget.dataset.data;
				const pData = {
					macid: this.battery_sn,
					value: item
				};
				const connection_state = bluetooth.getConnectionState(this.battery_sn);
				if (connection_state) {
					if (bluetooth.isConnected(this.battery_sn)) {
						// if(bluetooth.haveBMSForBT(connection_state.device)) {
						bluetooth.bmsDischargeMOS(pData.macid, pData.value, () => {
							common.simpleToast('设置成功');
							//bluetooth.stateUpdate(this.data.battery_sn)
							var me = this;
							setTimeout(function() {
								bluetooth.stateUpdate(
									me.battery_sn,
									(res) => {},
									(res) => {}
								);
							}, 2000);
						});
						return;
						// }
					} else {
						common.simpleToast('蓝牙连接失败');
					}
				}
				common.loading();
				http.postApi(config.API_BMS_DISCHARGARGE_MOS, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindRestart: function(e) {
				common.loading();
				const pData = {
					macid: this.battery_sn
				};
				http.postApi(config.API_BMS_RESTART, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindClose: function(e) {
				common.loading();
				const pData = {
					macid: this.battery_sn
				};
				http.postApi(config.API_BMS_CLOSE, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindCurrentZero: function(e) {
				common.loading();
				const pData = {
					macid: this.battery_sn
				};
				http.postApi(config.API_BMS_CURRENT_ZERO, pData, function(resp) {
					uni.hideLoading();
					if (resp.data.code === 200) {
						common.simpleToast('设置成功');
					} else {
						common.simpleToast(resp.data.msg);
					}
				});
			},

			bindAlarmDateChange(e) {
				this.setData({
					alarmDate: e.detail.value
				});
				this.loadAlarm();
			},

			loadAlarm() {
				const begin_time = parseInt(new Date(this.alarmDate).getTime() / 1000);
				const end_time = begin_time + 86400 - 1;
				common.loading();
				http.postApi(
					config.API_BMS_ALARM, {
						macid: this.battery_sn,
						begin_time: begin_time,
						end_time: end_time
					},
					(resp) => {
						uni.hideLoading();
						if (resp.data.code === 200) {
							this.setData({
								alarmList: resp.data.data.list
							});
						} else {
							//common.simpleToast(resp.data.msg)
						}
					}
				);
			},

			bindBTPickerChange: function(e) {
				var btBmsInfo = this.btBmsInfo;
				btBmsInfo.btsets.forEach((item, index) => {
					item.vars.forEach((v, i) => {
						if (v.name == e.currentTarget.dataset.data.name) {
							btBmsInfo.btsets[index].vars[i].set = e.detail.value;
						}
					});
				});
				this.setData({
					btBmsInfo: btBmsInfo
				});
			},

			bindBTInput: function(e) {
				var btBmsInfo = this.btBmsInfo;
				btBmsInfo.btsets.forEach((item, index) => {
					item.vars.forEach((v, i) => {
						if (v.name == e.currentTarget.dataset.data.name) {
							btBmsInfo.btsets[index].vars[i].set = e.detail.value;
						}
					});
				});
				this.setData({
					btBmsInfo: btBmsInfo
				});
			}
		}
	};
</script>
<style>
	@import './bms.css';
</style>