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

// 获取监管任务已结项列表
const getCompletedSupervisions = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      search = '',
      contractNumber = '',
      settlementStatus = ''
    } = req.query

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

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

    // 合同编号筛选
    if (contractNumber) {
      where.contractNumber = contractNumber
    }

    // 结清状态筛选
    if (settlementStatus) {
      where.settlementStatus = settlementStatus
    }

    const { count, rows } = await CompletedSupervision.findAndCountAll({
      where,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ],
      order: [['importTime', '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 getCompletedSupervisionById = async (req, res) => {
  try {
    const { id } = req.params

    const task = await CompletedSupervision.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 createCompletedSupervision = async (req, res) => {
  try {
    const {
      applicationNumber,
      contractNumber,
      productName,
      customerName,
      idType,
      idNumber,
      assetType,
      assetQuantity,
      totalRepaymentPeriods,
      settlementStatus,
      settlementDate,
      settlementAmount,
      remainingAmount,
      settlementNotes
    } = req.body

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

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

    // 验证状态枚举值
    const validStatuses = ['settled', 'unsettled', 'partial']
    if (settlementStatus && !validStatuses.includes(settlementStatus)) {
      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 CompletedSupervision.create({
      applicationNumber,
      contractNumber,
      productName,
      customerName,
      idType,
      idNumber,
      assetType,
      assetQuantity,
      totalRepaymentPeriods,
      settlementStatus: settlementStatus || 'unsettled',
      settlementDate: settlementDate || null,
      importTime: req.body.importTime || new Date(),
      settlementAmount: settlementAmount || null,
      remainingAmount: remainingAmount || null,
      settlementNotes: settlementNotes || null,
      createdBy: req.user.id
    })

    // 获取创建的任务详情（包含关联数据）
    const createdTask = await CompletedSupervision.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 updateCompletedSupervision = async (req, res) => {
  try {
    const { id } = req.params
    const updateData = req.body

    const task = await CompletedSupervision.findByPk(id)
    if (!task) {
      return res.status(404).json({
        success: false,
        message: '监管任务已结项不存在'
      })
    }

    // 验证状态枚举值
    if (updateData.settlementStatus) {
      const validStatuses = ['settled', 'unsettled', 'partial']
      if (!validStatuses.includes(updateData.settlementStatus)) {
        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 CompletedSupervision.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 CompletedSupervision.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 deleteCompletedSupervision = async (req, res) => {
  try {
    const { id } = req.params

    const task = await CompletedSupervision.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 getCompletedSupervisionStats = async (req, res) => {
  try {
    const stats = await CompletedSupervision.findAll({
      attributes: [
        'settlementStatus',
        [CompletedSupervision.sequelize.fn('COUNT', CompletedSupervision.sequelize.col('id')), 'count']
      ],
      group: ['settlementStatus'],
      raw: true
    })

    const totalCount = await CompletedSupervision.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, settlementStatus } = req.body

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

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

    const validStatuses = ['settled', 'unsettled', 'partial']
    if (!validStatuses.includes(settlementStatus)) {
      return res.status(400).json({
        success: false,
        message: '结清状态值无效'
      })
    }

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

    // 如果状态是已结清，设置结清日期
    if (settlementStatus === 'settled') {
      updateData.settlementDate = new Date()
    }

    await CompletedSupervision.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 CompletedSupervision.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 = {
  getCompletedSupervisions,
  getCompletedSupervisionById,
  createCompletedSupervision,
  updateCompletedSupervision,
  deleteCompletedSupervision,
  getCompletedSupervisionStats,
  batchUpdateStatus,
  batchDelete
}
