package com.aucma.production.controller;

import com.aucma.base.domain.BaseProductLine;
import com.aucma.base.service.IBaseProductLineService;
import com.aucma.common.constant.AnDonConstants;
import com.aucma.common.core.domain.AjaxResult;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.production.domain.AndonEvent;
import com.aucma.production.domain.AndonEventAssignment;
import com.aucma.production.domain.AndonRule;
import com.aucma.production.mapper.AndonRuleMapper;
import com.aucma.production.service.IAndonEventAssignmentService;
import com.aucma.production.service.IAndonEventService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 手持设备安灯呼叫接口（极简版）
 * 
 * 业务流程：
 * 1. 手持PDA已绑定工位（stationCode）
 * 2. 用户点击安灯按钮，PDA调用 /call-types 获取该工位可用的呼叫类型
 * 3. PDA显示呼叫类型按钮，用户选择一个
 * 4. PDA调用 /call 发送 stationCode + callTypeCode
 * 5. 后台匹配安灯规则，生成事件并自动派工
 * 6. 大屏看板实时显示事件
 *
 * @author Yinq
 * @date 2025-12-29
 */
@RestController
@RequestMapping("/production/andon/mobile")
public class AndonMobileController {

    @Autowired
    private IBaseProductLineService baseProductLineService;

    @Autowired
    private AndonRuleMapper andonRuleMapper;

    @Autowired
    private IAndonEventService andonEventService;

    @Autowired
    private IAndonEventAssignmentService andonEventAssignmentService;

    /**
     * 【接口1】获取工位可用的呼叫类型列表
     * 
     * PDA先调用此接口获取该工位配置的所有呼叫类型，然后显示按钮让用户选择
     * 
     * @param stationCode 工位编码
     * @return 呼叫类型列表 [{callTypeCode, callTypeName, ruleName}]
     */
    @GetMapping("/call-types")
    public AjaxResult getCallTypes(@RequestParam String stationCode) {
        if (StringUtils.isEmpty(stationCode)) {
            return AjaxResult.error("工位编码不能为空");
        }
        
        // 查询该工位配置的所有安灯规则
        AndonRule ruleQuery = new AndonRule();
        ruleQuery.setStationCode(stationCode);
        ruleQuery.setIsFlag(AnDonConstants.FLAG_VALID);
        List<AndonRule> rules = andonRuleMapper.selectAndonRuleList(ruleQuery);
        
        if (rules == null || rules.isEmpty()) {
            return AjaxResult.error("该工位未配置安灯规则，请联系管理员");
        }
        
        // 构建返回数据
        List<Map<String, Object>> callTypes = new ArrayList<>();
        for (AndonRule rule : rules) {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("callTypeCode", rule.getCallTypeCode());
            item.put("ruleName", rule.getRuleName());
            item.put("ruleId", rule.getRuleId());
            callTypes.add(item);
        }
        
        return AjaxResult.success(callTypes);
    }

