const { Employee, User } = require('../models');
const { validationResult } = require('express-validator');
const bcrypt = require('bcryptjs');

/**
 * 获取员工列表
 */
const getEmployees = async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      searchField = 'name',
      searchValue = '',
      status = '',
      isLoanSpecialist = ''
    } = req.query;

    // 构建查询条件
    const where = {};
    
    if (searchValue) {
      if (searchField === 'name') {
        where.name = { [require('sequelize').Op.like]: `%${searchValue}%` };
      } else if (searchField === 'phone') {
        where.phone = { [require('sequelize').Op.like]: `%${searchValue}%` };
      } else if (searchField === 'employeeNumber') {
        where.employeeNumber = { [require('sequelize').Op.like]: `%${searchValue}%` };
      }
    }

    if (status) {
      where.status = status;
    }

    if (isLoanSpecialist !== '') {
      where.isLoanSpecialist = isLoanSpecialist === 'true';
    }

    // 分页参数
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);

    // 查询数据
    const { count, rows } = await Employee.findAndCountAll({
      where,
      limit,
      offset,
      order: [['created_at', 'DESC']],
      attributes: {
        exclude: ['password'] // 不返回密码
      }
    });

    // 格式化数据
    const employees = rows.map(employee => ({
      id: employee.id,
      employeeNumber: employee.employeeNumber,
      name: employee.name,
      phone: employee.phone,
      email: employee.email,
      isLoanSpecialist: employee.isLoanSpecialist,
      department: employee.department,
      position: employee.position,
      status: employee.status,
      lastLogin: employee.lastLogin,
      createdAt: employee.createdAt,
      updatedAt: employee.updatedAt
    }));

    res.json({
      success: true,
      message: '获取员工列表成功',
      data: {
        employees,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(pageSize),
          total: count,
          pages: Math.ceil(count / parseInt(pageSize))
        }
      }
    });
  } catch (error) {
    console.error('获取员工列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取员工列表失败'
    });
  }
};

/**
 * 获取员工详情
 */
const getEmployeeById = async (req, res) => {
  try {
    const { id } = req.params;

    const employee = await Employee.findByPk(id, {
      attributes: {
        exclude: ['password'] // 不返回密码
      }
    });

    if (!employee) {
      return res.status(404).json({
        success: false,
        message: '员工不存在'
      });
    }

    res.json({
      success: true,
      message: '获取员工详情成功',
      data: employee
    });
  } catch (error) {
    console.error('获取员工详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取员工详情失败'
    });
  }
};

/**
 * 创建员工
 */
const createEmployee = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数错误',
        errors: errors.array()
      });
    }

    const {
      employeeNumber,
      name,
      phone,
      email,
      password,
      isLoanSpecialist,
      department,
      position
    } = req.body;

    // 检查员工编号是否已存在
    const existingEmployee = await Employee.findOne({
      where: { employeeNumber }
    });

    if (existingEmployee) {
      return res.status(400).json({
        success: false,
        message: '员工编号已存在'
      });
    }

    // 检查手机号是否已存在
    const existingPhone = await Employee.findOne({
      where: { phone }
    });

    if (existingPhone) {
      return res.status(400).json({
        success: false,
        message: '手机号已存在'
      });
    }

    // 创建员工
    const employee = await Employee.create({
      employeeNumber,
      name,
      phone,
      email,
      password: password || '123456', // 默认密码
      isLoanSpecialist: isLoanSpecialist || false,
      department,
      position,
      status: 'active'
    });

    res.status(201).json({
      success: true,
      message: '创建员工成功',
      data: {
        id: employee.id,
        employeeNumber: employee.employeeNumber,
        name: employee.name,
        phone: employee.phone,
        email: employee.email,
        isLoanSpecialist: employee.isLoanSpecialist,
        department: employee.department,
        position: employee.position,
        status: employee.status,
        createdAt: employee.createdAt
      }
    });
  } catch (error) {
    console.error('创建员工失败:', error);
    res.status(500).json({
      success: false,
      message: '创建员工失败'
    });
  }
};

/**
 * 更新员工信息
 */
