<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="设备标识ID" prop="deviceId">
        <el-input v-model="queryParams.deviceId" placeholder="请输入设备标识ID" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="设备型号" prop="deviceModel">
        <el-input v-model="queryParams.deviceModel" placeholder="请输入设备型号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入用户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="发放方式" prop="grantType">
        <el-input v-model="queryParams.grantType" placeholder="请输入发放方式" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="在线状态" prop="online_statis">
        <el-select v-model="queryParams.online_statis">
          <el-option label="离线" :value="0"></el-option>
          <el-option label="在线" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="最后在线时间" prop="offlinetime">
        <el-date-picker v-model="queryParams.offlinetime" type="datetime" placeholder="选择日期时间" :editable='false'
          value-format="yyyy-MM-dd HH:mm">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:device:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:device:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:device:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:profile:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-upload2" size="mini" @click="handleUpload"
          v-hasPermi="['system:manage:add']">导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备标识ID" align="center" prop="deviceId" />
      <el-table-column label="设备型号" align="center" prop="deviceType" />
      <el-table-column label="SIM卡号" align="center" prop="simCode" />
      <el-table-column label="用户姓名" align="center" prop="name" />
      <el-table-column label="身份证号码" align="center" prop="sfzid" />
      <el-table-column label="手机号" align="center" prop="telno" />
      <el-table-column label="发放方式" align="center" prop="granttype" />
      <el-table-column label="在线状态" align="center" prop="online" />
      <el-table-column label="设备电量" align="center" prop="electric_quantity" />
      <el-table-column label="最后在线时间" align="center" prop="offlinetime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:device:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:device:remove']">删除</el-button>
          <el-dropdown trigger="click" @command="openSetting($event, scope.row)">
            <span class="el-dropdown-link" style="color: #409EFF;">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="settingOpen">设备设置</el-dropdown-item>
              <el-dropdown-item command="healthInterval">健康阈值设置</el-dropdown-item>
              <el-dropdown-item command="fenceOpen">电子围栏</el-dropdown-item>
              <el-dropdown-item command="health">健康指标</el-dropdown-item>
              <el-dropdown-item command="deviceLog">设备消息日志</el-dropdown-item>
              <!-- <el-dropdown-item command="settingLog">设置日志</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改设备列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="设备属性">
          <el-radio-group v-model="form.deviceProper">
            <el-radio v-for="i in deviceAttribute" :key="i.dictValue" :label="i.dictValue">{{ i.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户姓名" prop="name" class="inp">
          <el-input v-model="form.name" placeholder="请选择" disabled class="setting-inp">
            <el-button slot="append" icon="el-icon-search" @click="toSelect"></el-button>
          </el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号码" prop="sfzid" class="inp">
              <el-input v-model="form.sfzid" placeholder="请输入身份证号码" class="setting-inp" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="telno" class="inp">
              <el-input v-model="form.telno" placeholder="请输入手机号" class="setting-inp" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工厂" prop="factory">
              <el-select v-model="form.factory" class="setting-inp">
                <el-option v-for="i in factoryList" :key="i.dictValue" :value="i.dictValue"
                  :label="i.dictLabel"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备型号" prop="deviceModel">
              <el-select v-model="form.deviceModel" class="setting-inp">
                <el-option v-for="i in deviceModel" :key="i.dictValue" :value="i.dictValue"
                  :label="i.dictLabel"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备标识ID" prop="deviceId">
              <el-input v-model="form.deviceId" placeholder="请输入设备标识ID" class="setting-inp" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SIM卡号" prop="simCode">
              <el-input v-model="form.simCode" placeholder="请输入SIM卡号" class="setting-inp" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备序列号" prop="serialNumber">
              <el-input v-model="form.serialNumber" placeholder="请输入设备序列号" class="setting-inp" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发放方式" prop="grantType">
              <el-radio-group :value="form.grantType">
                <el-radio v-for="i in grantType" :key="i.dictValue" :label="i.dictValue">{{ i.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="selectBuy">
          <el-row>
            <el-col :span="12">
              <el-form-item label="销售价格" prop="price">
                <el-input v-model="form.price" placeholder="请输入销售价格" class="setting-inp" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务费用" prop="cost">
                <el-input v-model="form.cost" placeholder="请输入服务费用" class="setting-inp" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="支付方式" prop="payment">
            <el-select v-model="form.payment" class="setting-inp">
              <el-option v-for="i in payment" :key="i.dictValue" :value="i.dictValue" :label="i.dictLabel"></el-option>
            </el-select>
          </el-form-item>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择用户" :visible.sync="selectUser" width="1200px" append-to-body destroy-on-close>
      <el-form :model="userForm" label-width="80px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" class="search-inp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号" prop="telOne">
              <el-input v-model="userForm.telOne" class="search-inp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号" prop="sfzid">
              <el-input v-model="userForm.telOne" class="search-inp"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="客户类型" prop="telOne">
              <el-select v-model="userForm.clientType" class="search-inp">
                <el-option v-for="i in clientType" :key="i.dictValue" :value="i.dictValue"
                  :label="i.dictLabel"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="家庭住址" prop="telOne">
              <el-input v-model="userForm.familyAddress" style="width: 500px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="searchUser">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetUser">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="userList" v-loading="loading" @selection-change="checkUser">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender" />
        <el-table-column label="年龄" align="center" prop="age" />
        <el-table-column label="手机号" align="center" prop="telOne" />
        <el-table-column label="身份证号" align="center" prop="sfzid" />
        <el-table-column label="家庭住址" align="center" prop="familyAddress" />
      </el-table>
      <pagination v-show="userTotal > 0" :total="userTotal" :page.sync="userForm.pageNum" :limit.sync="userForm.pageSize"
        @pagination="getUserList" />
      <el-row slot="footer" style="text-align: center;">
        <el-button style="width: 120px;margin: 0 30px" @click='checkUserCancel'>取消</el-button>
        <el-button type="primary" style="width: 120px;margin: 0 30px" @click='checkUserConfirm'>确定</el-button>
      </el-row>
    </el-dialog>
    <el-dialog title="设备设置" :visible.sync="settingOpen" width="1000px" append-to-body>
      <el-row :gutter="20" class="top">
        <el-col :span="5">设备ID：{{ setUser.deviceId }}</el-col>
        <el-col :span="5">{{ setUser.name }}</el-col>
        <el-col :span="5">{{ setUser.telno }}</el-col>
      </el-row>
      <el-row class="top">
        <el-col :span="5">
          <el-button type="warning">关机</el-button>
        </el-col>
        <el-col :span="5">
          <el-button type="warning">获取定位</el-button>
        </el-col>
        <el-col :span="5">
          <el-button type="warning">立即测量心率、血压</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="5">
          <el-menu default-active="sos" @select="selectSetting">
            <el-menu-item v-for="i in menuInfo" :key="i.dictValue" :index="i.dictValue">{{ i.dictLabel }}</el-menu-item>
          </el-menu>
        </el-col>
        <el-col :span="19">
          <el-form v-if="settingPage == 'sos'" label-width="180px" :model="sosForm">
            <el-form-item label="联系人1">
              <el-input class="setting-inp" v-model="sosForm.tel1"></el-input>
            </el-form-item>
            <el-form-item label="联系人2">
              <el-input class="setting-inp" v-model="sosForm.tel2"></el-input>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'measureInterval'" label-width="180px" :model="intervalForm">
            <el-form-item label="定位间隔（分钟）">
              <el-input class="setting-inp" type="number" v-model="intervalForm.cr_interval"></el-input>
            </el-form-item>
            <el-form-item label="心率间隔（分钟）">
              <el-input class="setting-inp" type="number" v-model="intervalForm.hrt_interval"></el-input>
            </el-form-item>
            <el-form-item label="体温间隔（分钟）">
              <el-input class="setting-inp" type="number" v-model="intervalForm.wd_interval"></el-input>
            </el-form-item>
            <el-form-item label="血压间隔（分钟）">
              <el-input class="setting-inp" type="number" v-model="intervalForm.bld_interval"></el-input>
            </el-form-item>
            <el-form-item label="血氧间隔（分钟）">
              <el-input class="setting-inp" type="number" v-model="intervalForm.ox_interval"></el-input>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'stepCount'" label-width="180px" :model="pedoForm">
            <el-form-item label="计步器状态">
              <el-switch v-model="pedoForm.isopen"></el-switch>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'contacts'" label-width="100px" :model="telForm">
            <el-form-item label="联系人">
              <el-row :gutter="20">
                <el-col :span="5">
                  <el-input style="width: 120px;" placeholder="姓名" v-model="telForm.name1"></el-input>
                </el-col>
                <el-col :span="5">
                  <el-input class="setting-inp" placeholder="电话" v-model="telForm.tel1"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="联系人">
              <el-row :gutter="20">
                <el-col :span="5">
                  <el-input style="width: 120px;" placeholder="姓名" v-model="telForm.name2"></el-input>
                </el-col>
                <el-col :span="5">
                  <el-input class="setting-inp" placeholder="电话" v-model="telForm.tel2"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="联系人">
              <el-row :gutter="20">
                <el-col :span="5">
                  <el-input style="width: 120px;" placeholder="姓名" v-model="telForm.name3"></el-input>
                </el-col>
                <el-col :span="5">
                  <el-input class="setting-inp" placeholder="电话" v-model="telForm.tel3"></el-input>
                </el-col>
              </el-row>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'clock'" label-width="80px" :model="clockForm">
            <div class="clock-item" v-for="item in clockList" :key="item.clockId">
              <el-form-item label="闹钟名称">
                <el-input class="clock-input" v-model="item.clockName"></el-input>
                <el-time-picker :editable="false" value-format="HH:mm" placeholder="请选择时间"
                  v-model="item.time"></el-time-picker>
                <el-switch class="clock-switch" v-model="item.isopen"></el-switch>
                <el-button type="danger" icon="el-icon-delete" circle @click="deleteClock(item.clockId)"></el-button>
              </el-form-item>
              <el-form-item label="日期">
                <el-checkbox-group v-model="item.weeks">
                  <el-checkbox v-for="i in clockDate" :key="i.dictValue" :label="i.dictValue">{{ i.dictLabel
                  }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-form>
          <el-form v-if="settingPage == 'silentTime'" label-width="80px">
            <el-form-item label="时间" v-for="item in silentList" :key="item.id" style="margin: 20px 0;">
              <el-time-picker is-range :editable="false" v-model="item.timeRange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="HH:mm">
              </el-time-picker>
              <el-button type="danger" style="margin-left: 20px;" icon="el-icon-delete" circle
                @click="deleteSilent(item.id)"></el-button>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'timeOnOff'" label-width="80px" :model="onoffForm">
            <el-form-item label="是否使用">
              <el-switch v-model="onoffForm.is_open"></el-switch>
            </el-form-item>
            <el-form-item label="开机时间">
              <el-time-picker :editable="false" v-model="onoffForm.bootup_time" value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="关机时间">
              <el-time-picker :editable="false" v-model="onoffForm.shutdown_time" value-format="HH:mm">
              </el-time-picker>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'wearNotice'" label-width="120px" :model="wearForm">
            <el-form-item label="佩戴提醒状态">
              <el-switch v-model="wearForm.is_open"></el-switch>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'fallNotice'" label-width="120px" :model="fallForm">
            <el-form-item label="跌倒提醒状态">
              <el-switch v-model="fallForm.is_open"></el-switch>
            </el-form-item>
            <el-form-item label="跌倒灵敏度">
              <el-radio-group v-model="fallForm.lsset_type">
                <el-radio v-for="i in sensitivityList" :key="i.dictValue" :value="i.dictValue"
                  :label="i.dictLabel"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
          <el-form v-if="settingPage == 'intercept'" label-width="120px">
            <el-form-item label="佩戴提醒状态">
              <el-switch v-model="intercept"></el-switch>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row slot="footer" style="text-align: center;">
        <el-button type="success" style="width: 120px;" @click="addList"
          v-if="['clock', 'silentTime'].indexOf(settingPage) != -1">新增</el-button>
        <el-button style="width: 120px;" @click="resetDeviceInfo">重置</el-button>
        <el-button type="primary" style="width: 120px;" @click="setDeviceInfo">保存</el-button>
      </el-row>
    </el-dialog>
    <el-dialog title="健康阈值设置" :visible.sync="healthInterval" width="1000px" append-to-body>
      <el-form label-width="100px" :data="deviceInterval">
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大心率">
              <el-input v-model="deviceInterval.shouhuan_heart_max"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小心率">
              <el-input v-model="deviceInterval.shouhuan_heart_min"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大高压">
              <el-input v-model="deviceInterval.shouhuan_blood_high_max" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小高压">
              <el-input v-model="deviceInterval.shouhuan_blood_high_min" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大低压">
              <el-input v-model="deviceInterval.shouhuan_blood_low_max" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小低压">
              <el-input v-model="deviceInterval.shouhuan_blood_low_min" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大血氧">
              <el-input v-model="deviceInterval.shouhuan_oxygen_max" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小血氧">
              <el-input v-model="deviceInterval.shouhuan_oxygen_min" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大体温">
              <el-input v-model="deviceInterval.shouhuan_body_max" type="number"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最小体温">
              <el-input v-model="deviceInterval.shouhuan_body_min" type="number"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row slot="footer" style="text-align: center;">
        <el-button style="width: 120px;" @click="closeInterval">取消</el-button>
        <el-button type="primary" style="width: 120px;" @click="subDeviceInterval">保存</el-button>
      </el-row>
    </el-dialog>
    <el-dialog title='健康指标' :visible.sync="health" width="1000px" append-to-body>
      <el-row style="text-align: center;">
        <el-radio-group v-model="tab" style="margin:0 auto 30px;text-align: center;" @input="switchTab">
          <el-radio-button label="0">心率</el-radio-button>
          <el-radio-button label="1">血压</el-radio-button>
          <el-radio-button label="2">血氧</el-radio-button>
          <el-radio-button label="3">体温</el-radio-button>
          <el-radio-button label="4">计步</el-radio-button>
          <el-radio-button label="5">睡眠</el-radio-button>
        </el-radio-group>
      </el-row>
      <template v-if="tab == 0">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="心率" prop="content" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <template v-if="tab == 1">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="舒张压" prop="blood_low_pressure" align="center"></el-table-column>
            <el-table-column label="收缩压" prop="blood_height_pressure" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <template v-if="tab == 2">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="血氧" prop="content" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <template v-if="tab == 3">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="体温" prop="content" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <template v-if="tab == 4">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="步数" prop="step_number" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <template v-if="tab == 5">
        <el-row>
          <div class="echart"></div>
          <el-table :data="rateInfo">
            <el-table-column label="时间" prop="createtime" align="center"></el-table-column>
            <el-table-column label="翻滚次数" prop="roll_number" align="center"></el-table-column>
            <el-table-column label="操作" prop="" align="center"></el-table-column>
          </el-table>
        </el-row>
      </template>
      <pagination v-show="rateTotal > 0" :total="rateTotal" :page.sync="echartsQuery.pageNum"
        :limit.sync="echartsQuery.pageSize" @pagination="setEcharts(tab)" />
    </el-dialog>
    <el-dialog title="设备消息日志" :visible.sync="deviceLog" width="1000px" append-to-body>
      <el-table :data="deviceLogList">
        <!-- <el-table-column label="序号" prop=""></el-table-column> -->
        <el-table-column label="设备ID" prop="device_id"></el-table-column>
        <el-table-column label="用户姓名" prop="name"></el-table-column>
        <el-table-column label="测量时间" prop="createtime"></el-table-column>
        <el-table-column label="消息类型" prop="describe"></el-table-column>
        <!-- <el-table-column label="开始时间" prop=""></el-table-column>
        <el-table-column label="结束时间" prop=""></el-table-column>
        <el-table-column label="持续时间（分钟）" prop=""></el-table-column>
        <el-table-column label="说明" prop=""></el-table-column> -->
      </el-table>
      <pagination v-show="logTotal > 0" :total="logTotal" :page.sync="logQuery.pageNum" :limit.sync="logQuery.pageSize"
        @pagination="getDeviceLog" />
    </el-dialog>
    <el-dialog title="电子围栏" :visible.sync="fenceOpen" width="1200px" :before-close="beforeClose" destroy-on-close :close-on-click-modal="false">
      <div id="map">
        <el-row class="map-tool">
          <el-select size="mini" v-model="fenceName" @change="selectFence">
            <el-option v-for="(item, index) in fenceList" :key="index" :label="item.fenceName"
              :value="item.fenceName"></el-option>
          </el-select>
          <el-button size="mini" type="primary" style="margin-left: 10px;" @click="editAdd">新增</el-button>
          <el-button size="mini" type="warning" @click="editUpdate">修改</el-button>
          <el-button size="mini" type="danger">删除</el-button>
        </el-row>
        <el-form class="update-tool" :model="fenceInfo" label-width="70px" size="mini" v-show="fenceEdit">
          <el-form-item label="围栏名称">
            <el-input size="mini" v-model="fenceInfo.fenceName"></el-input>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-time-picker v-model="fenceInfo.start_time" value-format="HH:mm" placeholder="选择日期时间">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-time-picker v-model="fenceInfo.end_time" :picker-options="{ minTime: fenceInfo.startTime }"
              value-format="HH:mm" placeholder="选择日期时间">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="围栏类型">
            <el-select v-model="fenceInfo.type">
              <el-option v-for="i in fenceType" :key="i.dictValue" :value="i.dictValue" :label="i.dictLabel"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="是否开启">
            <el-select v-model="fenceInfo.state">
              <el-option :value="1" label="是"></el-option>
              <el-option :value="0" label="否"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <el-row class="edit" v-show="fenceEdit">
          <el-dropdown size="small" trigger="click" style="margin-right: 10px;" @command="switchFenceType">
            <el-button type="primary" size="small">
              {{ fenceBtn }}<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="circle">圆形</el-dropdown-item>
              <!-- <el-dropdown-item command="rect">矩形</el-dropdown-item> -->
              <el-dropdown-item command="polygon">多边形</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button class="edit-btn" size="small" type="primary" @click="switchFenceType('circle')">重新绘制</el-button>
          <el-button class="edit-btn" size="small" type="primary" @click="editCancel">取消绘制</el-button>
          <el-button class="edit-btn" size="small" type="primary" @click="subFence">提交</el-button>
        </el-row>
      </div>
    </el-dialog>
    <el-dialog title="设置日志" :visible.sync="settingLog" width="1000px" append-to-body>
      <el-table>
        <el-table-column label="序号" prop=""></el-table-column>
        <el-table-column label="用户姓名" prop=""></el-table-column>
        <el-table-column label="开始时间" prop=""></el-table-column>
        <el-table-column label="结束时间" prop=""></el-table-column>
        <el-table-column label="接受内容" prop=""></el-table-column>
        <el-table-column label="发送指令" prop=""></el-table-column>
        <el-table-column label="发送内容" prop=""></el-table-column>
        <el-table-column label="设置内容" prop=""></el-table-column>
        <el-table-column label="发送状态" prop=""></el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-dialog>
    <el-dialog :visible.sync="openToUpload" width="630px" append-to-body>
      <el-upload class="upload-demo" drag :action="uploadFileUrl" multiple style="text-align: center;"
        :before-upload="handleBeforeUpload" :headers="headers" :on-success="handleUploadSuccess" ref="fileUpload">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip" style="font-size: 15px;line-height: 15px;">仅允许导入xls、xlsx格式文件
          <el-button type="text" @click="downloadTemplate">下载模板</el-button>
        </div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDevice,
  getDevice,
  delDevice,
  addDevice,
  updateDevice,
  getHeartRate,
  getBloodRate,
  getOxygenRate,
  getTempRate,
  getStepRate,
  getRollRate,
  getDeviceLog,
  setDeviceInterval,
  addFence
}
  from "@/api/system/device";
import { listProfile, getProfile } from "@/api/system/profile";
import * as echarts from "echarts";
import AMapLoader from '@amap/amap-jsapi-loader';
import { getToken } from "@/utils/auth";
import axios from 'axios'

export default {
  name: "Device",
  data() {
    return {
      openToUpload: false,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileType: ["xlsx", "xls"],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/system/device/importData",
      // 计步器
      settingOpen: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备列表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceProper: null,
        userid: null,
        sfzid: null,
        telno: null,
        factory: null,
        deviceModel: null,
        deviceId: null,
        simCode: null,
        serialNumber: null,
        grantType: null,
        price: null,
        cost: null,
        payment: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      menuInfo: [],
      settingPage: 'sos',
      clockList: [],
      silentList: [
        {
          timeRange: ['08:00', '09:00'],
          silentStatus: true,
          id: Date.now()
        }
      ],
      timeOnOff: {
        isuse: false,
        openTime: null,
        closeTime: null
      },
      wearStatus: false,
      intercept: false,
      fall: {
        status: false,
        sensitivity: null
      },
      sensitivityList: [],
      healthInterval: false,
      deviceLog: false,
      settingLog: false,
      deviceAttribute: [],
      factoryList: [],
      deviceModel: [],
      grantType: [],
      payment: [],
      selectBuy: false,
      userForm: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        gender: null,
        age: null,
        telOne: null,
        sfzid: null,
        familyAddress: null,
        clientType: null
      },
      userList: [],
      userTotal: null,
      clientType: [],
      selectUser: false,
      userInfo: {},
      health: false,
      tab: 0,
      map: null,
      fenceOpen: false,
      fenceInfo: {},
      fenceName: null,
      echartsQuery: {
        device_id_code: null,
        pageNum: 1,
        pageSize: 10
      },
      rateInfo: [],
      rateTotal: null,
      deviceLogList: [],
      logQuery: {
        device_id: null,
        pageNum: 1,
        pageSize: 10,
      },
      logTotal: null,
      setUser: {},
      sosForm: {},
      intervalForm: {},
      pedoForm: {},
      telForm: {},
      clockForm: {},
      onoffForm: {},
      wearForm: {},
      fallForm: {},
      deviceInterval: {
        shouhuan_heart_max: null,
        shouhuan_heart_min: null,
        shouhuan_blood_high_max: null,
        shouhuan_blood_high_min: null,
        shouhuan_blood_low_max: null,
        shouhuan_blood_low_min: null,
        shouhuan_oxygen_max: null,
        shouhuan_oxygen_min: null,
        shouhuan_body_max: null,
        shouhuan_body_min: null
      },
      fenceEdit: false,
      fenceType: [],
      fenceBtn: '圆形',
      fence: null,
      fenceEditor: null,
      fenceData: {},
      fenceList: [],
      fenceName: null,
      add_flag: true
    };
  },
  created() {
    this.getList();
    this.getUserList()
    this.getDicts('sys_menu_info').then(res => {
      this.menuInfo = res.data
    })
    this.getDicts('sys_clock').then(res => {
      this.clockDate = res.data
    })
    this.getDicts('sys_fall_sensitivity').then(res => {
      this.sensitivityList = res.data
    })
    this.getDicts('sys_device_attribute').then(res => {
      this.deviceAttribute = res.data
    })
    this.getDicts('sys_factory').then(res => {
      this.factoryList = res.data
    })
    this.getDicts('sys_payment').then(res => {
      this.payment = res.data
    })
    this.getDicts('sys_user_type').then(res => {
      this.clientType = res.data
    })
    this.getDicts('sys_fence_type').then(res => {
      this.fenceType = res.data
    })
  },
  watch: {
    'form.grantType': {
      handler(val) {
        if (val && val == 1) {
          this.selectBuy = true
        } else {
          this.selectBuy = false
        }
      }
    },
  },
  methods: {
    subDeviceInterval() {
      setDeviceInterval(this.deviceInterval).then(res => {
        if (res.code == 200) {
          this.$modal.msgSuccess('设置成功')
          this.healthInterval = false
          this.deviceInterval = {
            shouhuan_heart_max: null,
            shouhuan_heart_min: null,
            shouhuan_blood_high_max: null,
            shouhuan_blood_high_min: null,
            shouhuan_blood_low_max: null,
            shouhuan_blood_low_min: null,
            shouhuan_oxygen_max: null,
            shouhuan_oxygen_min: null,
            shouhuan_body_max: null,
            shouhuan_body_min: null
          }
        }
      })
    },
    closeInterval() {
      this.healthInterval = false
      this.deviceInterval = {
        shouhuan_heart_max: null,
        shouhuan_heart_min: null,
        shouhuan_blood_high_max: null,
        shouhuan_blood_high_min: null,
        shouhuan_blood_low_max: null,
        shouhuan_blood_low_min: null,
        shouhuan_oxygen_max: null,
        shouhuan_oxygen_min: null,
        shouhuan_body_max: null,
        shouhuan_body_min: null
      }
    },
    selectSetting(e) {
      this.settingPage = e
    },
    async setDeviceInfo() {
      if (Object.keys(this.sosForm).length && this.settingPage == 'sos') {
        let arr = []
        arr.push(this.sosForm.tel1)
        arr.push(this.sosForm.tel2)
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'sos'
        obj.param = { tels: arr }
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('SOS设置失败')
          }
        })
      } else if (Object.keys(this.intervalForm).length && this.settingPage == 'sos') {
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'interval'
        obj.param = this.intervalForm
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('测量间隔设置失败')
          }
        })
      } else if (Object.keys(this.pedoForm).length && this.settingPage == 'sos') {
        let is_open = this.pedoForm.isopen ? 1 : 0
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'pedo'
        obj.param = { is_open: is_open }
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('计步设置失败')
          }
        })
      } else if (Object.keys(this.telForm).length && this.settingPage == 'sos') {
        let arr = []
        if (this.telForm.tel1 && this.telForm.name1) {
          arr.push({ telno: this.telForm.tel1, name: this.telForm.name1 })
        }
        if (this.telForm.tel2 && this.telForm.name2) {
          arr.push({ telno: this.telForm.tel2, name: this.telForm.name2 })
        }
        if (this.telForm.tel3 && this.telForm.name3) {
          arr.push({ telno: this.telForm.tel3, name: this.telForm.name3 })
        }
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'phl'
        obj.param = arr
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('通讯录设置失败')
          }
        })
      } else if (Object.keys(this.onoffForm).length && this.settingPage == 'sos') {
        this.onoffForm.is_open = this.onoffForm.is_open ? 1 : 0
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'bootoff'
        obj.param = this.onoffForm
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('定时开关机设置失败')
          }
        })
      } else if (Object.keys(this.wearForm).length && this.settingPage == 'sos') {
        this.wearForm.is_open = this.wearForm.is_open ? 1 : 0
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'remove'
        obj.param = this.wearForm
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('定时开关机设置失败')
          }
        })
      } else if (this.clockList.length && this.settingPage == 'sos') {
        this.clockList.map(item => {
          if (item.weeks.length) {
            item.type = 3
          } else {
            item.type = 1
          }
        })
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'remind'
        obj.param = this.clockList
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('闹钟设置失败')
          }
        })
      } else if (Object.keys(this.fallForm).length && this.settingPage == 'sos') {
        this.fallForm.is_open = this.onoffForm.is_open ? 1 : 0
        let obj = {}
        obj.facility_id = this.setUser.fid
        obj.device_id_code = this.setUser.deviceId
        obj.command = 'falldown'
        obj.param = this.fallForm
        await axios({
          method: 'POST',
          url: 'http://43.138.30.29:4200/index.php/api/shouhuan/createcommand',
          headers: {
            Authorization: getToken(),
          },
          data: obj,
        }).then(res => {
          if (res.data && res.data.code == 200) {
            this.$modal.msgSuccess('设置成功')
          } else {
            this.$modal.msgError('跌倒提醒设置失败')
          }
        })
      }
    },
    resetDeviceInfo() {
      this.sosForm = {}
      this.intervalForm = {}
      this.pedoForm = {}
      this.telForm = {}
      this.clockForm = {}
      this.onoffForm = {}
      this.wearForm = {}
      this.fallForm = {}
      this.clockList = []
    },
    handleUploadSuccess(res, file) {
      if (res.code != 200) {
        this.$modal.msgError(`上传模板不正确，请重新上传`);
        this.$modal.closeLoading()
        this.$refs.fileUpload.handleRemove(file);
      } else {
        this.modal.msgSuccess("导入成功");
        this.openToUpload = false
        this.resetQuery()
      }
    },
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
      }
      this.$modal.loading("正在上传文件，请稍候...");
      return true;
    },
    downloadTemplate() {
      this.download('system/device/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    handleUpload() {
      this.openToUpload = true
    },
    switchTab(e) {
      this.tab = e
      this.echartsQuery.pageNum = 1
      this.echartsQuery.pageSize = 10
      this.setEcharts(e)
    },
    setEcharts(tab) {
      let mychart = echarts.init(document.querySelector('.echart'))
      if (tab == 0) {
        mychart.clear()
        getHeartRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let heartBeat = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            heartBeat.push(item.content)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '心率',
                data: heartBeat,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      } else if (tab == 1) {
        mychart.clear()
        getBloodRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let high = []
          let low = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            high.push(item.blood_height_pressure)
            low.push(item.blood_low_pressure)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '高压',
                data: high,
                type: 'line'
              },
              {
                name: '低压',
                data: low,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      } else if (tab == 2) {
        mychart.clear()
        getOxygenRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let heartBeat = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            heartBeat.push(item.content)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '血氧',
                data: heartBeat,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      } else if (tab == 3) {
        mychart.clear()
        getTempRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let heartBeat = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            heartBeat.push(item.content)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '体温',
                data: heartBeat,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      } else if (tab == 4) {
        mychart.clear()
        getStepRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let heartBeat = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            heartBeat.push(item.step_number)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '计步',
                data: heartBeat,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      } else if (tab == 5) {
        mychart.clear()
        getRollRate(this.echartsQuery).then(data => {
          this.rateInfo = data.rows
          this.rateTotal = data.total
          let createTime = []
          let heartBeat = []
          this.rateInfo = this.rateInfo.reverse()
          this.rateInfo.map(item => {
            createTime.push(item.createtime)
            heartBeat.push(item.roll_number)
          })
          let option = {
            xAxis: {
              type: 'category',
              data: createTime,
              boundaryGap: false,
              nameTextStyle: {
                fontSize: 10
              }
            },
            legend: {},
            yAxis: {
              type: 'value'
            },
            series: [
              {
                name: '翻滚次数',
                data: heartBeat,
                type: 'line'
              }
            ]
          }
          mychart.setOption(option)
        })
      }
    },
    subFence() {
      this.fenceEditor.close()
      if (this.add_flag) {
        this.fenceInfo.deviceid = this.setUser.deviceId
        console.log(this.fenceInfo);
        // addFence(this.fenceInfo).then(res => {

        // })
        this.fenceList.push(this.fenceInfo)
      } else {
        this.fenceList.map(item => {
          if (item.fenceName == this.fenceInfo.fenceName) {
            item = this.fenceInfo
          }
        })
      }
      this.fenceEdit = false
    },
    switchFenceType(e) {
      if (e == 'circle') {
        if (this.fence) {
          this.fenceEditor.close()
          this.map.remove(this.fence)
        }
        this.fenceBtn = '圆形'
        this.fenceInfo.geofence_type = 0
        let radius = 500
        let lnglat = this.map.getCenter()
        this.fence = new AMap.Circle({
          center: lnglat,
          radius: radius, //半径
          borderWeight: 3,
          fillOpacity: 0.4,
          strokeStyle: 'dashed',
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: '#1791fc',
          zIndex: 50,
        })
        this.map.add(this.fence);
        // 缩放地图到合适的视野级别
        // this.map.setFitView([this.circle])
        this.fenceEditor = new AMap.CircleEditor(this.map, this.fence)
        this.fenceEditor.open()
        this.fenceEditor.on('end', (e) => {
          this.fenceInfo.radius = radius
          this.fenceInfo.lnglat = lnglat
        })
        this.fenceEditor.on('adjust', (e) => {
          radius = e.radius
        })
        this.fenceEditor.on('move', (e) => {
          lnglat = e.lnglat
        })
      } else if (e == 'rect') {
        if (this.fence) {
          this.fenceEditor.close()
          this.map.remove(this.fence)
        }
        this.fenceBtn = '矩形'
        let center = this.map.getCenter()
        var southWest = new AMap.LngLat(center.lng + 0.01, center.lat + 0.005)
        var northEast = new AMap.LngLat(center.lng - 0.01, center.lat - 0.005)

        var bounds = new AMap.Bounds(southWest, northEast)

        this.fence = new AMap.Rectangle({
          bounds: bounds,
          fillColor: 'blue',
          fillOpacity: 0.5,
          cursor: 'pointer',
          zIndex: 50,
        })

        this.map.add(this.fence);
        // 缩放地图到合适的视野级别

        this.fenceEditor = new AMap.RectangleEditor(this.map, this.fence)
        this.fenceEditor.open()
      } else if (e == 'polygon') {
        if (this.fence) {
          this.fenceEditor.close()
          this.map.remove(this.fence)
        }
        this.fenceBtn = '多边形'
        let center = this.map.getCenter()
        let path = [
          [center.lng - 0.01, center.lat + 0.005],
          [center.lng + 0.01, center.lat + 0.005],
          [center.lng + 0.01, center.lat - 0.005],
          [center.lng - 0.01, center.lat - 0.005]
        ]
        this.fence = new AMap.Polygon({
          path: path,
          strokeColor: "#FF33FF",
          strokeWeight: 6,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: '#1791fc',
          zIndex: 50,
          bubble: true,
          draggable: true,
        })
        this.map.add(this.fence);
        this.fenceEditor = new AMap.PolygonEditor(this.map, this.fence);
        this.fenceEditor.open();
        this.fenceEditor.on('end', (e) => {
          this.fenceInfo.path = e.target._opts.path
        })
      }
    },
    editAdd() {
      this.fenceEdit = true
      this.add_flag = true
      if (this.fence == null) {
        this.switchFenceType('circle')
      }
    },
    editCancel() {
      this.fenceEdit = false
      this.map.remove(this.fence)
      this.fence = null
      this.fenceEditor = null
    },
    editUpdate() {
      this.add_flag = false
      this.fenceEdit = true
      if (this.fence) {
        if (this.fence._opts.radius) {
        this.fenceEditor = new AMap.CircleEditor(this.map, this.fence)
        let radius = this.fenceInfo.radius
        let lnglat = this.fenceInfo.lnglat
        this.fenceEditor.open()
        this.fenceEditor.on('end', (e) => {
          this.fenceInfo.radius = radius
          this.fenceInfo.lnglat = lnglat
        })
        this.fenceEditor.on('adjust', (e) => {
          radius = e.radius
        })
        this.fenceEditor.on('move', (e) => {
          lnglat = e.lnglat
        })
        }
      }
    },
    selectFence(e) {
      this.fenceList.map(item => {
        if (item.fenceName == e) {
          if (this.fence) {
            this.map.remove(this.fence)
          }
          if (item.type == 'circle') {
            this.fence = new AMap.Circle({
              center: item.lnglat,
              radius: item.radius, //半径
              borderWeight: 3,
              fillOpacity: 0.4,
              strokeStyle: 'dashed',
              strokeDasharray: [10, 10],
              // 线样式还支持 'dashed'
              fillColor: '#1791fc',
              zIndex: 50,
            })
            this.map.add(this.fence);
            this.map.setCenter(item.lnglat)
            this.map.setFitView([this.fence])
          }
        }
      })
    },
    createMap() {
      window._AMapSecurityConfig = {
        securityJsCode: 'e91e92cbd76e89c48f3ff1d6180f288c'
      }
      AMapLoader.load({
        key: 'c968deab485d6e688e7c68689722ffb4',
        version: '2.0'
      }).then(AMap => {
        this.map = new AMap.Map('map', {
          zoom: 15
        })
        this.map.plugin([
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.Geolocation',
          'AMap.CircleEditor',
          'AMap.RectangleEditor',
          'AMap.PolygonEditor'], () => {
            this.map.addControl(new AMap.ToolBar({
              position: 'RT'
            }))
            this.map.addControl(new AMap.Scale())
            var geolocation = new AMap.Geolocation({
              enableHighAccuracy: true, // 是否使用高精度定位，默认：true
              timeout: 10000, // 设置定位超时时间，默认：无穷大
              offset: [10, 20],  // 定位按钮的停靠位置的偏移量
              zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
              position: 'RB' //  定位按钮的排放位置,  RB表示右下
            })

            geolocation.getCurrentPosition((status, result) => {
              if (status == 'complete') {
                this.$modal.msgSuccess('定位成功')
                this.map.setCenter([result.position.lng, result.position.lat])
              } else {
                this.$modal.msgError('获取定位失败')
              }
            });
          })
      })
    },
    getUserList() {
      this.loading = true;
      listProfile(this.userForm).then(response => {
        this.userList = response.rows;
        this.userTotal = response.total;
        this.loading = false;
      });
    },
    searchUser() {
      this.userForm.pageNum = 1
      this.getUserList()
    },
    resetUser() {
      this.userForm = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        gender: null,
        age: null,
        telOne: null,
        sfzid: null,
        familyAddress: null,
        clientType: null
      }
      this.getUserList()
    },
    checkUser(e) {
      if (e.length > 1) return this.$modal.msgError('只能选择一人')
      this.userInfo = e[0]
    },
    toSelect() {
      this.selectUser = true
    },
    checkUserConfirm() {
      if (Object.keys(this.userInfo).length) {
        this.form.name = this.userInfo.name
        this.form.sfzid = this.userInfo.sfzid
        this.form.telno = this.userInfo.telOne
        this.form.userid = this.userInfo.id
        this.selectUser = false
      } else {
        this.$modal.msgError('请选择用户')
      }
    },
    checkUserCancel() {
      this.selectUser = false
      this.userInfo = {}
    },
    addList() {
      if (this.settingPage == 'clock') {
        let obj = {
          clockName: null,
          time: null,
          isopen: true,
          weeks: [],
          clockId: Date.now()
        }
        this.clockList.push(obj)
      } else if (this.settingPage == 'silentTime') {
        let obj = {
          timeRange: [new Date(8, 0), new Date(9, 0)],
          silentStatus: true,
          id: Date.now()
        }
        this.silentList.push(obj)
      }
    },
    deleteSilent(e) {
      this.silentList.map((item, index) => {
        if (item.id == e) {
          this.silentList.splice(index, 1)
        }
      })
    },
    deleteClock(e) {
      this.clockList.map((item, index) => {
        if (item.clockId == e) {
          this.clockList.splice(index, 1)
        }
      })
    },
    openSetting(e, row) {
      this.echartsQuery.device_id_code = row.deviceId
      this[e] = true
      if (e == 'health') {
        setTimeout(() => {
          this.setEcharts(0)
        }, 100);
      } else if (e == 'fenceOpen') {
        this.createMap()
        this.setUser = row
      } else if (e == 'deviceLog') {
        this.getDeviceLog()
      } else if (e == 'settingOpen') {
        this.setUser = row
      } else if (e == 'healthInterval') {
        this.setUser = row
      }
    },
    getDeviceLog() {
      getDeviceLog(this.logQuery).then(res => {
        this.deviceLogList = res.rows
        this.deviceLogList.map(item => {
          if (item.alarm_type == 0) {
            item.describe = '无效'
          } else if (item.alarm_type == 16) {
            item.describe = 'SOS报警'
          } else if (item.alarm_type == 17) {
            item.describe = '低电量'
          } else if (item.alarm_type == 20) {
            item.describe = '手表未佩戴'
          } else if (item.alarm_type == 21) {
            item.describe = '跌倒报警'
          } else if (item.alarm_type == 22) {
            item.describe = '心率异常'
          }
        })
        this.logTotal = res.total
      })
    },
    beforeClose(done) {
      this.map.destroy()
      done()
    },
    /** 查询设备列列表 */
    async getList() {
      this.loading = true;
      let { data: grantType } = await this.getDicts('sys_grant_type')
      this.grantType = grantType
      let { data: deviceModel } = await this.getDicts('sys_device_type')
      this.deviceModel = deviceModel
      await listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.deviceList.map(item => {
          if (item.deviceModel || item.deviceModel == 0) {
            item.deviceType = this.deviceModel[item.deviceModel].dictLabel
          }
          if (item.grantType || item.grantType == 0) {
            item.granttype = this.grantType[item.grantType].dictLabel
          }
          item.online = item.online_statis == 1 ? '在线' : item.online_statis == 0 ? '离线' : ''
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deviceProper: null,
        userid: null,
        sfzid: null,
        telno: null,
        factory: null,
        deviceModel: null,
        deviceId: null,
        simCode: null,
        serialNumber: null,
        grantType: null,
        price: null,
        cost: null,
        payment: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备列";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDevice(id).then(response => {
        this.form = response.data;
        this.deviceList.map(item => {
          if (item.id == id) {
            this.form.name = item.name
          }
        })
        this.open = true;
        this.title = "修改设备列";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            console.log('form', this.form);
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备列编号为"' + ids + '"的数据项？').then(function () {
        return delDevice(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/device/export', {
        ...this.queryParams
      }, `device_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.top {
  margin-bottom: 20px;
}

.setting-inp {
  width: 350px;
}

.clock-item {
  margin: 20px 0 0 0;
  border-bottom: 1px solid #ccc;
}

.clock-input {
  margin: 0 10px 0 0;
  width: 200px;
}

.clock-switch {
  margin: 0 20px;
}

.search-inp {
  width: 200px
}

.inp /deep/ .el-input__inner {
  color: #000 !important;
  /* cursor: pointer; */
}

.echart {
  margin: 0 auto;
  width: 500px;
  height: 250px;
}

#map {
  position: relative;
  width: 1160px;
  height: 700px;
}

.map-tool {
  position: relative;
  padding: 10px;
  z-index: 1;
}

.update-tool {
  position: relative;
  margin: 0px 0 0 10px;
  padding: 10px;
  width: 330px;
  height: 240px;
  background-color: rgba(255, 255, 255, .7);
  z-index: 1;
}

.edit {
  position: absolute;
  bottom: 5px;
  right: 5px;
  z-index: 1;
}

.edit-btn {
  width: 80px;
}
</style>
