const { InstallationTask, User } = require('../models')
const { Op } = require('sequelize')

// 获取待安装任务列表
const getInstallationTasks = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      search = '',
      installationStatus = '',
      dateRange = ''
    } = req.query

    const offset = (page - 1) * limit
    const where = {}

    // 搜索条件
    if (search) {
      where[Op.or] = [
        { contractNumber: { [Op.like]: `%${search}%` } },
        { applicationNumber: { [Op.like]: `%${search}%` } },
        { customerName: { [Op.like]: `%${search}%` } }
      ]
    }

    // 状态筛选
    if (installationStatus) {
      where.installationStatus = installationStatus
    }

    // 日期范围筛选
    if (dateRange) {
      const [startDate, endDate] = dateRange.split(',')
      if (startDate && endDate) {
        where.taskGenerationTime = {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        }
      }
    }

    const { count, rows } = await InstallationTask.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ],
      order: [['taskGenerationTime', 'DESC']],
      limit: parseInt(limit),
      offset: parseInt(offset)
    })

    const totalPages = Math.ceil(count / limit)

    res.json({
      success: true,
      message: '获取待安装任务列表成功',
      data: {
        tasks: rows,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total: count,
          totalPages,
          hasNextPage: parseInt(page) < totalPages,
          hasPrevPage: parseInt(page) > 1
        }
      }
    })
  } catch (error) {
    console.error('获取待安装任务列表失败:', error)
    res.status(500).json({
      success: false,
      message: '获取待安装任务列表失败',
      error: error.message
    })
  }
}

// 根据ID获取待安装任务详情
const getInstallationTaskById = async (req, res) => {
  try {
    const { id } = req.params

    const task = await InstallationTask.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    })

    if (!task) {
      return res.status(404).json({
        success: false,
        message: '待安装任务不存在'
      })
    }

    res.json({
      success: true,
      message: '获取待安装任务详情成功',
      data: task
    })
  } catch (error) {
    console.error('获取待安装任务详情失败:', error)
    res.status(500).json({
      success: false,
      message: '获取待安装任务详情失败',
      error: error.message
    })
  }
}

// 创建待安装任务
const createInstallationTask = async (req, res) => {
  try {
    const {
      applicationNumber,
      contractNumber,
      productName,
      customerName,
      idType,
      idNumber,
      assetType,
      equipmentToInstall,
      installationNotes,
      installerName,
      installerPhone,
      installationAddress
    } = req.body

    // 验证必填字段
    const requiredFields = [
      'applicationNumber', 'contractNumber', 'productName', 
      'customerName', 'idType', 'idNumber', 'assetType', 'equipmentToInstall'
    ]
    
    for (const field of requiredFields) {
      if (!req.body[field]) {
        return res.status(400).json({
          success: false,
          message: `${field} 是必填字段`
        })
      }
    }

    // 验证申请单号唯一性
    const existingTask = await InstallationTask.findOne({
      where: { applicationNumber }
    })
    
    if (existingTask) {
      return res.status(400).json({
        success: false,
        message: '申请单号已存在'
      })
    }

    // 验证状态枚举值
    const validStatuses = ['pending', 'in-progress', 'completed', 'failed']
    if (req.body.installationStatus && !validStatuses.includes(req.body.installationStatus)) {
      return res.status(400).json({
        success: false,
        message: '安装状态值无效'
      })
    }

    // 验证证件类型枚举值
    const validIdTypes = ['ID_CARD', 'PASSPORT', 'OTHER']
    if (!validIdTypes.includes(idType)) {
      return res.status(400).json({
        success: false,
        message: '证件类型值无效'
      })
    }

    const task = await InstallationTask.create({
      applicationNumber,
      contractNumber,
      productName,
      customerName,
      idType,
      idNumber,
      assetType,
      equipmentToInstall,
      installationStatus: req.body.installationStatus || 'pending',
      taskGenerationTime: req.body.taskGenerationTime || new Date(),
      completionTime: req.body.completionTime || null,
      installationNotes,
      installerName,
      installerPhone,
      installationAddress,
      createdBy: req.user.id
    })

    // 获取创建的任务详情（包含关联数据）
    const createdTask = await InstallationTask.findByPk(task.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    })

    res.status(201).json({
      success: true,
      message: '创建待安装任务成功',
      data: createdTask
    })
  } catch (error) {
    console.error('创建待安装任务失败:', error)
    res.status(500).json({
      success: false,
      message: '创建待安装任务失败',
      error: error.message
    })
  }
}

