<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="所属医生" prop="doctorId">
          <el-input v-model="queryParams.doctorName" placeholder="请输入所属医生" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item label="绑定用户" prop="watchUserName">
          <el-input v-model="queryParams.watchUserName" placeholder="请输入绑定用户" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item> -->
        <el-form-item label="设备编号" prop="deviceNumber">
          <el-input v-model="queryParams.deviceNumber" placeholder="请输入设备编号" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="绑定状态" prop="lifeStatus">
          <el-select v-model="queryParams.lifeStatus" placeholder="请选择绑定状态" clearable size="small">
            <!-- <el-option label="请选择字典生成" value="" /> -->
            <el-option v-for="item in lifeStatusOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择设备状态" clearable size="small">
            <!-- <el-option label="请选择字典生成" value="" /> -->
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </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="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
            @click="handleExport" v-hasPermi="['watchApi:deviceInfo:export']">导出</el-button>
        </el-col>
  
        <el-col :span="1.5">
          <el-popover placement="right" width="400" trigger="click" @show="refreshPageAlarm">
            <div>
              <div class="clearfix" style="padding: 10px; border-bottom: 1px solid #ebeef5;">
                <span>预警通知</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="markAllAsRead"
                  v-if="alarmData && alarmData.length > 0">一键已读</el-button>
              </div>
              <div class="notification-container" v-infinite-scroll="load">
                <el-card v-for="(notification, index) in alarmData" :key="index" class="notification-card">
                  <!-- 红点标记 -->
                  <div v-if="notification.status === 0" class="red-dot"></div>
                  <el-row @click="goDetailPage(notification)">
                    <el-col :span="20" :style="{ opacity: notification.status == 1 ? 0.6 : 1 }">
                      <div class="notification-title">{{ notification.title }}</div>
                      <div class="notification-desc">{{ notification.description }}</div>
                      <div class="notification-time">{{ notification.dateTime }}</div>
                    </el-col>
                    <el-col :span="4" class="notification-status">
                      <el-button style="float: right; padding: 3px 0" type="text" size="mini"
                        @click="readItem(notification)">阅读</el-button>
                    </el-col>
                  </el-row>
                </el-card>
  
              </div>
            </div>
            <!-- 触发弹出框的按钮 -->
            <el-button type="info" plain icon="el-icon-bell" size="mini" slot="reference">预警通知</el-button>
          </el-popover>
        </el-col>
  
        <el-col :span="1.5">
          <el-button plain icon="el-icon-setting" size="mini" @click="sendMsg" :disabled="sendMsgButtonDisabled"
            v-hasPermi="['watchApi:deviceInfo:edit']">看课提醒</el-button>
        </el-col>
  
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <el-table v-loading="loading" :data="deviceInfoList" @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="doctorName" />
        <el-table-column  label="绑定用户"  align="center">
          <template slot-scope="scope">
              <el-link :underline="false" prop="item.userId" v-for="(item, index) in scope.row.users"  v-if="scope.row.users"  @click="handleDetails(scope.row.deviceId,item.userId,0)">{{item.nickName}}</el-link>
          </template>
        </el-table-column>
        <el-table-column  label="绑定家人用户"  align="center">
            <template slot-scope="scope">
                <el-link :underline="false" prop="item.userId" v-for="(item, index) in scope.row.familyUsers"  v-if="scope.row.familyUsers"  @click="handleDetails(scope.row.deviceId,item.userId,1)">{{item.nickName}}</el-link>
            </template>
        </el-table-column>
        <el-table-column label="设备编号" align="center" prop="deviceNumber" width="150"/>
        <el-table-column label="电量" align="center" prop="battery" />
        <el-table-column label="信号" align="center" prop="rssi" />
        <el-table-column label="绑定状态" align="center" prop="lifeStatusOut" />
        <el-table-column label="设备状态" align="center" prop="statusOut" />
        <el-table-column label="最新健康数据" align="center" width="120" >
          <template slot-scope="scope">
            <span 
              @click="showHealthData(scope.row.deviceNumber)"
              style="cursor: pointer; color: #409EFF;"
            >
              最新数据
            </span>
            <el-tag size="mini" :type="scope.row.isNormal == '异常'?'danger':'primary'">{{scope.row.isNormal}}</el-tag>
  
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetails(scope.row.deviceId,null,0)"
              v-hasPermi="['watchApi:deviceInfo:query']">查询详情</el-button>
            <el-button size="mini" type="text" icon="el-icon-phone-outline" @click="handleSoSPeople(scope.row.deviceNumber)"
              v-hasPermi="['watchApi:deviceInfo:query']">查看紧急联系人</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 弹窗展示紧急联系人列表 -->
      <el-dialog :visible.sync="sosVisible" title="紧急联系人" width="50%">
          <el-table v-loading="sosLoading" :data="sosPeopleList">
            <el-table-column prop="name" label="联系人" align="center" />
            <el-table-column prop="number" label="电话" align="center" />
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="sosVisible = false">关闭</el-button>
          </div>
      </el-dialog>
      <!-- 弹窗展示最新健康数据列表 -->
      <el-dialog :visible.sync="healthDataDialogVisible" title="最新健康数据" width="50%">
          <el-table :data="selectedHealthData" :row-class-name="rowClassName">
            <el-table-column prop="type" label="类型" align="center" />
            <el-table-column prop="data" label="数值" align="center" />
            <el-table-column prop="status" label="状态" align="center" />
            <el-table-column prop="date" label="时间" align="center" />
          </el-table>
          <div slot="footer" class="dialog-footer">
            <el-button @click="healthDataDialogVisible = false">关闭</el-button>
          </div>
        </el-dialog>
        
        
      <!-- 消息发送弹窗 -->
      <el-dialog :visible.sync="showSend" :title="senFormTitle" width="40%">
        <el-form :model="sendForm" :rules="sendRules" label-width="100px" ref="sendForm">
          <el-form-item label="标题" prop="title">
            <el-input  v-model="sendForm.title"></el-input>
          </el-form-item>
          <el-form-item label="详情" prop="description">
            <el-input type="textarea" v-model="sendForm.description"></el-input>
          </el-form-item>
        
        </el-form>      
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitSendForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
  
      <setUpUserInfoDialog ref="setUpUserInfoDialog" />
      <!-- 其他设置弹窗 -->
      <SetInfoDialog ref="setInfoDialog" @refreshList="getList" />
      <!-- 下发通讯录弹窗 -->
      <Phonebook ref="phonebook" />
      <!-- 设置闹钟 -->
      <Clockalarm ref="clockalarm" />
      <!-- 设置久坐 -->
      <Sedentary ref="sedentary" />
    </div>
  </template>
  
  <script>
  import { myDeviceInfo, getDeviceInfo, delDeviceInfo, addDeviceInfo, updateDeviceInfo, exportMy, queryAlarm, setStatus, queryPageAlarm,queryLastHealthData,querySos} from "@/api/watch/deviceInfo";
  import { getAllUserlist } from "@/api/company/companyUser";
  import { messageSend } from "@/api/watch/deviceInfoSet.js";
  import setUpUserInfoDialog from "@/components/DeviceInfo/SettingDialog/setUpUserInfoDialog.vue";
  import SetInfoDialog from "@/components/DeviceInfo/SettingDialog/SetInfoDialog.vue";
  import Phonebook from "@/components/DeviceInfo/SettingDialog/Phonebook.vue";
  import Clockalarm from "@/components/DeviceInfo/SettingDialog/Clockalarm.vue";
  import Sedentary from "@/components/DeviceInfo/SettingDialog/Sedentary.vue";
  // import {getInfo} from "@/api/login"
  
  export default {
    name: "my",
    components: {
      setUpUserInfoDialog,
      SetInfoDialog,
      Phonebook,
      Clockalarm,
      Sedentary
    },
    data() {
      return {
        sosVisible: false,
        sosLoading: false,
        sosPeopleList: [],
        // healthDataloading: false,
        deviceInfoList: [],  // 设备信息列表
        healthDataDialogVisible: false,  // 控制弹窗显示
        selectedHealthData: [],  // 选中设备的健康数据列表
        roles: null, // 登录用户信息
        // 查询参数
        queryAlarmParams: {
          pageNum: 1,
          pageSize: 10
        },
        alarmTotal: 0,
        alarmData: [],
        hasMore: true,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 选中编号数组
        deviceNumbers: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 设备信息表格数据
        deviceInfoList: [],
        // 公司信息表格数据
        companyList: [],
        // 公司员工信息表格数据
        companyUserList: [],
        doctorList:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          companyId: null,
          deviceNumber: null,
          battery: null,
          rssi: null,
          status: null,
          lifeStatus: undefined
        },
        // 表单参数
        form: {
          companyId: '',
          companyUserId:"",
          doctorId:"",
          deviceNumber: '',
          battery: '',
          rssi: '',
          status: 1,
        },
        // 表单校验
        rules: {
          // companyId: [
          //   { required: true, message: "请选择所属公司", trigger: "change" }
          // ],
          deviceNumber: [
            { required: true, message: "设备编号不能为空", trigger: "blur" },
            { pattern: /^\d{15}$/, message: "设备编号必须是15位数字", trigger: "blur" }
          ],
        },
        sendRules:{
          title: [
            { required: true, message: '标题不能为空', trigger: 'blur' },
            { max: 15, message: '标题最多15个字节', trigger: 'blur' }
          ],
          description: [
            { required: true, message: '详情不能为空', trigger: 'blur' },
            { max: 240, message: '详情最多240个字节', trigger: 'blur' }
          ]
        },
        options: [{
          value: '0',
          label: 'OFFLINE'
        }, {
          value: '1',
          label: 'ONLINE'
        }, {
          value: '2',
          label: 'UNACTIVE'
        }, {
          value: '3',
          label: 'DISABLE'
        }, {
          value: '4',
          label: 'NOT EXIST'
        }],
        lifeStatusOptions:[{
          value: '0',
          label: '空置'
        },{
          value: '1',
          label: '已送出'
        },{
          value: '2',
          label: '已激活'
        }],
        // 是否展示设置按钮面板
        // showSettingBtn: true,
        showSend:false,
        senFormTitle:'',
        sendForm:{
          title:'',
          description:''
        },
      };
    },
    created() {
      this.getList();
    },
    computed: {
      // 计算属性来控制按钮的disabled状态
      sendMsgButtonDisabled() {
        return this.deviceNumbers.length === 0;
      }
    },
    methods: {
      rowClassName({row}) {
        if (row.status && row.status.includes('偏')) {
          // console.log("=============================" + JSON.stringify(row.status, null, 2))
          return 'text-red';
          // return true
        }
        return '';
      },
      showHealthData(deviceId) {
        // 模拟获取最新健康数据，实际应用中可能需要通过 API 获取数据
        queryLastHealthData({deviceId}).then(response => {
          this.selectedHealthData = response.data;
        });
        this.healthDataDialogVisible = true;  // 显示弹窗
      },
      shouldShowCompanySelect() {
        // 根据登录用户信息判断是否显示所属公司选择框
        const roles = this.$store.getters.roles; // 获取角色信息
        // 只有包含 'admin' 或 'common' 才返回 true
        return (roles.includes('admin') || roles.includes('common'));
      },
      load() {
        if (this.hasMore) this.refreshPageAlarm()
      },
      markAllAsRead() {
        // 提取所有通知的 ID
        const ids = this.alarmData.map(notification => notification.id);
        // 调用 setStatus 方法将这些通知标记为已读
        setStatus(ids).then(response => {
          if (response.code == 200) {
            this.alarmData = this.alarmData.map(item => ({
              ...item,
              status: 1
            }))
          }
        })
          .catch(error => {
            console.error('一键已读操作失败:', error);
          });
      },
      //设置已读
      readItem(notification) {
        if (notification.status == 1) return
        setStatus([notification.id]).then(response => {
          if (response.code == 200) {
            notification.status = 1
          }
        })
          .catch(error => {
            console.error('更新状态失败:', error);
          });
      },
      getAlarm() {
        queryAlarm(null).then(response => {
          this.alarmData = response.data
        });
      },
      refreshPageAlarm() {
        this.alarmData = []
        this.queryAlarmParams.pageNum = 1
        this.hasMore = true
        this.getPageAlarm()
      },
      // 获取分页预警通知
      getPageAlarm() {
        queryPageAlarm(this.queryAlarmParams).then(response => {
          if (response.code == 200) {
            const list = response.rows
            this.alarmTotal = response.total
            this.alarmData = this.alarmData.concat(list)
            this.queryAlarmParams.pageNum++
            if (this.alarmData.length == this.alarmTotal) {
              this.hasMore = false
            }
          }
        });
      },
      // 查看预警通知详情
      goDetailPage(row) {
        // 如果sos跳转地图
        if (row.extra == "sos") {
  
        }
      },
      /** 处理查询详情按钮点击事件 */
      handleDetails(deviceId,userId,type) {
        this.$router.push({ name: 'details', params: { deviceId:deviceId,userId:userId,selectType:type } });
      },
  
      /** 查询设备信息列表 */
      getList() {
        this.loading = true;
        myDeviceInfo(this.queryParams).then(response => {
          this.deviceInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          deviceId: null,
          createTime: null,
          createBy: null,
          updateTime: null,
          updateBy: null,
          companyName: null,
          companyId: '',
          companyUserId: '',
          deviceNumber: null,
          battery: null,
          rssi: null,
          status: 0
        };
        this.resetForm("form");
      },
  
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.deviceId)
        this.deviceNumbers = selection.map(item => item.deviceNumber)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 发送消息 */
      sendMsg() {
        console.log("点击事件触发，item 为：", this.deviceNumbers);
          this.showSend=true;
          this.senFormTitle = "看课提醒";
          this.sendForm.title ="看课提醒";
      },
      submitSendForm(){
        // 首先调用表单验证方法
        this.$refs.sendForm.validate((valid) => {
          if (valid) {
            // 如果验证通过，则发送消息
            console.log("=============================2" +JSON.stringify( this.sendForm, null, 2));
            messageSend({
              deviceNumber: this.deviceNumbers.join(","),
              title: this.sendForm.title,
              description: this.sendForm.description,
              type: 'study'
            }).then(response => {
                if(response.code === 200){
                  this.msgSuccess("发送成功");
                  this.showSend = false;
                }
              });
          } else {
            // 如果验证失败，则提示用户
            console.log('表单验证失败');
            this.$message.error('请检查表单内容');
            return false;
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有设备信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportMy(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => { });
      },
      // 查询紧急联系人
      handleSoSPeople(deviceId) {
        this.sosLoading = true;
        querySos({deviceId: deviceId}).then(res=>{
          this.sosLoading = false
          this.sosPeopleList = res.data || []
          this.sosVisible = true
        }).catch(()=>{
          this.sosLoading = false
        })
      }
    }
  };
  </script>
  <style>
  .text-red {
    color: red;
  }
  </style>
  <style lang="scss" scoped>
  .notification-container {
    padding: 10px 0;
    height: 80vh;
    overflow-y: auto;
  }
  
  .notification-container::-webkit-scrollbar {
    width: 4px;
    /*  设置纵轴（y轴）轴滚动条 */
    height: 4px;
    /*  设置横轴（x轴）轴滚动条 */
  }
  
  /* 滚动条滑块（里面小方块） */
  .notification-container::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(144, 147, 153, 0.3);
  }
  
  /* 滚动条轨道 */
  .notification-container::-webkit-scrollbar-track {
    border-radius: 0;
  }
  
  .notification-card {
    position: relative;
    padding-right: 10px;
    margin-bottom: 10px;
    cursor: pointer;
  
    &:hover {
      background: #edf8ff;
    }
  }
  
  .red-dot {
    position: absolute;
    top: 10px;
    right: 10px;
    width: 8px;
    height: 8px;
    background-color: red;
    border-radius: 50%;
  }
  
  .notification-title {
    font-weight: bold;
    font-size: 16px;
  }
  
  .notification-desc {
    margin-top: 5px;
    color: #666;
  }
  
  .notification-time {
    margin-top: 10px;
    font-size: 12px;
    color: #999;
  }
  
  .notification-status {
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  
  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }
  
  .text {
    font-size: 14px;
  }
  
  .item {
    margin-bottom: 18px;
  }
  
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  
  .clearfix:after {
    clear: both
  }
  
  .box-card {
    width: 480px;
  }
  </style>
  