    /**
     * 【接口2】提交安灯呼叫
     * 
     * @param stationCode 工位编码（必填）
     * @param callTypeCode 呼叫类型编码（必填）- 从 /call-types 接口获取
     * @return 创建的安灯事件信息
     */
    @PostMapping("/call")
    public AjaxResult submitAndonCall(@RequestParam String stationCode,
                                      @RequestParam String callTypeCode) {
        System.out.println("stationCode: " + stationCode + ", callTypeCode: " + callTypeCode);
        // 参数校验
        if (StringUtils.isEmpty(stationCode)) {
            return AjaxResult.error("工位编码不能为空");
        }
        if (StringUtils.isEmpty(callTypeCode)) {
            return AjaxResult.error("呼叫类型不能为空");
        }

        // 1. 根据 stationCode 查询产线信息（productLineType=2 表示工位）
        BaseProductLine lineQuery = new BaseProductLine(); 
        lineQuery.setProductLineCode(stationCode);
        lineQuery.setProductLineType(2L);  // 2表示工位类型
        List<BaseProductLine> lines = baseProductLineService.selectBaseProductLineList(lineQuery);
        if (lines == null || lines.isEmpty()) {
            return AjaxResult.error("工位不存在：" + stationCode);
        }
        BaseProductLine productLine = lines.get(0);
        String productLineCode = productLine.getParentId();  // 父级产线编码

        // 2. 根据 stationCode + callTypeCode 匹配安灯规则
        AndonRule ruleQuery = new AndonRule();
        ruleQuery.setStationCode(stationCode);
        ruleQuery.setCallTypeCode(callTypeCode);
        ruleQuery.setIsFlag(AnDonConstants.FLAG_VALID);
        List<AndonRule> rules = andonRuleMapper.selectAndonRuleList(ruleQuery);
        if (rules == null || rules.isEmpty()) {
            return AjaxResult.error("未找到该工位+呼叫类型的安灯规则");
        }
        AndonRule rule = rules.get(0);

        // 3. 构建安灯事件
        AndonEvent event = new AndonEvent();
        
        // 生成呼叫单号
        event.setCallCode(generateCallCode());
        
        // 从规则获取呼叫类型
        event.setCallTypeCode(rule.getCallTypeCode());
        
        // 从工位获取产线
        event.setProductLineCode(productLineCode);
        event.setStationCode(stationCode);

         // 呼叫人（可选，默认为PDA）
         event.setCreateBy(SecurityUtils.getLoginUser().getUserId() != null ? SecurityUtils.getLoginUser().getUserId().toString() : "PDA");
        
        
        // 触发源类型：工位
        event.setSourceType(AnDonConstants.SourceType.STATION);
        
        // 初始状态
        event.setEventStatus(AnDonConstants.EventStatus.PENDING);
        event.setIsFlag(AnDonConstants.FLAG_VALID);
        event.setCreateTime(DateUtils.getNowDate());

        // 4. 调用服务保存（自动匹配规则、计算时限、创建派工）
        int result = andonEventService.insertAndonEvent(event);
        
        if (result > 0) {
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("eventId", event.getEventId());
            data.put("callCode", event.getCallCode());
            data.put("stationName", productLine.getProductLineName());
            data.put("callType", rule.getRuleName());
            data.put("message", "安灯呼叫成功，已通知相关人员");
            return AjaxResult.success(data);
        } else {
            return AjaxResult.error("安灯呼叫失败");
        }
    }

    /**
     * 【接口3】获取当前用户的派工任务列表
     * 
     * @return 派工任务列表
     */
    @GetMapping("/my-assignments")
    public AjaxResult getMyAssignments() {
        Long userId = SecurityUtils.getUserId();
        if (userId == null) {
            return AjaxResult.error("未获取到用户信息");
        }
        
        AndonEventAssignment query = new AndonEventAssignment();
        query.setAssigneeUserId(userId);
        query.setIsFlag(AnDonConstants.FLAG_VALID);
        List<AndonEventAssignment> assignments = andonEventAssignmentService.selectAndonEventAssignmentList(query);
        
        // 过滤只返回待处理和处理中的任务
        List<Map<String, Object>> result = new ArrayList<>();
        for (AndonEventAssignment a : assignments) {
            String status = a.getStatus();
            if (AnDonConstants.AssignmentStatus.ASSIGNED.equals(status) || 
                AnDonConstants.AssignmentStatus.ACCEPTED.equals(status)) {
                Map<String, Object> item = new LinkedHashMap<>();
                item.put("assignmentId", a.getAssignmentId());
                item.put("eventId", a.getEventId());
                item.put("status", a.getStatus());
                item.put("statusName", getAssignmentStatusName(a.getStatus()));
                item.put("assignedTime", a.getAssignedTime());
                item.put("acceptTime", a.getAcceptTime());
                
                // 获取事件详情
                if (a.getEventId() != null) {
                    AndonEvent event = andonEventService.selectAndonEventByEventId(a.getEventId());
                    if (event != null) {
                        item.put("callCode", event.getCallCode());
                        item.put("callTypeCode", event.getCallTypeCode());
                        item.put("stationCode", event.getStationCode());
                        item.put("productLineCode", event.getProductLineCode());
                        item.put("eventStatus", event.getEventStatus());
                        item.put("createTime", event.getCreateTime());
                    }
                }
                result.add(item);
            }
        }
        
        return AjaxResult.success(result);
    }

    /**
     * 【接口4】接单 - 接受派工任务
     * 
     * @param assignmentId 派工ID
     * @return 操作结果
     */
    @PostMapping("/accept")
    public AjaxResult acceptAssignment(@RequestParam Long assignmentId) {
        if (assignmentId == null) {
            return AjaxResult.error("派工ID不能为空");
        }
        
        AndonEventAssignment assignment = andonEventAssignmentService.selectAndonEventAssignmentByAssignmentId(assignmentId);
        if (assignment == null) {
            return AjaxResult.error("派工记录不存在");
        }
        
        // 检查状态是否为已分配
        if (!AnDonConstants.AssignmentStatus.ASSIGNED.equals(assignment.getStatus())) {
            return AjaxResult.error("当前状态不允许接单，当前状态：" + getAssignmentStatusName(assignment.getStatus()));
        }
        
        // 更新状态为已接受，后端会自动设置acceptTime
        assignment.setStatus(AnDonConstants.AssignmentStatus.ACCEPTED);
        int result = andonEventAssignmentService.updateAndonEventAssignment(assignment);
        
        if (result > 0) {
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("assignmentId", assignmentId);
            data.put("status", AnDonConstants.AssignmentStatus.ACCEPTED);
            data.put("statusName", "已接单");
            data.put("acceptTime", DateUtils.getNowDate());
            data.put("message", "接单成功");
            return AjaxResult.success(data);
        } else {
            return AjaxResult.error("接单失败");
        }
    }

