package org.xyzh.workcase.service;

import java.util.List;

import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.xyzh.api.workcase.dto.TbWorkcaseDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseDeviceDTO;
import org.xyzh.api.workcase.dto.TbWorkcaseProcessDTO;
import org.xyzh.api.workcase.service.WorkcaseChatService;
import org.xyzh.api.workcase.service.WorkcaseService;
import org.xyzh.common.core.domain.ResultDomain;
import org.xyzh.common.core.page.PageDomain;
import org.xyzh.common.core.page.PageParam;
import org.xyzh.common.core.page.PageRequest;
import org.xyzh.common.utils.id.IdUtil;
import org.xyzh.workcase.enums.WorkcaseProcessAction;
import org.xyzh.workcase.mapper.TbWorkcaseDeviceMapper;
import org.xyzh.workcase.mapper.TbWorkcaseMapper;
import org.xyzh.workcase.mapper.TbWorkcaseProcessMapper;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

@DubboService(version = "1.0.0",group = "workcase",timeout = 30000,retries = 0)
public class WorkcaseServiceImpl implements WorkcaseService {
    private static final Logger logger = LoggerFactory.getLogger(WorkcaseServiceImpl.class);

    @Autowired
    private TbWorkcaseMapper workcaseMapper;

    @Autowired
    private TbWorkcaseProcessMapper workcaseProcessMapper;

    @Autowired
    private TbWorkcaseDeviceMapper workcaseDeviceMapper;

    @Autowired
    private WorkcaseChatService workcaseChatService;

    // ====================== 工单管理 ======================

