// pages/profile/profile.js
const app = getApp();
const apiService = require('../../utils/api.js');

Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    
    // 用户信息
    userInfo: {
      id: '',
      username: '',
      name: '',
      avatar: '/images/avatar.png',
      phone: '',
      email: '',
      department: '',
      position: '',
      lastLoginTime: ''
    },
    
    // 统计数据
    statistics: {
      totalFarmers: 0,
      totalChecks: 0,
      totalAlerts: 0,
      totalTasks: 0
    },
    
    // 快捷操作
    quickActions: [
      {
        id: 'farmer_manage',
        title: '养殖户管理',
        icon: 'farmer',
        color: '#1890ff',
        path: '/pages/farmer/farmer'
      },
      {
        id: 'data_stats',
        title: '数据统计',
        icon: 'chart',
        color: '#52c41a',
        path: '/pages/statistics/statistics'
      },
      {
        id: 'notification',
        title: '消息通知',
        icon: 'notification',
        color: '#fa8c16',
        path: '/pages/notification/notification'
      },
      {
        id: 'settings',
        title: '系统设置',
        icon: 'settings',
        color: '#722ed1',
        path: '/pages/settings/settings'
      }
    ],
    
    // 功能菜单
    menuList: [
      {
        id: 'profile_edit',
        title: '个人资料',
        icon: 'user',
        arrow: true,
        path: '/pages/profile/edit/edit'
      },
      {
        id: 'password_change',
        title: '修改密码',
        icon: 'lock',
        arrow: true,
        path: '/pages/profile/password/password'
      },
      {
        id: 'notification_settings',
        title: '通知设置',
        icon: 'bell',
        arrow: true,
        path: '/pages/profile/notification/notification'
      },
      {
        id: 'about',
        title: '关于我们',
        icon: 'info',
        arrow: true,
        path: '/pages/profile/about/about'
      },
      {
        id: 'help',
        title: '帮助中心',
        icon: 'help',
        arrow: true,
        path: '/pages/profile/help/help'
      }
    ]
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
    
    // 检查登录状态
    this.checkLoginStatus();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadUserData();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
  },

  // 编辑个人资料
  editProfile() {
    wx.showToast({
      title: '编辑功能开发中',
      icon: 'none'
    });
  },
  async loadUserData() {
    try {
      // 从本地存储获取用户信息
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...userInfo
          }
        });
      }
      
      // 模拟从服务器获取最新数据
      await this.fetchUserProfile();
      
    } catch (error) {
      console.error('加载用户数据失败:', error);
    }
  },

  // 获取用户资料
  fetchUserProfile() {
    return new Promise((resolve) => {
      setTimeout(() => {
        // 模拟API返回的用户数据
        const profileData = {
          name: '张管理员',
          department: '宁夏畜牧管理局',
          position: '高级管理员',
          lastLoginTime: this.formatTime(new Date())
        };
        
        this.setData({
          userInfo: {
            ...this.data.userInfo,
            ...profileData
          }
        });
        
        resolve();
      }, 500);
    });
  },

  // 刷新统计数据
  async refreshStats() {
    try {
      const stats = await this.fetchStatsData();
      this.setData({ statsData: stats });
    } catch (error) {
      console.error('刷新统计数据失败:', error);
    }
  },

  // 获取统计数据
  fetchStatsData() {
    return new Promise((resolve) => {
      setTimeout(() => {
        const stats = {
          todayCheck: Math.floor(Math.random() * 20) + 5,
          totalFarmers: Math.floor(Math.random() * 50) + 150,
          totalAlerts: Math.floor(Math.random() * 10),
          completedTasks: Math.floor(Math.random() * 20) + 20
        };
        resolve(stats);
      }, 300);
    });
  },

  // 头像点击
  onAvatarTap() {
    wx.showActionSheet({
      itemList: ['查看头像', '更换头像'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.viewAvatar();
        } else if (res.tapIndex === 1) {
          this.changeAvatar();
        }
      }
    });
  },

  // 查看头像
  viewAvatar() {
    if (this.data.userInfo.avatar) {
      wx.previewImage({
        urls: [this.data.userInfo.avatar]
      });
    } else {
      wx.showToast({
        title: '暂无头像',
        icon: 'none'
      });
    }
  },

  // 更换头像
  changeAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        // 模拟上传头像
        wx.showLoading({ title: '上传中...' });
        
        setTimeout(() => {
          this.setData({
            'userInfo.avatar': tempFilePath
          });
          
          wx.hideLoading();
          wx.showToast({
            title: '头像更新成功',
            icon: 'success'
          });
        }, 2000);
      }
    });
  },

  // 菜单项点击
  onMenuItemTap(e) {
    const { id } = e.currentTarget.dataset;
    
    switch (id) {
      case 'personal_info':
        this.editPersonalInfo();
        break;
      case 'change_password':
        this.changePassword();
        break;
      case 'notification_settings':
        this.openNotificationSettings();
        break;
      case 'work_report':
        this.viewWorkReport();
        break;
      case 'help_feedback':
        this.openHelpFeedback();
        break;
      case 'about':
        this.showAbout();
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
    }
  },

  // 编辑个人信息
  editPersonalInfo() {
    wx.showModal({
      title: '个人信息',
      content: '此功能将跳转到个人信息编辑页面',
      showCancel: false
    });
  },

  // 修改密码
  changePassword() {
    wx.showModal({
      title: '修改密码',
      content: '请输入原密码和新密码',
      editable: true,
      placeholderText: '请输入原密码',
      success: (res) => {
        if (res.confirm && res.content) {
          wx.showModal({
            title: '新密码',
            content: '请输入新密码',
            editable: true,
            placeholderText: '请输入新密码',
            success: (newRes) => {
              if (newRes.confirm && newRes.content) {
                wx.showLoading({ title: '修改中...' });
                
                setTimeout(() => {
                  wx.hideLoading();
                  wx.showToast({
                    title: '密码修改成功',
                    icon: 'success'
                  });
                }, 2000);
              }
            }
          });
        }
      }
    });
  },

  // 消息设置
  openNotificationSettings() {
    wx.showActionSheet({
      itemList: ['推送通知', '声音提醒', '震动提醒', '免打扰时间'],
      success: (res) => {
        const settings = ['推送通知', '声音提醒', '震动提醒', '免打扰时间'];
        wx.showToast({
          title: `${settings[res.tapIndex]}设置`,
          icon: 'none'
        });
      }
    });
  },

  // 工作报告
  viewWorkReport() {
    wx.showModal({
      title: '工作报告',
      content: `本月检查: ${this.data.statsData.todayCheck * 30}次\n管理养殖户: ${this.data.statsData.totalFarmers}户\n处理告警: ${this.data.statsData.totalAlerts * 10}次\n完成任务: ${this.data.statsData.completedTasks * 5}个`,
      showCancel: false
    });
  },

  // 帮助反馈
  openHelpFeedback() {
    wx.showActionSheet({
      itemList: ['使用帮助', '问题反馈', '联系客服'],
      success: (res) => {
        const actions = ['使用帮助', '问题反馈', '联系客服'];
        if (res.tapIndex === 2) {
          wx.makePhoneCall({
            phoneNumber: '400-123-4567'
          });
        } else {
          wx.showToast({
            title: `${actions[res.tapIndex]}功能开发中`,
            icon: 'none'
          });
        }
      }
    });
  },

  // 关于应用
  showAbout() {
    wx.showModal({
      title: '关于应用',
      content: '宁夏智慧牧场政府端\n版本: v1.0.0\n更新时间: 2024-01-15\n\n智慧畜牧管理系统，助力现代化养殖业发展',
      showCancel: false
    });
  },

  // 快捷操作点击
  onQuickActionTap(e) {
    const { id } = e.currentTarget.dataset;
    
    switch (id) {
      case 'scan_qr':
        this.scanQRCode();
        break;
      case 'emergency_report':
        this.emergencyReport();
        break;
      case 'data_export':
        this.exportData();
        break;
      case 'system_settings':
        this.systemSettings();
        break;
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        });
    }
  },

  // 扫码检查
  scanQRCode() {
    wx.scanCode({
      success: (res) => {
        wx.showModal({
          title: '扫码结果',
          content: `扫码内容: ${res.result}`,
          showCancel: false
        });
      },
      fail: () => {
        wx.showToast({
          title: '扫码失败',
          icon: 'none'
        });
      }
    });
  },

  // 紧急上报
  emergencyReport() {
    wx.showActionSheet({
      itemList: ['疫情报告', '设备故障', '安全事故', '其他紧急情况'],
      success: (res) => {
        const types = ['疫情报告', '设备故障', '安全事故', '其他紧急情况'];
        wx.showModal({
          title: '紧急上报',
          content: `上报类型: ${types[res.tapIndex]}\n请描述具体情况`,
          editable: true,
          placeholderText: '请输入详细描述',
          success: (modalRes) => {
            if (modalRes.confirm) {
              wx.showLoading({ title: '上报中...' });
              
              setTimeout(() => {
                wx.hideLoading();
                wx.showToast({
                  title: '上报成功',
                  icon: 'success'
                });
              }, 2000);
            }
          }
        });
      }
    });
  },

  // 数据导出
  exportData() {
    wx.showActionSheet({
      itemList: ['养殖户数据', '检查记录', '告警记录', '统计报表'],
      success: (res) => {
        const types = ['养殖户数据', '检查记录', '告警记录', '统计报表'];
        
        wx.showLoading({ title: '导出中...' });
        
        setTimeout(() => {
          wx.hideLoading();
          wx.showToast({
            title: `${types[res.tapIndex]}导出成功`,
            icon: 'success'
          });
        }, 3000);
      }
    });
  },

  // 系统设置
  systemSettings() {
    wx.showActionSheet({
      itemList: ['清除缓存', '检查更新', '重置设置'],
      success: (res) => {
        if (res.tapIndex === 0) {
          this.clearCache();
        } else if (res.tapIndex === 1) {
          this.checkUpdate();
        } else if (res.tapIndex === 2) {
          this.resetSettings();
        }
      }
    });
  },

  // 清除缓存
  clearCache() {
    wx.showModal({
      title: '清除缓存',
      content: '确定要清除应用缓存吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '清除中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '缓存清除成功',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },

  // 检查更新
  checkUpdate() {
    wx.showLoading({ title: '检查中...' });
    
    setTimeout(() => {
      wx.hideLoading();
      wx.showModal({
        title: '检查更新',
        content: '当前已是最新版本',
        showCancel: false
      });
    }, 2000);
  },

  // 重置设置
  resetSettings() {
    wx.showModal({
      title: '重置设置',
      content: '确定要重置所有设置吗？此操作不可恢复',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '重置中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '设置重置成功',
              icon: 'success'
            });
          }, 2000);
        }
      }
    });
  },

  // 退出登录
  onLogout() {
    wx.showModal({
      title: '退出登录',
      content: '确定要退出当前账号吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除本地存储
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
          
          // 跳转到登录页
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/login/login'
            });
          }, 1500);
        }
      }
    });
  },

  // 格式化时间
  formatTime(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hour = date.getHours().toString().padStart(2, '0');
    const minute = date.getMinutes().toString().padStart(2, '0');
    const second = date.getSeconds().toString().padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }
});
