<template>
  <div class="evaluation-panel">
    <div class="status-bar">
      <div class="status-item">
        <span :class="['status-badge', deviceStatusClass]"></span>
        <span>设备状态: {{ deviceStatusText }}</span>
      </div>
      <div class="status-item">
        <span :class="['status-badge', loginStatusClass]"></span>
        <span>登录状态: {{ loginStatusText }}</span>
      </div>
      <div class="status-item">
        <i class="fas fa-user"></i>
        <span>用户: {{ signInParams.name }} (工号: {{ signInParams.num }})</span>
      </div>
      <div class="status-item">
        <span>评价状态: {{ evaluationStatus }}</span>
      </div>
    </div>
    <div class="auto-process" v-if="autoProcessMessage">
      <h4>评价器状态</h4>
      <p>{{ autoProcessMessage }}</p>
    </div>
    <div class="section">
      <button v-on:click="handleEvaluate" v-bind:disabled="loading">发起评价</button>
      <button v-on:click="checkStatus" v-bind:disabled="loading">检查在线状态</button>
      <button v-on:click="getLoginInfo" v-bind:disabled="loading">检查登录状态</button>
    </div>
  </div>
</template>

<script>
import co from "co";

module.exports = {
  title: 'EvaluationPanel',
  data () {
    return {
      signInParams: {
        num: this.$login.f.id,
        name: this.$login.f.name,
        pos: this.$login.f.f_show_rolestr,
        org: this.$login.f.f_show_department_name,
        equ: this.$login.f.f_show_department_name,
        star: '5',
        inf: `工号：${this.$login.f.id}`,
        photo: '127.0.0.1:8068/photo.jpg'
      },
      loading: false,
      response: null,
      error: null,
      userLogin: false,
      loginIng: false,
      deviceOnline: false,
      deviceCheckTimer: null,
      deviceCheckInterval: 10000,
      loginCheckTimer: null,
      loginCheckInterval: 1000,
      evaluationStatus: '未发起',
      // 新增：组件销毁标志和请求跟踪
      isComponentDestroyed: false,
      pendingRequests: new Set()
    }
  },
  props: {
    row: {
      type: Object,
      default: undefined
    }
  },
  beforeDestroy() {
    this.cleanup();
  },
  destroyed() {
    this.cleanup();
  },
  async ready() {
    console.log('row', this.row)
    await this.initSystem()
    this.startDeviceStatusMonitoring()
  },
  methods: {
    // 新增：统一的清理方法
    cleanup() {
      console.log('开始清理组件资源');
      this.isComponentDestroyed = true;

      // 清理所有定时器
      this.stopDeviceStatusMonitoring();
      this.stopLoginStatusMonitoring();

      // 取消所有进行中的请求
      this.pendingRequests.clear();

      // 重置状态
      this.loading = false;
    },

    // 新增：安全执行方法，检查组件状态
    safeExecute(callback) {
      if (this.isComponentDestroyed) {
        console.log('组件已销毁，停止执行');
        return false;
      }
      return true;
    },

    async initSystem () {
      if (!this.safeExecute()) return;

      console.log('检查设备状态')
      await this.checkStatus()
      if (!this.safeExecute()) return;

      console.log('设备在线，检查登录状态')
      if (this.deviceOnline) {
        await this.getLoginInfo()
      }
      if (!this.safeExecute()) return;

      if (this.deviceOnline && !this.userLogin) {
        console.log('设备在线但未登录，自动登录')
        await this.handleSignIn()
      }
    },

    // 提交评价
    async submitEvaluation(value) {
      if (!this.safeExecute()) return;

      this.evaluationStatus = '未发起'
      console.log('用户评价值：', value)
      let req = await this.$resetpost('api/af-revenue/logic/saveEvaluationBussiness', {
        f_orgid: this.$login.f.orgid,
        f_userinfo_id: this.row.f_userinfo_id,
        f_operatorid: this.$login.f.id,
        f_satisfaction: 5 - value,
        f_user_type: this.row.f_user_type
      }, {resolveMsg: '提交评价成功', rejectMsg: '提交评价失败!'})
      this.$dispatch('success', '评价')
    },

    handleSignIn () {
      if (!this.safeExecute()) return;

      let self = this;
      self.loading = true;
      self.error = null;
      self.response = null;

      const requestId = 'signIn_' + Date.now();
      this.pendingRequests.add(requestId);

      return co(
        this.$CEVEvaluator.signIn(this.signInParams)
          .then(function(result) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.response = JSON.stringify(result.data, null, 2);
            console.log('登录result.data', result.data)
            if (result.data.code === '0' && result.data.text) {
              self.showCeAlert(result.data.text, 'success');
              self.loginIng = true
              self.startLoginStatusMonitoring()
            }
          })
          .catch(function(err) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.error = err.message || '签到失败';
            self.showCeAlert('签到失败: ' + (err.message || '未知错误'), 'error');
          })
          .finally(function() {
            self.pendingRequests.delete(requestId);
            if (self.safeExecute()) {
              self.loading = false;
            }
          })
      )
    },

    handleEvaluate () {
      if (!this.safeExecute()) return;

      let self = this;
      self.loading = true;
      self.error = null;
      self.response = null;
      self.evaluationStatus = '等待用户评价'

      const requestId = 'evaluate_' + Date.now();
      this.pendingRequests.add(requestId);

      this.$CEVEvaluator.startEvaluateDirect()
        .then(async function (result) {
          if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

          self.response = JSON.stringify(result.data, null, 2);
          if (result.data.code === '0') {
            console.log('result.data.data', result.data.data)
            self.evaluationStatus = '用户已评价'
            let res = await self.$showMessage(`用户已评价，请提交`, ['confirm', 'cancel'])
            if (res !== 'confirm') return
            self.submitEvaluation(result.data.data)
          }
        })
        .catch(function(err) {
          if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

          self.error = err.message || '评价启动失败';
          self.showCeAlert('用户评价失败: ' + (err.message || '未知错误'), 'error');
          self.evaluationStatus = '未发起'
        })
        .finally(function() {
          self.pendingRequests.delete(requestId);
          if (self.safeExecute()) {
            self.loading = false;
          }
        });
    },

    // 启动设备状态定时监测
    startDeviceStatusMonitoring() {
      if (!this.safeExecute()) return;

      // 先停止可能存在的旧定时器
      this.stopDeviceStatusMonitoring();

      this.deviceCheckTimer = setInterval(async () => {
        if (!this.safeExecute()) {
          this.stopDeviceStatusMonitoring();
          return;
        }

        await this.checkStatus();
        if (!this.safeExecute()) return;

        if (this.deviceOnline) {
          await this.getLoginInfo();
        }
        if (!this.safeExecute()) return;

        if (this.deviceOnline && !this.userLogin) {
          console.log('设备在线但未登录，自动登录')
          await this.handleSignIn()
        }
      }, this.deviceCheckInterval);
    },

    // 停止设备状态监测
    stopDeviceStatusMonitoring() {
      if (this.deviceCheckTimer) {
        clearInterval(this.deviceCheckTimer);
        this.deviceCheckTimer = null;
      }
    },

    // 启动登录定时监测
    startLoginStatusMonitoring() {
      if (!this.safeExecute()) return;

      this.stopLoginStatusMonitoring();

      this.loginCheckTimer = setInterval(async () => {
        if (!this.safeExecute()) {
          this.stopLoginStatusMonitoring();
          return;
        }

        let self = this;
        try {
          const result = await this.$CEVEvaluator.getProgress();
          if (!self.safeExecute()) return;

          console.log('progress', result.data)
          if (result.data.code === '0') {
            if (result.data.progress >= 100) {
              self.stopLoginStatusMonitoring();
              self.loginIng = false
              await self.getLoginInfo()
            }
          }
        } catch (error) {
          if (!self.safeExecute()) return;
          console.error('评价进度检测失败:', error);
        }
      }, this.loginCheckInterval);
    },

    // 停止评价状态监测
    stopLoginStatusMonitoring() {
      if (this.loginCheckTimer) {
        clearInterval(this.loginCheckTimer);
        this.loginCheckTimer = null;
      }
    },

    checkStatus () {
      if (!this.safeExecute()) return;

      let self = this;
      self.loading = true;
      self.error = null;
      self.response = null;

      const requestId = 'checkStatus_' + Date.now();
      this.pendingRequests.add(requestId);

      return co(
        this.$CEVEvaluator.checkOnline()
          .then(function(result) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.response = JSON.stringify(result.data, null, 2);
            if (result.data.code === '0' && result.data.online === '1') {
              self.deviceOnline = true
            } else {
              self.deviceOnline = false
              self.showCeAlert('状态检查完成', 'success');
            }
          })
          .catch(function(err) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.error = err.message || '状态检查失败';
            self.showCeAlert('状态检查失败', 'error');
          })
          .finally(function() {
            self.pendingRequests.delete(requestId);
            if (self.safeExecute()) {
              self.loading = false;
            }
          })
      )
    },

    getLoginInfo () {
      if (!this.safeExecute()) return;

      let self = this;
      self.loading = true;
      self.error = null;
      self.response = null;

      const requestId = 'getLoginInfo_' + Date.now();
      this.pendingRequests.add(requestId);

      return co(
        this.$CEVEvaluator.getLoginInfo()
          .then(async function (result) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.response = JSON.stringify(result.data, null, 2);
            console.log('result.data', result.data)
            if (result.data.code === '0' && result.data.info.name) {
              if (result.data.info.name === self.signInParams.name) {
                self.userLogin = true
                self.stopLoginStatusMonitoring();
              } else {
                await self.signOut()
              }
            } else {
              self.userLogin = false
              self.showCeAlert('当前用户未登录评价器', 'error');
            }
          })
          .catch(function(err) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.error = err.message || '获取登录信息失败';
            self.showCeAlert('获取登录信息失败', 'error');
          })
          .finally(function() {
            self.pendingRequests.delete(requestId);
            if (self.safeExecute()) {
              self.loading = false;
            }
          })
      )
    },

    signOut () {
      if (!this.safeExecute()) return;

      let self = this;
      self.loading = true;
      self.error = null;
      self.response = null;

      const requestId = 'signOut_' + Date.now();
      this.pendingRequests.add(requestId);

      return co(
        this.$CEVEvaluator.signOut()
          .then(function(result) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.response = JSON.stringify(result.data, null, 2);
          })
          .catch(function(err) {
            if (!self.safeExecute() || !self.pendingRequests.has(requestId)) return;

            self.error = err.message || '签退失败';
            self.showCeAlert('签退失败', 'error');
          })
          .finally(function() {
            self.pendingRequests.delete(requestId);
            if (self.safeExecute()) {
              self.loading = false;
            }
          })
      )
    },

    showCeAlert (message, type) {
      if (!this.safeExecute()) return;

      if (type === 'error') {
        console.error(message);
        this.$showAlert(message, 'danger', 2000);
      } else {
        console.log(message);
        this.$showAlert(message, 'success', 2000);
      }
    }
  },
  computed: {
    deviceStatusClass() {
      if (this.loading) return 'loading';
      return this.deviceOnline ? 'online' : 'offline';
    },
    deviceStatusText() {
      if (this.loading) return '检测中...';
      return this.deviceOnline ? '在线' : '离线';
    },
    loginStatusClass() {
      if (this.loading) return 'loading';
      return this.userLogin ? 'online' : 'offline';
    },
    loginStatusText() {
      if (this.loading) return '验证中...';
      return this.userLogin ? '已登录' : this.loginIng ? '登录中' : '未登录'
    },
    autoProcessMessage () {
      if (!this.deviceOnline) return '系统启动中，正在检查设备状态...'
      return this.deviceOnline && this.userLogin ? '系统已就绪，可以开始评价' : this.loginIng ? '系统初始化中正在登录..' : '系统初始化失败，请检查设备连接'
    }
  },
};
</script>