    /**
     * 【接口5】完成 - 完成派工任务
     * 
     * @param assignmentId 派工ID
     * @param resolution 解决措施（可选）
     * @return 操作结果
     */
    @PostMapping("/complete")
    public AjaxResult completeAssignment(@RequestParam Long assignmentId,
                                         @RequestParam(required = false) String resolution) {
        if (assignmentId == null) {
            return AjaxResult.error("派工ID不能为空");
        }
        
        AndonEventAssignment assignment = andonEventAssignmentService.selectAndonEventAssignmentByAssignmentId(assignmentId);
        if (assignment == null) {
            return AjaxResult.error("派工记录不存在");
        }
        
        // 检查状态是否为已接受
        if (!AnDonConstants.AssignmentStatus.ACCEPTED.equals(assignment.getStatus())) {
            return AjaxResult.error("请先接单后再完成，当前状态：" + getAssignmentStatusName(assignment.getStatus()));
        }
        
        // 更新状态为已完成，后端会自动设置finishTime
        assignment.setStatus(AnDonConstants.AssignmentStatus.DONE);
        if (StringUtils.isNotEmpty(resolution)) {
            assignment.setRemark(resolution);
        }
        int result = andonEventAssignmentService.updateAndonEventAssignment(assignment);
        
        if (result > 0) {
            Map<String, Object> data = new LinkedHashMap<>();
            data.put("assignmentId", assignmentId);
            data.put("status", AnDonConstants.AssignmentStatus.DONE);
            data.put("statusName", "已完成");
            data.put("finishTime", DateUtils.getNowDate());
            data.put("message", "完成成功，事件已解决");
            return AjaxResult.success(data);
        } else {
            return AjaxResult.error("完成操作失败");
        }
    }

    /**
     * 【接口6】获取事件详情
     * 
     * @param eventId 事件ID
     * @return 事件详情
     */
    @GetMapping("/event-detail")
    public AjaxResult getEventDetail(@RequestParam Long eventId) {
        if (eventId == null) {
            return AjaxResult.error("事件ID不能为空");
        }
        
        AndonEvent event = andonEventService.selectAndonEventByEventId(eventId);
        if (event == null) {
            return AjaxResult.error("事件不存在");
        }
        
        Map<String, Object> data = new LinkedHashMap<>();
        data.put("eventId", event.getEventId());
        data.put("callCode", event.getCallCode());
        data.put("callTypeCode", event.getCallTypeCode());
        data.put("productLineCode", event.getProductLineCode());
        data.put("stationCode", event.getStationCode());
        data.put("sourceType", event.getSourceType());
        data.put("eventStatus", event.getEventStatus());
        data.put("eventStatusName", getEventStatusName(event.getEventStatus()));
        data.put("priority", event.getPriority());
        data.put("createTime", event.getCreateTime());
        data.put("ackTime", event.getAckTime());
        data.put("responseStartTime", event.getResponseStartTime());
        data.put("responseEndTime", event.getResponseEndTime());
        data.put("resolution", event.getResolution());
        
        return AjaxResult.success(data);
    }

    /**
     * 生成呼叫单号
     * 格式：AD + 年月日时分秒 + 3位随机数
     */
    private String generateCallCode() {
        String dateStr = DateUtils.dateTimeNow("yyyyMMddHHmmss");
        int random = (int) (Math.random() * 900) + 100; // 100-999
        return "AD" + dateStr + random;
    }

    /**
     * 获取派工状态名称
     */
    private String getAssignmentStatusName(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "0": return "待接单";
            case "1": return "已接单";
            case "2": return "已拒绝";
            case "3": return "已完成";
            case "4": return "已取消";
            default: return "未知";
        }
    }

    /**
     * 获取事件状态名称
     */
    private String getEventStatusName(String status) {
        if (status == null) return "未知";
        switch (status) {
            case "0": return "待处理";
            case "1": return "处理中";
            case "2": return "已解决";
            case "3": return "已取消";
            default: return "未知";
        }
    }
}
