package com.ygtx.gxt.task;

import com.ygtx.common.utils.DateUtils;
import com.ygtx.common.utils.StringUtils;
import com.ygtx.gxt.domain.GxtEquipment;
import com.ygtx.gxt.mapper.GxtEquipmentMapper;
import com.ygtx.system.service.ISysUserService;
import com.ygtx.common.core.domain.entity.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@EnableScheduling
@Component("equipmentSyncTask")
public class EquipmentSyncTask {
    
    private static final Logger log = LoggerFactory.getLogger(EquipmentSyncTask.class);

    @Autowired
    private GxtEquipmentMapper gxtEquipmentMapper;
    
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    @Qualifier("sourceDataSource")
    private DataSource sourceDataSource;
    
    /**
     * 定时同步设备数据
     * 每天凌晨2点执行一次同步任务
     */
    //@Scheduled(cron = "0 0 2 * * ?")
    public void syncEquipment() {
        log.info("设备同步任务开始执行...");
        
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        
        try {
            // 获取源数据库连接
            conn = sourceDataSource.getConnection();
            
            // 记录连接的数据库信息
            DatabaseMetaData metaData = conn.getMetaData();
            // 查询源数据库中的设备数据
            String sql = "SELECT equipment_code, maintenance_center, station, brand, model, responsible_person_name FROM gxt_equipment";
            stmt = conn.prepareStatement(sql);
            rs = stmt.executeQuery();
            
            // 存储从源数据库查询到的设备数据
            List<GxtEquipment> sourceEquipmentList = new ArrayList<>();
            
            int count = 0;
            while (rs.next()) {
                GxtEquipment equipment = new GxtEquipment();
                equipment.setEquipmentCode(rs.getString("equipment_code"));
                equipment.setMaintenanceCenter(rs.getString("maintenance_center"));
                equipment.setStation(rs.getString("station"));
                equipment.setBrand(rs.getString("brand"));
                equipment.setModel(rs.getString("model"));
                
                // 处理责任人信息
                String responsiblePersonName = rs.getString("responsible_person_name");
                if (StringUtils.isNotEmpty(responsiblePersonName)) {
                    equipment.setResponsiblePersonName(responsiblePersonName);
                    processResponsiblePerson(equipment);
                }
                
                // 设置默认值
                equipment.setEquipmentType("1"); // 默认设置为风机
                equipment.setStatus("1"); // 默认设置为正常状态
                
                sourceEquipmentList.add(equipment);
                count++;
            }
            
            log.info("从源数据库查询到 {} 条设备数据", sourceEquipmentList.size());
            
            // 同步数据到当前系统数据库
            syncDataToTargetDatabase(sourceEquipmentList);
            
            log.info("设备同步任务执行完成，共同步 {} 条数据", sourceEquipmentList.size());
        } catch (Exception e) {
            log.error("设备同步任务执行失败：", e);
        } finally {
            // 关闭资源
            closeResources(rs, stmt, conn);
        }
    }
    
    /**
     * 处理设备责任人信息
     * 根据责任人姓名查找系统用户，如果找到唯一用户则设置责任人ID
     * 
     * @param equipment 设备对象
     */
    private void processResponsiblePerson(GxtEquipment equipment) {
        // 如果责任人姓名不为空，则尝试查找对应的用户
        if (StringUtils.isNotEmpty(equipment.getResponsiblePersonName())) {
            List<SysUser> users = sysUserService.selectUserByNickName(equipment.getResponsiblePersonName());
            // 如果只找到一个用户，则设置责任人ID
            if (users != null && users.size() == 1) {
                equipment.setResponsiblePersonId(users.get(0).getUserId());
            }
            // 如果找到多个用户或未找到用户，则不设置责任人ID，保持原值
        }
    }
    
    /**
     * 同步数据到目标数据库
     * 
     * @param sourceEquipmentList 源设备数据列表
     */
    private void syncDataToTargetDatabase(List<GxtEquipment> sourceEquipmentList) {
        if (sourceEquipmentList == null || sourceEquipmentList.isEmpty()) {
            log.info("没有需要同步的设备数据");
            return;
        }
        
        int successCount = 0;
        int updateCount = 0;
        int insertCount = 0;
        
        for (GxtEquipment sourceEquipment : sourceEquipmentList) {
            try {
                // 检查设备是否已存在（根据风机编号、维保中心和场站判断唯一性）
                GxtEquipment existingEquipment = gxtEquipmentMapper.selectGxtEquipmentByCodeAndLocation(sourceEquipment);
                
                if (existingEquipment != null) {
                    // 更新现有设备信息
                    sourceEquipment.setEquipmentId(existingEquipment.getEquipmentId());
                    sourceEquipment.setUpdateTime(DateUtils.getNowDate());
                    gxtEquipmentMapper.updateGxtEquipment(sourceEquipment);
                    updateCount++;
                    log.debug("更新设备: {}", sourceEquipment.getEquipmentCode());
                } else {
                    // 新增设备信息
                    sourceEquipment.setCreateTime(DateUtils.getNowDate());
                    gxtEquipmentMapper.insertGxtEquipment(sourceEquipment);
                    insertCount++;
                    log.debug("新增设备: {}", sourceEquipment.getEquipmentCode());
                }
                successCount++;
            } catch (Exception e) {
                log.error("同步设备数据失败，风机编号：{}，错误信息：{}", 
                    sourceEquipment.getEquipmentCode(), e.getMessage(), e);
            }
        }
        
        log.info("数据同步完成：成功同步 {} 条数据，新增 {} 条，更新 {} 条", 
            successCount, insertCount, updateCount);
    }
    
    /**
     * 关闭数据库资源
     * 
     * @param rs ResultSet
     * @param stmt PreparedStatement
     * @param conn Connection
     */
    private void closeResources(ResultSet rs, PreparedStatement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                log.error("关闭ResultSet失败：", e);
            }
        }
        
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                log.error("关闭PreparedStatement失败：", e);
            }
        }
        
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                log.error("关闭Connection失败：", e);
            }
        }
    }

}