<style scoped>
.section {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
}

.section h3 {
  margin-top: 0;
  color: #333;
  border-bottom: 1px solid #ddd;
  padding-bottom: 8px;
}

.input-group {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.input-group label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
  margin-right: 10px;
}

.input-group input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 3px;
  max-width: 300px;
}

button {
  margin-right: 10px;
  margin-bottom: 10px;
  padding: 10px 15px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #45a049;
}

.response, .error {
  margin-top: 20px;
  padding: 15px;
  border-radius: 5px;
  font-size: 14px;
}

.response {
  background-color: #f0f9f0;
  border-left: 4px solid #4CAF50;
}

.error {
  background-color: #fef0f0;
  border-left: 4px solid #f56c6c;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

h2 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}
.auto-process {
  background: #fff3cd;
  border-left: 4px solid #ffc107;
  padding: 10px 15px;
  margin: 15px 0;
  border-radius: 4px;
}

.auto-process h4 {
  color: #856404;
  margin-bottom: 5px;
}
.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 5px 0;
}

.status-badge {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.online {
  background: #2ecc71;
}

.offline {
  background: #e74c3c;
}

.loading {
  background: #f39c12;
  animation: pulse 1.5s infinite;
}
.timer-badge {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 12px;
  background: #3498db;
  color: white;
  font-size: 12px;
  margin-left: 8px;
}
</style>
