<template>
  <div class="app-container" v-loading="loading">
    <div v-if="deviceData">
      <el-card class="device-info-card">
        <!-- 设备基本信息展示区 -->
        <div class="device-info-container">
          <div class="device-header">
            <!-- 主要信息 -->
            <div class="device-title">
              <i class="el-icon-monitor"></i>
              <div class="device-name">
                {{ deviceData.deviceName | dv }}
                <el-link type="primary" v-if="isSysAdmin()" icon="el-icon-edit" @click="handleEditDevice"></el-link>
              </div>
            </div>

            <!-- 操作按钮组 -->
            <el-row class="device-actions">
              <el-button size="small" plain type="warning" icon="el-icon-switch-button" v-if="!isOpen"
                         @click="handleSwitch(true)">强制开启
              </el-button>
              <el-button size="small" plain type="warning" icon="el-icon-switch-button" v-if="isOpen"
                         @click="handleSwitch(false)">强制关闭
              </el-button>
              <el-button size="small" plain icon="el-icon-refresh"
                         @click="refreshIot(deviceId, true, DeviceOnlineType.COMMAND)">刷新设备信息
              </el-button>
            </el-row>
          </div>

          <!-- 次要信息 -->
          <div class="device-info">
            <div class="info-item">
              <i class="el-icon-document"></i>
              <span class="label">SN:</span>
              <span>{{ deviceData.deviceNo | dv }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-connection"></i>
              <span class="label">MAC-1:</span>
              <span>{{ deviceData.mac | dv }}</span>
              <dot-status v-if="deviceData.mac" :active="deviceData.onlineStatus1 === OnlineStatus.ONLINE"/>
            </div>
            <div class="info-item" v-if="deviceData.mac2">
              <i class="el-icon-connection"></i>
              <span class="label">MAC-2:</span>
              <span>{{ deviceData.mac2 | dv }}</span>
              <dot-status :active="deviceData.onlineStatus2 === OnlineStatus.ONLINE"/>
            </div>
            <div class="info-item">
              <i class="el-icon-collection-tag"></i>
              <span class="label">型号:</span>
              <span>{{ deviceData.model | dv }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-cpu"></i>
              <span class="label">SIM卡:</span>
              {{ deviceData.imsi | dv }}
            </div>
            <div class="info-item">
              <i class="el-icon-cpu"></i>
              <span class="label">产品ID:</span>
              <span>{{ deviceData.productId | dv }}</span>
            </div>
            <div class="info-item">
              <i class="el-icon-open"></i>
              <span class="label">开关状态:</span>
              <dict-tag :options="dict.type.device_power_status" :value="deviceData.powerStatus" size="mini"/>
            </div>
            <div class="info-item">
              <i class="el-icon-collection-tag"></i>
              <span class="label">功能:</span>
              <dict-tag :options="dict.type.model_type" :value="deviceData.modelTags" size="mini"/>
            </div>

          </div>
        </div>
      </el-card>

      <el-row :gutter="16" class="equal-height-row">
        <el-col :lg="18" :xs="24">
          <el-card class="box-card equal-height-card">
            <template #header>
              <el-row type="flex" style="justify-content: space-between;align-items: center">
                <div class="card-title">
                  <i class="el-icon-data-line"></i>
                  实时信息
                </div>
                <div class="last-update-time">
                  <i class="el-icon-time"></i>
                  最后更新: {{ deviceData.lastPullTime | dv }}
                </div>
              </el-row>
            </template>

            <div class="realtime-info">
              <el-row :gutter="16">
                <!--时长信息-->
                <el-col :span="8">
                  <div class="info-section">
                    <div class="section-title">
                      <span><i class="el-icon-time"></i>时长信息</span>
                    </div>
                    <div class="data-grid">
                      <div class="data-item">
                        <div class="item-label">开启时长
                          <el-tooltip content="设置设备开启时长" placement="top">
                            <el-link @click="handleSetDuration" type="primary" icon="el-icon-edit" class="reset-btn"></el-link>
                          </el-tooltip>
                        </div>
                        <div class="item-value">{{ deviceData.duration| dv }} s</div>
                      </div>
                    </div>
                  </div>
                </el-col>
                <!-- 电量信息 -->
                <el-col :span="8">
                  <div class="info-section">
                    <div class="section-title">
                      <span><i class="el-icon-odometer"></i>电力参数</span>
                    </div>
                    <div class="data-grid">
                      <div class="data-item">
                        <div class="item-label">电压</div>
                        <div class="item-value">{{ deviceData.voltage | fix2 | dv }} V</div>
                      </div>
                      <div class="data-item">
                        <div class="item-label">电流</div>
                        <div class="item-value">{{ deviceData.electricity | fix2 | dv }} A</div>
                      </div>
                      <div class="data-item">
                        <div class="item-label">功率</div>
                        <div class="item-value">{{ deviceData.realTimePower | fix2 | dv }} W</div>
                      </div>
                      <div class="data-item">
                        <div class="item-label">电压系数</div>
                        <div class="item-value">{{ deviceData.vxs | fix2 | dv }}</div>
                      </div>
                    </div>
                  </div>
                </el-col>

                <!-- 累计用电信息 -->
                <el-col :span="8">
                  <div class="info-section">
                    <div class="section-title">
                      <span><i class="el-icon-reading"></i>累计用电</span>

                      <div class="reset-time">
                        最近重置: {{ deviceData.lastInitReading | dv }}
                      </div>
                    </div>
                    <div class="data-grid">
                      <div class="data-item">
                        <div class="item-label">累计用电量</div>
                        <div class="item-value">{{ deviceData.totalElectriQuantity | money | dv }} 度</div>
                      </div>
                      <div class="data-item">
                        <div class="item-label">
                          电量读数
                          <el-tooltip content="重置读数" placement="top">
                            <el-link @click="handleInitReading" type="primary" icon="el-icon-refresh"
                                     class="reset-btn"></el-link>
                          </el-tooltip>
                        </div>
                        <div class="item-value">
                          {{ deviceData.totalElectriQuantity - deviceData.initReading | money | dv }} 度
                        </div>
                      </div>
                      <div class="data-item">
                        <div class="item-label">
                          电量系数
                          <el-tooltip content="修改电量系数" placement="top">
                            <el-link @click="handleSetWxs" type="primary" icon="el-icon-edit"
                                     class="reset-btn"></el-link>
                          </el-tooltip>
                        </div>
                        <div class="item-value">{{ deviceData.wxs | dv }}</div>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>

        <el-col :lg="6" :xs="20">
          <el-card class="box-card equal-height-card">
            <el-descriptions title="归属信息" :column="1">
              <el-descriptions-item label="所属商户">
                <user-link :text="deviceData.userName" :id="deviceData.userId"/>
              </el-descriptions-item>
              <el-descriptions-item label="店铺名称">
                <store-link :name="deviceData.storeName" :id="deviceData.storeId"/>
              </el-descriptions-item>
              <el-descriptions-item label="备注">{{ deviceData.remark | dv }}</el-descriptions-item>
            </el-descriptions>
            <template>
              <el-row type="flex">
                <template v-if="isSysAdmin()">
                  <el-button size="small"  plain icon="el-icon-link" type="danger" @click="handleUnbind" v-if="deviceData.userId != null">解绑商户</el-button>
                  <bind-mch-button v-else :deviceId="deviceData.deviceId" :deviceNo="deviceData.deviceNo" @success="getDevice" style="margin-left: 0.5em"/>
                </template>
              </el-row>
            </template>
          </el-card>
        </el-col>

      </el-row>
      <el-card class="box-card">
        <el-tabs>
          <el-tab-pane label="套餐列表" :lazy="true">
            <suit
              v-if="deviceData.storeId != null"
              :views="views.device"
              :query="{
                storeId: deviceData.storeId,
              }"
            />
          </el-tab-pane>
          <el-tab-pane label="命令日志" :lazy="true">
            <command-log :query="{macList: macList}" :views="views.device"/>
          </el-tab-pane>
          <el-tab-pane label="绑定/解绑记录" :lazy="true">
            <bind-record :query="{deviceId: deviceData.deviceId}" :views="views.device"/>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>
    <device-edit-dialog :visible.sync="editDialogVisible" :device-id="deviceData.deviceId"/>
  </div>
</template>

<script>


import QrCode from "@/components/QrCode/index.vue";
import {toDescriptionFromSecond} from '@/utils/date'
import BooleanTag from '@/components/BooleanTag/index.vue'
import {isEmpty} from '@/utils'
import LineField from '@/components/LineField/index.vue'
import {DeviceOnlineType, OnlineStatus, views} from "@/utils/constants";
import {ModelTag} from "@/utils/constants";
import DotStatus from "@/components/DotStatus/index.vue";
import {refreshIot} from "@/api/bst/deviceIot";
import {deviceSetTime, getDevice, unbindMch} from "@/api/bst/device";
import {switchDevice} from "@/api/bst/deviceIot";
import UserLink from "@/views/system/user/UserLink.vue";
import StoreLink from "@/views/bst/store/StoreLink.vue";
import Suit from "@/views/bst/suit/index.vue";
import Order from "@/views/bst/order/index.vue";
import CommandLog from "@/views/bst/commandLog/index.vue";
import BindRecord from "@/views/bst/bindRecord/index.vue";
import DeviceEditDialog from "@/views/bst/device/components/DeviceEditDialog.vue";
import BindMchButton from "@/views/bst/device/components/BindMchButton.vue";
import {isSysAdmin} from "@/utils/permission";

export default {
  name: 'DeviceView',
  dicts: [
    'device_set',
    'device_online_status',
    'device_status',
    'device_power_status',
    'device_model_tag',
    'model_type',
  ],
  components: {
    BindMchButton,
    DeviceEditDialog,
    BindRecord,
    CommandLog,
    Order,
    Suit,
    StoreLink,
    UserLink,
    DotStatus,
    LineField,
    BooleanTag,
    QrCode,
    OnlineStatus
  },
  data() {
    return {
      loading: false,
      deviceData: {
        modelTags: [],
      },
      timer: null,
      surplusTime: 0, // 剩余时长
      addElectricityForm: {
        amount: 0,
        timeUnit: '3'
      },
      showAddElectricity: false,
      addRules: {
        amount: [
          {required: true, message: '请输入电量', trigger: 'blur'}
        ]
      },
      // 设备ID
      deviceId: null,
      OnlineStatus,
      ModelTag,
      editDialogVisible: false
    }
  },
  computed: {
    views() {
      return views
    },
    DeviceOnlineType() {
      return DeviceOnlineType
    },
    // 计算数据库电量
    calcDbEle() {
      return (device) => {
        return device.expireEle - device.totalElectriQuantity;
      }
    },
    // MAC 列表
    macList() {
      let list = [];
      if (!isEmpty(this.deviceData.mac)) {
        list.push(this.deviceData.mac)
      }
      if (!isEmpty(this.deviceData.mac2)) {
        list.push(this.deviceData.mac2);
      }
      return list;
    },
    // 二维码文本
    qrCodeText() {
      return (device) => {
        return getWxIndexUrl({s: device.deviceNo});
      }
    },
    // 剩余时长描述
    surplusTimeDesc() {
      return (second) => {
        return toDescriptionFromSecond(second);
      }
    },
    // 是否开启
    isOpen() {
      return this.deviceData != null && this.deviceData.powerStatus === '1';
    },
    // 是否反转
    isReverse() {
      return this.deviceData != null && this.deviceData.set === '1';
    },
    // 是否限制充值
    isLimitRecharge() {
      if (this.deviceData == null || this.deviceData.limitRechargeTime == null) {
        return false;
      }
      return new Date(this.deviceData.limitRechargeTime).getTime() < new Date();
    }
  },
  created() {
    this.deviceId = this.$route.params.deviceId;
    this.refreshIot(this.deviceId, false, DeviceOnlineType.GET);
  },
  beforeDestroy() {
    clearInterval(this.timer);
  },
  methods: {
    isSysAdmin,
    // 反转设备
    handleReverse(reverse) {
      this.$confirm(`是否确认${reverse ? '反转' : '正转'}设备？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let set = reverse ? '1' : '0';
        deviceSetSet(this.deviceData.deviceId, set).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
            this.deviceData.set = set;
          }
        })
      })
    },
    // 修改设备开启时间
    handleSetDuration() {
      this.$prompt('请输入设备开启时间', '修改设备开启时间', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => {
          if (val <= 0) {
            return "设备的开启时间不允许小于等于0";
          }
          return true;
        }
      }).then(({value}) => {
        deviceSetTime(this.deviceData.deviceId, value).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.deviceData.duration = value;
          }
        })
      })
    },

    // 修改电量系数
    handleSetWxs() {
      this.$prompt('请输入电量系数', '修改电量系数', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+(\.\d{0,3})?$/,
        inputErrorMessage: '请输入最多3位小数的数字',
        inputValidator: (val) => {
          if (val <= 0.02) {
            return "输入的电量系数不允许小于0.02";
          }
          return true;
        }
      }).then(({value}) => {
        deviceSetWxs(this.deviceData.deviceId, value).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.deviceData.wxs = value;
          }
        })
      })
    },
    /** 修改按钮操作 */
      handleEditDevice() {
        this.editDialogVisible = true;
      },
    handleInitReading() {
      this.$confirm(`是否初始化电量读数？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deviceInitTotalEle(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.getDevice();
          }
        })
      })
    },
    isEmpty,
    handleUnbind() {
      this.$confirm('是否强制解绑该商户？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        unbindMch(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
          }
        }).finally(() => {
          this.getDevice();
        })
      })
    },
    handleSwitch(open) {
      this.$confirm(`是否确认强制${open ? '开启' : '关闭'}设备？`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        switchDevice(this.deviceData.deviceId, open).then(res => {
          if (res.code === 200) {
            this.$message.success("操作成功");
            this.deviceData.powerStatus = open ? '1' : '0';
          }
        }).catch(() => {
          this.getDevice();
        })
          .finally(() => {
            this.loading = false;
          })
      })
    },
    // 计算剩余时长
    computeSurplusTime() {
      if (this.deviceData.expireTime == null) {
        return 0;
      }
      let expireTime = new Date(this.deviceData.expireTime).getTime();
      let now = new Date().getTime();
      if (expireTime < now) {
        return 0;
      }
      return ((expireTime - now) / 1000).toFixed(2);
    },
    handleReset() {
      this.$confirm('是否确认归零设备时长？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetDevice(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
          }
        }).finally(() => {
          this.getDevice();
        })
      })
    },
    handleResetEle() {
      this.$confirm('是否确认归零设备电量？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetEleDevice(this.deviceData.deviceId).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
          }
        }).finally(() => {
          this.getDevice();
        })
      })
    },
    handleAddTime() {
      this.resetAddElectricityForm();
      this.showAddElectricity = true;
    },
    handleAddEle() {
      this.$prompt('请输入增加的电量（度）', '增加电量', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => {
          if (val < 0) {
            return "输入的电量不允许小于0";
          }
          return true;
        }
      }).then(({value}) => {
        addEle(this.deviceData.deviceId, value).then(res => {
          if (res.code === 200) {
            this.$message.success('操作成功');
          }
        }).finally(() => {
          this.getDevice();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    submitAddElectricity() {
      addTime(this.deviceData.deviceId, this.addElectricityForm.amount, this.addElectricityForm.timeUnit).then(res => {
        if (res.code === 200) {
          this.$message.success('操作成功');
          this.showAddElectricity = false;
        }
      }).finally(() => {
        this.getDevice();
      })
    },
    resetAddElectricityForm() {
      this.addElectricityForm = {
        amount: 0,
        timeUnit: '3'
      }
    },
    // 刷新设备信息
    refreshIot(deviceId, notice = false, onlineType = DeviceOnlineType.GET) {
      this.loading = true;
      refreshIot(deviceId, onlineType).then(res => {
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        }
        if (notice) {
          this.$message.success('操作成功');
        }
      }).finally(() => {
        this.getDevice();
      })
    },
    getDevice() {
      this.loading = true;
      getDevice(this.deviceId).then(response => {
        this.deviceData = response.data;
        this.surplusTime = this.computeSurplusTime();
        if (this.timer == null) {
          this.timer = setInterval(() => {
            this.surplusTime = this.computeSurplusTime();
          }, 1000)
        }
      }).finally(() => {
        this.loading = false;
      })
    },
  }
}
</script>

<style lang="scss" scoped>
.device-info-card {
  margin-bottom: 12px;

  .device-info-container {

    .device-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .device-title {
        display: flex;
        align-items: center;

        i {
          font-size: 20px;
          color: #409EFF;
          margin-right: 8px;
        }

        .device-name {
          font-size: 18px;
          font-weight: bold;
          margin-right: 6px;
          display: flex;
          align-items: center;
        }

        .last-online-time {
          color: #909399;
          font-size: 12px;
          font-weight: normal;
          margin-left: 8px;

          i {
            font-size: 13px;
            margin-right: 0;
            color: #909399;
          }
        }
      }

      .device-actions {
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
      }
    }

    .device-info {
      display: flex;
      flex-wrap: wrap;
      padding: 12px;
      background: #f5f7fa;
      border-radius: 4px;

      &.model-tags {
        margin-top: 8px;
      }

      .info-item {
        display: flex;
        align-items: center;
        font-size: 12px;
        color: #606266;
        margin-right: 16px;


        i {
          font-size: 14px;
          color: #909399;
          margin-right: 4px;
        }

        .label {
          color: #909399;
          margin-right: 4px;
        }

        :deep(.el-tag) {
          margin-right: 4px;
        }
      }
    }
  }
}

