// pages/kaohe_dafen/kaohe_dafen.js
const app = getApp();
import request from '../../utils/request.js';

Page({
  data: {
    recordList: [],
    page: 1,
    pageSize: 10,
    hasMore: false,
    isLoading: false,
    ossImageUrl: app.globalData.ossImageUrl || '',

    // 操作弹窗
    showAgreeModal: false,
    showRejectModal: false,
    showTransferModal: false,
    currentItem: null,
    rejectReason: '',

    // 倒计时
    countdown: 2,
    counting: false,
    countdownTimer: null,
  },

  onLoad() {
    this.loadRecords(true);
  },

  // 加载考核记录
  async loadRecords(isRefresh = false) {
    if (this.data.isLoading) return;
    const page = isRefresh ? 1 : this.data.page;
    this.setData({ isLoading: true });
    try {
      const res = await request({
        url: '/dengji/hqkhxq',
        method: 'POST',
        data: { page, page_size: this.data.pageSize }
      });
      if (res && res.data.code === 0) {
        const list = res.data.data.list || [];
        const hasMore = res.data.data.has_more;
        const oss = this.data.ossImageUrl;
        const processed = list.map(item => ({
          ...item,
          shenqingren_avatar: item.shenqingren_avatar && !item.shenqingren_avatar.startsWith('http')
            ? oss + item.shenqingren_avatar
            : item.shenqingren_avatar || '/images/default-avatar.png'
        }));
        const newList = isRefresh ? processed : [...this.data.recordList, ...processed];
        this.setData({ recordList: newList, page: page + 1, hasMore, isLoading: false });
      } else {
        wx.showToast({ title: '加载失败', icon: 'none' });
        this.setData({ isLoading: false });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
      this.setData({ isLoading: false });
    }
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadRecords(false);
    }
  },

  // 联系打手（私聊）—— 照搬金牌页面逻辑
  contactDashou(e) {
    const item = e.currentTarget.dataset.item;
    if (!item) return;
    if (!item.shenqingren_id) {
      wx.showToast({ title: '无法获取打手ID', icon: 'none' });
      return;
    }

    const uid = wx.getStorageSync('uid');
    if (!uid) {
      wx.showToast({ title: '用户信息缺失', icon: 'none' });
      return;
    }

    // 1. 设置当前角色为考核官
    if (app.globalData.currentRole !== 'kaoheguan') {
      app.globalData.currentRole = 'kaoheguan';
      wx.setStorageSync('currentRole', 'kaoheguan');
    }

    // 2. 确保 IM 连接存活
    if (app.connectForCurrentRole) {
      app.connectForCurrentRole();
    } else if (app.ensureConnection) {
      app.ensureConnection();
    }

    // 3. 构造私聊参数
    const param = {
      toUserId: 'Ds' + item.shenqingren_id,
      toName: '打手' + item.shenqingren_id,
      toAvatar: item.shenqingren_avatar || ''
    };

    // 4. 直接跳转聊天页面
    wx.navigateTo({
      url: '/pages/liaotian/liaotian?data=' + encodeURIComponent(JSON.stringify(param)),
      fail: (err) => {
        console.error('跳转私聊失败', err);
        wx.showToast({ title: '打开聊天失败', icon: 'none' });
      }
    });
  },

  // 修改游戏昵称
  async modifyNick(e) {
    const { id } = e.currentTarget.dataset;
    const item = this.data.recordList.find(r => r.jilu_id === id);
    if (!item) return;
    const newNick = item.shenheguan_youxi_id || '';
    try {
      const res = await request({
        url: '/dengji/khgxgkh',
        method: 'POST',
        data: { jilu_id: id, caozuo: 'modify_nick', youxi_id: newNick }
      });
      if (res && res.data.code === 0) {
        wx.showToast({ title: '修改成功', icon: 'success' });
      } else {
        wx.showToast({ title: res.data?.msg || '修改失败', icon: 'none' });
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  onNickInput(e) {
    const id = e.currentTarget.dataset.id;
    const value = e.detail.value;
    const list = this.data.recordList.map(item => {
      if (item.jilu_id === id) {
        return { ...item, shenheguan_youxi_id: value };
      }
      return item;
    });
    this.setData({ recordList: list });
  },

  // 🆕 实时更新拒绝原因
  onRejectInput(e) {
    this.setData({ rejectReason: e.detail.value });
  },

  openAgreeModal(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({ showAgreeModal: true, currentItem: item });
    this.startCountdown();
  },
  openRejectModal(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({ showRejectModal: true, currentItem: item, rejectReason: '' });
    this.startCountdown();
  },
  openTransferModal(e) {
    const item = e.currentTarget.dataset.item;
    this.setData({ showTransferModal: true, currentItem: item });
    this.startCountdown();
  },

  closeAllModals() {
    this.stopCountdown();
    this.setData({
      showAgreeModal: false,
      showRejectModal: false,
      showTransferModal: false,
      currentItem: null,
      rejectReason: ''
    });
  },

  startCountdown() {
    this.stopCountdown();
    this.setData({ counting: true, countdown: 2 });
    this.data.countdownTimer = setInterval(() => {
      if (this.data.countdown > 1) {
        this.setData({ countdown: this.data.countdown - 1 });
      } else {
        this.stopCountdown();
        this.setData({ counting: false, countdown: 0 });
      }
    }, 1000);
  },
  stopCountdown() {
    if (this.data.countdownTimer) {
      clearInterval(this.data.countdownTimer);
      this.data.countdownTimer = null;
    }
  },

  // 执行操作（从事件对象中获取操作类型）
  async executeAction(e) {
    const actionType = e.currentTarget.dataset.action;
    if (!actionType) {
      wx.showToast({ title: '操作类型异常', icon: 'none' });
      return;
    }

    const item = this.data.currentItem;
    if (!item) return;

    const params = { jilu_id: item.jilu_id, caozuo: actionType };

    if (actionType === 'reject') {
      if (!this.data.rejectReason.trim()) {
        wx.showToast({ title: '请填写拒绝原因', icon: 'none' });
        return;
      }
      params.yuanyin = this.data.rejectReason;
    }

    try {
      const res = await request({ url: '/dengji/khgxgkh', method: 'POST', data: params });
      if (res && res.data.code === 0) {
        wx.showToast({ title: '操作成功', icon: 'success' });
        this.closeAllModals();
        const newList = this.data.recordList.filter(r => r.jilu_id !== item.jilu_id);
        this.setData({ recordList: newList });
      } else {
        wx.showToast({ title: res.data?.msg || '操作失败', icon: 'none' });
        this.closeAllModals();
      }
    } catch (e) {
      wx.showToast({ title: '网络错误', icon: 'none' });
      this.closeAllModals();
    }
  },
});