package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.module.hygf.api.Enum.TaskTypeStationEnum;
import com.yeejoin.amos.boot.module.hygf.api.dto.DealerReviewDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.ReviewDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.WorkDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.DealerReview;
import com.yeejoin.amos.boot.module.hygf.api.entity.ToDoTasks;
import com.yeejoin.amos.boot.module.hygf.api.entity.UserMessage;
import com.yeejoin.amos.boot.module.hygf.api.mapper.DealerReviewMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.ToDoTasksMapper;
import com.yeejoin.amos.boot.module.hygf.api.mapper.UserMessageMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.IDealerReviewService;
import com.yeejoin.amos.boot.module.hygf.biz.feign.WorkflowFeignClient;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/8/1
 */
@Service
public class DealerReviewServiceImpl extends BaseService<DealerReviewDto, DealerReview, DealerReviewMapper> implements IDealerReviewService {
    @Autowired
    DealerReviewMapper dealerReviewMapper;
    private static final String IDX_REQUEST_STATE = "200";
    @Autowired
    WorkflowFeignClient workflowFeignClient;
    @Autowired
    protected EmqKeeper emqKeeper;
    @Autowired
    AmosRequestContext requestContext;
    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;
    @Autowired
    ToDoTasksMapper toDoTasksMapper;

    @Value("${amos.system.user.product}")
    private String AMOS_STUDIO_WEB;
    @Value("${amos.system.user.app-key}")
    private String AMOS_STUDIO;
    @Autowired
    UserMessageMapper userMessageMapper;

    @Override
    public com.baomidou.mybatisplus.extension.plugins.pagination.Page<ReviewDto> queryForDealerReviewPage(int pageNum, int pageSize, ReviewDto reviewDto) {
        PageHelper.startPage(pageNum, pageSize);
        List<ReviewDto> list = dealerReviewMapper.queryForDealerReviewPage(reviewDto);
        PageInfo<ReviewDto> page = new PageInfo(list);
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<ReviewDto> pagenew = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<ReviewDto>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

    @Override
    public boolean saveDealerReview(DealerReview dealerReview, boolean flag, boolean token,String name,String meg) {
        try {
            //流程节点code
            if (flag) {
                String flowTaskIdnext = this.getTaskNoAuth(dealerReview.getProcessInstanceId(), token);
                WorkDto workDto = this.getNodeInfoCode(flowTaskIdnext, token);
                dealerReview.setNextProcessNode(workDto.getNextProcessNode());
                dealerReview.setNodeRole(workDto.getNodeRole());
                dealerReview.setNodeRouting(workDto.getNodeRouting());
            }
            boolean fl = this.saveOrUpdate(dealerReview);
            if (flag) {
                ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.经销商审核.getCode(), dealerReview.getSequenceNbr(), "经销商"+name+"待经销商审核",null);
                toDoTasksServiceImpl.addToDoTasksByRole(dealerReview.getNodeRole(), toDoTasks,meg);
            }else{
                LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(ToDoTasks::getType, TaskTypeStationEnum.经销商审核.getCode());
                wrapper.eq(ToDoTasks::getState, "待办");
                wrapper.eq(ToDoTasks::getBusinessId, dealerReview.getSequenceNbr());
                ToDoTasks doTasks= toDoTasksMapper.selectOne(wrapper);
                if(doTasks!=null){
                    doTasks.setState("已办");
                    doTasks.setCompleteTime(new Date());
                    toDoTasksMapper.updateById(doTasks);
                    emqKeeper.getMqttClient().publish("TASK_MESSAGE" , JSON.toJSONString(doTasks).getBytes(), 2 ,false);

                    UserMessage userMessage=  new UserMessage( doTasks.getType(),  doTasks.getBusinessId(),  doTasks.getAmosUserId(),  new Date(),  doTasks.getTaskName()+"已完成."+meg,  doTasks.getAmosOrgCode());
                    userMessageMapper.insert(userMessage);
                    emqKeeper.getMqttClient().publish("MY_MESSAGE" ,JSON.toJSONString(userMessage).getBytes(), 2 ,false);

                }
            }
                return fl;
        } catch (Exception e) {
        	 e.printStackTrace();
        	 return false;
            //
        }
    }

    public WorkDto getNodeInfoCode(String flowTaskId, boolean token) {
        WorkDto workDto = null;
            FeignClientResult<JSONObject> jSONObject = null;
            if (token) {
                jSONObject = workflowFeignClient.getNodeInfo(flowTaskId);

            } else {
                jSONObject = workflowFeignClient.getNodeInfotoken(AMOS_STUDIO, AMOS_STUDIO_WEB, requestContext.getToken(), flowTaskId);
            }

            if (IDX_REQUEST_STATE.equals(String.valueOf(jSONObject.getStatus()))) {
                JSONObject js = jSONObject.getResult();
                if (js == null) {
                    throw new BaseException("获取工作流节点失败！", "400", "获取工作流节点失败！");
                }
                LinkedHashMap taskInfo = js.get("taskInfo") != null ? (LinkedHashMap) js.get("taskInfo") : null;
                String nextProcessNode = taskInfo != null ? taskInfo.get("taskDefinitionKey").toString() : null;
                List<LinkedHashMap> executor = js.get("executor") != null ? (List<LinkedHashMap>) js.get("executor") : null;
                String nodeRole = null;
                if (!executor.isEmpty()) {
                    List<String> idList = executor.stream().map(e -> e.get("groupId").toString()).collect(Collectors.toList());
                    nodeRole = StringUtils.join(idList, ",");
                }
                LinkedHashMap extensionInfo = js.get("extensionInfo") != null ? (LinkedHashMap) js.get("extensionInfo") : null;
                String nodeRouting = extensionInfo != null ? extensionInfo.get("nodeRole").toString() : null;

                workDto = new WorkDto(nodeRouting, nodeRole, nextProcessNode);
            }

            return workDto;

    }

    public String getTaskNoAuth(String processInstanceId, boolean token) {
        String flowTaskId = null;
            JSONObject jSONObject = null;
            if (token) {
                jSONObject = workflowFeignClient.getTaskNoAuth(processInstanceId);

            } else {
                jSONObject = workflowFeignClient.getTaskNoAuthtoken(AMOS_STUDIO, AMOS_STUDIO_WEB, requestContext.getToken(), processInstanceId);
            }
            if (IDX_REQUEST_STATE.equals(String.valueOf(jSONObject.get("code")))) {
                LinkedHashMap jsd = jSONObject.get("data") != null ? (LinkedHashMap) jSONObject.get("data") : null;
                flowTaskId = jsd != null ? jsd.get("id").toString() : null;
            }
            if (flowTaskId == null) {
                throw new BaseException("获取工作流节点失败！", "400", "获取工作流节点失败！");
            }
            return flowTaskId;

    }

}