.box-card {
  margin-bottom: 12px;

  :deep(.el-card__body) {
    padding: 12px;
  }

  .card-title {
    font-size: 16px;
    font-weight: 500;
    display: flex;
    align-items: center;

    i {
      margin-right: 8px;
      color: #409EFF;
    }
  }

  .last-update-time {
    color: #909399;
    font-size: 13px;

    i {
      margin-right: 4px;
    }
  }

  .realtime-info {
    .info-section {
      background: #f8f9fa;
      border-radius: 6px;
      padding: 12px;
      margin-bottom: 12px;
      height: calc(100% - 12px);

      .section-title {
        width: 100%;
        font-size: 13px;
        font-weight: 500;
        color: #606266;
        margin-bottom: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        i {
          margin-right: 4px;
          color: #409EFF;
        }

        .reset-time {
          font-size: 12px;
          color: #909399;
          text-align: right;
        }
      }

      .data-grid {
        display: flex;
        flex-wrap: nowrap;

        .data-item {
          flex: 1;
          border-radius: 4px;

          .item-label {
            color: #909399;
            font-size: 12px;
            display: flex;
            align-items: center;
            white-space: nowrap;

            .reset-btn {
              font-size: 12px;
              padding: 0 2px;
              margin-left: 4px;
            }
          }

          .item-value {
            margin-top: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #303133;
          }
        }
      }
    }
  }
}

.qr-code-box {
  text-align: center;
}


</style>