    @Override
    public ResultDomain<TbWorkcaseDTO> createWorkcase(TbWorkcaseDTO workcase) {
        logger.info("创建工单: userId={}, type={}", workcase.getUserId(), workcase.getType());
        
        if (workcase.getWorkcaseId() == null || workcase.getWorkcaseId().isEmpty()) {
            workcase.setWorkcaseId(IdUtil.generateUUID());
        }
        if (workcase.getOptsn() == null || workcase.getOptsn().isEmpty()) {
            workcase.setOptsn(IdUtil.getOptsn());
        }
        if (workcase.getStatus() == null || workcase.getStatus().isEmpty()) {
            workcase.setStatus("pending");
        }
        if (workcase.getEmergency() == null || workcase.getEmergency().isEmpty()) {
            workcase.setEmergency("normal");
        }
        
        int rows = workcaseMapper.insertWorkcase(workcase);
        if (rows > 0) {
            TbWorkcaseProcessDTO process = new TbWorkcaseProcessDTO();
            process.setProcessId(IdUtil.generateUUID());
            process.setOptsn(IdUtil.getOptsn());
            process.setWorkcaseId(workcase.getWorkcaseId());
            process.setAction(WorkcaseProcessAction.INFO.getName());
            process.setMessage("工单创建");
            process.setCreator(workcase.getCreator());
            workcaseProcessMapper.insertWorkcaseProcess(process);
            
            syncWorkcaseToCrm(workcase);
            sendWechatKefuWelcome(workcase);
            
            return ResultDomain.success("创建成功", workcase);
        }
        return ResultDomain.failure("创建失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> updateWorkcase(TbWorkcaseDTO workcase) {
        logger.info("更新工单: workcaseId={}, status={}", workcase.getWorkcaseId(), workcase.getStatus());
        
        TbWorkcaseDTO existing = workcaseMapper.selectWorkcaseById(workcase.getWorkcaseId());
        if (existing == null) {
            return ResultDomain.failure("工单不存在");
        }
        
        String oldStatus = existing.getStatus();
        int rows = workcaseMapper.updateWorkcase(workcase);
        
        if (rows > 0) {
            TbWorkcaseDTO updated = workcaseMapper.selectWorkcaseById(workcase.getWorkcaseId());
            
            if (workcase.getStatus() != null && !workcase.getStatus().equals(oldStatus)) {
                TbWorkcaseProcessDTO process = new TbWorkcaseProcessDTO();
                process.setProcessId(IdUtil.generateUUID());
                process.setOptsn(IdUtil.getOptsn());
                process.setWorkcaseId(workcase.getWorkcaseId());
                process.setCreator(workcase.getCreator());
                
                if ("done".equals(workcase.getStatus())) {
                    process.setAction(WorkcaseProcessAction.FINISH.getName());
                    process.setMessage("工单完成");
                    workcaseChatService.summaryChat(existing.getWorkcaseId());
                } else if ("cancelled".equals(workcase.getStatus())) {
                    process.setAction(WorkcaseProcessAction.REPEAL.getName());
                    process.setMessage("工单撤销");
                    workcaseChatService.summaryChat(existing.getWorkcaseId());
                } else {
                    process.setAction(WorkcaseProcessAction.INFO.getName());
                    process.setMessage("状态变更: " + oldStatus + " -> " + workcase.getStatus());
                }
                workcaseProcessMapper.insertWorkcaseProcess(process);
            }
            
            syncWorkcaseToCrm(updated);
            
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> deleteWorkcase(TbWorkcaseDTO workcase) {
        logger.info("删除工单: workcaseId={}", workcase.getWorkcaseId());
        
        int rows = workcaseMapper.deleteWorkcase(workcase);
        if (rows > 0) {
            return ResultDomain.success("删除成功", workcase);
        }
        return ResultDomain.failure("删除失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> getWorkcaseById(String workcaseId) {
        TbWorkcaseDTO workcase = workcaseMapper.selectWorkcaseById(workcaseId);
        if (workcase != null) {
            return ResultDomain.success("查询成功", workcase);
        }
        return ResultDomain.failure("工单不存在");
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> getWorkcaseList(TbWorkcaseDTO filter) {
        List<TbWorkcaseDTO> list = workcaseMapper.selectWorkcaseList(filter);
        return ResultDomain.success("查询成功", list);
    }

    @Override
    public ResultDomain<TbWorkcaseDTO> getWorkcasePage(PageRequest<TbWorkcaseDTO> pageRequest) {
        TbWorkcaseDTO filter = pageRequest.getFilter();
        PageParam pageParam = pageRequest.getPageParam();
        
        List<TbWorkcaseDTO> list = workcaseMapper.selectWorkcasePage(filter, pageParam);
        long total = workcaseMapper.countWorkcases(filter);
        
        pageParam.setTotal((int) total);
        PageDomain<TbWorkcaseDTO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

    // ====================== 同步到CRM和接收 ===================

    @Override
    public ResultDomain<Void> syncWorkcaseToCrm(TbWorkcaseDTO workcase) {
        logger.info("同步工单到CRM: workcaseId={}", workcase.getWorkcaseId());
        
        // ============== 伪代码：同步工单到CRM系统 ==============
        // 1. 构建CRM请求数据
        // JSONObject crmData = new JSONObject();
        // crmData.put("workcaseId", workcase.getWorkcaseId());
        // crmData.put("userId", workcase.getUserId());
        // crmData.put("username", workcase.getUsername());
        // crmData.put("phone", workcase.getPhone());
        // crmData.put("type", workcase.getType());
        // crmData.put("device", workcase.getDevice());
        // crmData.put("deviceCode", workcase.getDeviceCode());
        // crmData.put("emergency", workcase.getEmergency());
        // crmData.put("status", workcase.getStatus());
        // crmData.put("createTime", workcase.getCreateTime());
        
        // 2. 调用CRM接口
        // String crmApiUrl = "https://crm.example.com/api/workcase/sync";
        // HttpHeaders headers = new HttpHeaders();
        // headers.setContentType(MediaType.APPLICATION_JSON);
        // headers.set("Authorization", "Bearer " + crmToken);
        // HttpEntity<String> request = new HttpEntity<>(crmData.toJSONString(), headers);
        // ResponseEntity<String> response = restTemplate.postForEntity(crmApiUrl, request, String.class);
        
        // 3. 处理响应
        // if (response.getStatusCode() == HttpStatus.OK) {
        //     JSONObject result = JSON.parseObject(response.getBody());
        //     String crmWorkcaseId = result.getString("crmWorkcaseId");
        //     logger.info("同步成功，CRM工单ID: {}", crmWorkcaseId);
        // } else {
        //     logger.error("同步失败: {}", response.getBody());
        //     return ResultDomain.failure("同步CRM失败");
        // }
        // ============== 伪代码结束 ==============
        
        logger.info("CRM同步完成（伪代码）: workcaseId={}", workcase.getWorkcaseId());
        return ResultDomain.success("同步成功");
    }

    @Override
    public ResultDomain<Void> receiveWorkcaseFromCrm(JSONObject json) {
        logger.info("接收CRM工单更新");
        
        // ============== 伪代码：接收CRM的工单处理结果 ==============
        // 1. 解析CRM推送的数据
        // JSONObject crmData = (JSONObject) json;
        // String workcaseId = crmData.getString("workcaseId");
        // String status = crmData.getString("status");
        // String processor = crmData.getString("processor");
        // String message = crmData.getString("message");
        
        // 2. 更新本地工单
        // TbWorkcaseDTO workcase = new TbWorkcaseDTO();
        // workcase.setWorkcaseId(workcaseId);
        // workcase.setStatus(status);
        // workcase.setProcessor(processor);
        // workcaseMapper.updateWorkcase(workcase);
        
        // 3. 记录处理过程
        // TbWorkcaseProcessDTO process = new TbWorkcaseProcessDTO();
        // process.setProcessId(UUID.randomUUID().toString().replace("-", ""));
        // process.setOptsn(SnowflakeIdUtil.nextIdStr());
        // process.setWorkcaseId(workcaseId);
        // process.setAction(WorkcaseProcessAction.INFO.getName());
        // process.setMessage("CRM更新: " + message);
        // process.setProcessor(processor);
        // process.setCreator("CRM_SYSTEM");
        // workcaseProcessMapper.insertWorkcaseProcess(process);
        
        // 4. 如果工单完成或撤销，触发总结
        // if ("done".equals(status) || "cancelled".equals(status)) {
        //     workcaseChatService.summaryChat(workcaseId);
        // }
        // ============== 伪代码结束 ==============
        
        logger.info("CRM工单接收处理完成（伪代码）");
        return ResultDomain.success("接收成功");
    }

    private void sendWechatKefuWelcome(TbWorkcaseDTO workcase) {
        logger.info("发送微信客服欢迎语: workcaseId={}", workcase.getWorkcaseId());
        
        // ============== 伪代码：发送微信客服欢迎语 ==============
        // 1. 构建欢迎语内容（包含工单基本信息）
        // StringBuilder welcomeMsg = new StringBuilder();
        // welcomeMsg.append("【工单信息】\n");
        // welcomeMsg.append("工单编号：").append(workcase.getOptsn()).append("\n");
        // welcomeMsg.append("故障类型：").append(workcase.getType()).append("\n");
        // welcomeMsg.append("设备名称：").append(workcase.getDevice()).append("\n");
        // welcomeMsg.append("紧急程度：").append("emergency".equals(workcase.getEmergency()) ? "紧急" : "普通").append("\n");
        // welcomeMsg.append("联系人：").append(workcase.getUsername()).append("\n");
        // welcomeMsg.append("联系电话：").append(workcase.getPhone()).append("\n");
        // welcomeMsg.append("\n客服将尽快为您处理，请稍候...");
        
        // 2. 获取微信客服接入链接
        // String kefuUrl = wechatKefuService.getKefuUrl(workcase.getUserId());
        
        // 3. 调用微信客服API发送欢迎语
        // JSONObject msgBody = new JSONObject();
        // msgBody.put("touser", workcase.getUserId());  // 微信openid
        // msgBody.put("msgtype", "text");
        // JSONObject textContent = new JSONObject();
        // textContent.put("content", welcomeMsg.toString());
        // msgBody.put("text", textContent);
        
        // String accessToken = wechatService.getAccessToken();
        // String apiUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken;
        // restTemplate.postForEntity(apiUrl, msgBody.toJSONString(), String.class);
        
        // 4. 记录客服会话开始
        // wechatKefuService.startSession(workcase.getUserId(), workcase.getWorkcaseId());
        // ============== 伪代码结束 ==============
        
        logger.info("微信客服欢迎语发送完成（伪代码）: workcaseId={}", workcase.getWorkcaseId());
    }

    // ====================== 工单处理过程 ======================

    @Override
    public ResultDomain<TbWorkcaseProcessDTO> createWorkcaseProcess(TbWorkcaseProcessDTO workcaseProcess) {
        logger.info("创建工单过程: workcaseId={}, action={}", workcaseProcess.getWorkcaseId(), workcaseProcess.getAction());
        
        if (workcaseProcess.getProcessId() == null || workcaseProcess.getProcessId().isEmpty()) {
            workcaseProcess.setProcessId(IdUtil.generateUUID());
        }
        if (workcaseProcess.getOptsn() == null || workcaseProcess.getOptsn().isEmpty()) {
            workcaseProcess.setOptsn(IdUtil.getOptsn());
        }
        
        String action = workcaseProcess.getAction();
        if (WorkcaseProcessAction.ASSIGN.getName().equals(action) || 
            WorkcaseProcessAction.REDEPLOY.getName().equals(action)) {
            if (workcaseProcess.getProcessor() != null) {
                TbWorkcaseDTO workcase = new TbWorkcaseDTO();
                workcase.setWorkcaseId(workcaseProcess.getWorkcaseId());
                workcase.setProcessor(workcaseProcess.getProcessor());
                workcase.setStatus("processing");
                workcaseMapper.updateWorkcase(workcase);
            }
        } else if (WorkcaseProcessAction.FINISH.getName().equals(action)) {
            TbWorkcaseDTO workcase = new TbWorkcaseDTO();
            workcase.setWorkcaseId(workcaseProcess.getWorkcaseId());
            workcase.setStatus("done");
            workcaseMapper.updateWorkcase(workcase);
            workcaseChatService.summaryChat(workcaseProcess.getWorkcaseId());
        } else if (WorkcaseProcessAction.REPEAL.getName().equals(action)) {
            TbWorkcaseDTO workcase = new TbWorkcaseDTO();
            workcase.setWorkcaseId(workcaseProcess.getWorkcaseId());
            workcase.setStatus("cancelled");
            workcaseMapper.updateWorkcase(workcase);
            workcaseChatService.summaryChat(workcaseProcess.getWorkcaseId());
        }
        
        int rows = workcaseProcessMapper.insertWorkcaseProcess(workcaseProcess);
        if (rows > 0) {
            TbWorkcaseDTO workcase = workcaseMapper.selectWorkcaseById(workcaseProcess.getWorkcaseId());
            if (workcase != null) {
                syncWorkcaseToCrm(workcase);
            }
            return ResultDomain.success("创建成功", workcaseProcess);
        }
        return ResultDomain.failure("创建失败");
    }

    @Override
    public ResultDomain<TbWorkcaseProcessDTO> updateWorkcaseProcess(TbWorkcaseProcessDTO workcaseProcess) {
        logger.info("更新工单过程: processId={}", workcaseProcess.getProcessId());
        
        int rows = workcaseProcessMapper.updateWorkcaseProcess(workcaseProcess);
        if (rows > 0) {
            TbWorkcaseProcessDTO updated = workcaseProcessMapper.selectWorkcaseProcessById(workcaseProcess.getProcessId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<TbWorkcaseProcessDTO> deleteWorkcaseProcess(TbWorkcaseProcessDTO workcaseProcess) {
        logger.info("删除工单过程: processId={}", workcaseProcess.getProcessId());
        
        int rows = workcaseProcessMapper.deleteWorkcaseProcess(workcaseProcess.getProcessId());
        if (rows > 0) {
            return ResultDomain.success("删除成功", workcaseProcess);
        }
        return ResultDomain.failure("删除失败");
    }

    @Override
    public ResultDomain<TbWorkcaseProcessDTO> getWorkcaseProcessList(TbWorkcaseProcessDTO filter) {
        List<TbWorkcaseProcessDTO> list = workcaseProcessMapper.selectWorkcaseProcessList(filter);
        return ResultDomain.success("查询成功", list);
    }

    @Override
    public ResultDomain<TbWorkcaseProcessDTO> getWorkcaseProcessPage(PageRequest<TbWorkcaseProcessDTO> pageRequest) {
        TbWorkcaseProcessDTO filter = pageRequest.getFilter();
        PageParam pageParam = pageRequest.getPageParam();
        
        List<TbWorkcaseProcessDTO> list = workcaseProcessMapper.selectWorkcaseProcessPage(filter, pageParam);
        long total = workcaseProcessMapper.countWorkcaseProcesses(filter);
        
        pageParam.setTotal((int) total);
        PageDomain<TbWorkcaseProcessDTO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

    // ====================== 工单设备管理 ======================

    @Override
    public ResultDomain<TbWorkcaseDeviceDTO> createWorkcaseDevice(TbWorkcaseDeviceDTO workcaseDevice) {
        logger.info("创建工单设备: workcaseId={}, device={}", workcaseDevice.getWorkcaseId(), workcaseDevice.getDevice());
        
        if (workcaseDevice.getOptsn() == null || workcaseDevice.getOptsn().isEmpty()) {
            workcaseDevice.setOptsn(IdUtil.getOptsn());
        }
        
        int rows = workcaseDeviceMapper.insertWorkcaseDevice(workcaseDevice);
        if (rows > 0) {
            return ResultDomain.success("创建成功", workcaseDevice);
        }
        return ResultDomain.failure("创建失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDeviceDTO> updateWorkcaseDevice(TbWorkcaseDeviceDTO workcaseDevice) {
        logger.info("更新工单设备: workcaseId={}, fileId={}", workcaseDevice.getWorkcaseId(), workcaseDevice.getFileId());
        
        int rows = workcaseDeviceMapper.updateWorkcaseDevice(workcaseDevice);
        if (rows > 0) {
            TbWorkcaseDeviceDTO updated = workcaseDeviceMapper.selectWorkcaseDeviceById(
                workcaseDevice.getWorkcaseId(), workcaseDevice.getFileId());
            return ResultDomain.success("更新成功", updated);
        }
        return ResultDomain.failure("更新失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDeviceDTO> deleteWorkcaseDevice(TbWorkcaseDeviceDTO workcaseDevice) {
        logger.info("删除工单设备: workcaseId={}, fileId={}", workcaseDevice.getWorkcaseId(), workcaseDevice.getFileId());
        
        int rows = workcaseDeviceMapper.deleteWorkcaseDevice(workcaseDevice.getWorkcaseId(), workcaseDevice.getFileId());
        if (rows > 0) {
            return ResultDomain.success("删除成功", workcaseDevice);
        }
        return ResultDomain.failure("删除失败");
    }

    @Override
    public ResultDomain<TbWorkcaseDeviceDTO> getWorkcaseDeviceList(TbWorkcaseDeviceDTO filter) {
        List<TbWorkcaseDeviceDTO> list = workcaseDeviceMapper.selectWorkcaseDeviceList(filter);
        return ResultDomain.success("查询成功", list);
    }

    @Override
    public ResultDomain<TbWorkcaseDeviceDTO> getWorkcaseDevicePage(PageRequest<TbWorkcaseDeviceDTO> pageRequest) {
        TbWorkcaseDeviceDTO filter = pageRequest.getFilter();
        PageParam pageParam = pageRequest.getPageParam();
        
        List<TbWorkcaseDeviceDTO> list = workcaseDeviceMapper.selectWorkcaseDevicePage(filter, pageParam);
        long total = workcaseDeviceMapper.countWorkcaseDevices(filter);
        
        pageParam.setTotal((int) total);
        PageDomain<TbWorkcaseDeviceDTO> pageDomain = new PageDomain<>(pageParam, list);
        return ResultDomain.success("查询成功", pageDomain);
    }

}