const updateEmployee = async (req, res) => {
  try {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        success: false,
        message: '请求参数错误',
        errors: errors.array()
      });
    }

    const { id } = req.params;
    const {
      name,
      phone,
      email,
      isLoanSpecialist,
      department,
      position,
      status
    } = req.body;

    const employee = await Employee.findByPk(id);
    if (!employee) {
      return res.status(404).json({
        success: false,
        message: '员工不存在'
      });
    }

    // 检查手机号是否被其他员工使用
    if (phone && phone !== employee.phone) {
      const existingPhone = await Employee.findOne({
        where: { 
          phone,
          id: { [require('sequelize').Op.ne]: id }
        }
      });

      if (existingPhone) {
        return res.status(400).json({
          success: false,
          message: '手机号已被其他员工使用'
        });
      }
    }

    // 更新员工信息
    await employee.update({
      name,
      phone,
      email,
      isLoanSpecialist,
      department,
      position,
      status
    });

    res.json({
      success: true,
      message: '更新员工信息成功',
      data: {
        id: employee.id,
        employeeNumber: employee.employeeNumber,
        name: employee.name,
        phone: employee.phone,
        email: employee.email,
        isLoanSpecialist: employee.isLoanSpecialist,
        department: employee.department,
        position: employee.position,
        status: employee.status,
        updatedAt: employee.updatedAt
      }
    });
  } catch (error) {
    console.error('更新员工信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新员工信息失败'
    });
  }
};

/**
 * 重设密码
 */
const resetPassword = async (req, res) => {
  try {
    const { id } = req.params;
    const { newPassword } = req.body;

    const employee = await Employee.findByPk(id);
    if (!employee) {
      return res.status(404).json({
        success: false,
        message: '员工不存在'
      });
    }

    // 更新密码
    await employee.update({
      password: newPassword || '123456' // 默认密码
    });

    res.json({
      success: true,
      message: '重设密码成功'
    });
  } catch (error) {
    console.error('重设密码失败:', error);
    res.status(500).json({
      success: false,
      message: '重设密码失败'
    });
  }
};

/**
 * 删除员工
 */
const deleteEmployee = async (req, res) => {
  try {
    const { id } = req.params;

    const employee = await Employee.findByPk(id);
    if (!employee) {
      return res.status(404).json({
        success: false,
        message: '员工不存在'
      });
    }

    // 软删除
    await employee.destroy();

    res.json({
      success: true,
      message: '删除员工成功'
    });
  } catch (error) {
    console.error('删除员工失败:', error);
    res.status(500).json({
      success: false,
      message: '删除员工失败'
    });
  }
};

/**
 * 批量更新员工状态
 */
const batchUpdateStatus = async (req, res) => {
  try {
    const { ids, status } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要更新的员工'
      });
    }

    if (!status) {
      return res.status(400).json({
        success: false,
        message: '请选择要更新的状态'
      });
    }

    await Employee.update(
      { 
        status
      },
      {
        where: {
          id: { [require('sequelize').Op.in]: ids }
        }
      }
    );

    res.json({
      success: true,
      message: '批量更新状态成功'
    });
  } catch (error) {
    console.error('批量更新状态失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新状态失败'
    });
  }
};

/**
 * 获取员工统计信息
 */
const getEmployeeStats = async (req, res) => {
  try {
    const totalEmployees = await Employee.count();
    const activeEmployees = await Employee.count({ where: { status: 'active' } });
    const inactiveEmployees = await Employee.count({ where: { status: 'inactive' } });
    const lockedEmployees = await Employee.count({ where: { status: 'locked' } });
    const loanSpecialists = await Employee.count({ where: { isLoanSpecialist: true } });

    res.json({
      success: true,
      message: '获取员工统计成功',
      data: {
        totalEmployees,
        activeEmployees,
        inactiveEmployees,
        lockedEmployees,
        loanSpecialists
      }
    });
  } catch (error) {
    console.error('获取员工统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取员工统计失败'
    });
  }
};

module.exports = {
  getEmployees,
  getEmployeeById,
  createEmployee,
  updateEmployee,
  resetPassword,
  deleteEmployee,
  batchUpdateStatus,
  getEmployeeStats
};