// 更新待安装任务
const updateInstallationTask = async (req, res) => {
  try {
    const { id } = req.params
    const updateData = req.body

    const task = await InstallationTask.findByPk(id)
    if (!task) {
      return res.status(404).json({
        success: false,
        message: '待安装任务不存在'
      })
    }

    // 验证状态枚举值
    if (updateData.installationStatus) {
      const validStatuses = ['pending', 'in-progress', 'completed', 'failed']
      if (!validStatuses.includes(updateData.installationStatus)) {
        return res.status(400).json({
          success: false,
          message: '安装状态值无效'
        })
      }
    }

    // 验证证件类型枚举值
    if (updateData.idType) {
      const validIdTypes = ['ID_CARD', 'PASSPORT', 'OTHER']
      if (!validIdTypes.includes(updateData.idType)) {
        return res.status(400).json({
          success: false,
          message: '证件类型值无效'
        })
      }
    }

    // 如果申请单号有变化，检查唯一性
    if (updateData.applicationNumber && updateData.applicationNumber !== task.applicationNumber) {
      const existingTask = await InstallationTask.findOne({
        where: { 
          applicationNumber: updateData.applicationNumber,
          id: { [Op.ne]: id }
        }
      })
      
      if (existingTask) {
        return res.status(400).json({
          success: false,
          message: '申请单号已存在'
        })
      }
    }

    await task.update({
      ...updateData,
      updatedBy: req.user.id
    })

    // 获取更新后的任务详情
    const updatedTask = await InstallationTask.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    })

    res.json({
      success: true,
      message: '更新待安装任务成功',
      data: updatedTask
    })
  } catch (error) {
    console.error('更新待安装任务失败:', error)
    res.status(500).json({
      success: false,
      message: '更新待安装任务失败',
      error: error.message
    })
  }
}

// 删除待安装任务
const deleteInstallationTask = async (req, res) => {
  try {
    const { id } = req.params

    const task = await InstallationTask.findByPk(id)
    if (!task) {
      return res.status(404).json({
        success: false,
        message: '待安装任务不存在'
      })
    }

    await task.destroy()

    res.json({
      success: true,
      message: '删除待安装任务成功'
    })
  } catch (error) {
    console.error('删除待安装任务失败:', error)
    res.status(500).json({
      success: false,
      message: '删除待安装任务失败',
      error: error.message
    })
  }
}

// 获取待安装任务统计信息
const getInstallationTaskStats = async (req, res) => {
  try {
    const stats = await InstallationTask.findAll({
      attributes: [
        'installationStatus',
        [InstallationTask.sequelize.fn('COUNT', InstallationTask.sequelize.col('id')), 'count']
      ],
      group: ['installationStatus'],
      raw: true
    })

    const totalCount = await InstallationTask.count()

    res.json({
      success: true,
      message: '获取待安装任务统计成功',
      data: {
        stats,
        totalCount
      }
    })
  } catch (error) {
    console.error('获取待安装任务统计失败:', error)
    res.status(500).json({
      success: false,
      message: '获取待安装任务统计失败',
      error: error.message
    })
  }
}

// 批量更新安装状态
const batchUpdateStatus = async (req, res) => {
  try {
    const { ids, installationStatus } = req.body

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

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

    const validStatuses = ['pending', 'in-progress', 'completed', 'failed']
    if (!validStatuses.includes(installationStatus)) {
      return res.status(400).json({
        success: false,
        message: '安装状态值无效'
      })
    }

    const updateData = {
      installationStatus,
      updatedBy: req.user.id
    }

    // 如果状态是已完成，设置完成时间
    if (installationStatus === 'completed') {
      updateData.completionTime = new Date()
    }

    await InstallationTask.update(updateData, {
      where: { id: { [Op.in]: ids } }
    })

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

// 批量删除待安装任务
const batchDelete = async (req, res) => {
  try {
    const { ids } = req.body

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要删除的任务'
      })
    }

    await InstallationTask.destroy({
      where: { id: { [Op.in]: ids } }
    })

    res.json({
      success: true,
      message: '批量删除待安装任务成功'
    })
  } catch (error) {
    console.error('批量删除待安装任务失败:', error)
    res.status(500).json({
      success: false,
      message: '批量删除待安装任务失败',
      error: error.message
    })
  }
}

module.exports = {
  getInstallationTasks,
  getInstallationTaskById,
  createInstallationTask,
  updateInstallationTask,
  deleteInstallationTask,
  getInstallationTaskStats,
  batchUpdateStatus,
  batchDelete
}
