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.DealerReviewEnum;
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.UnitInfo;
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.boot.module.hygf.biz.vo.RouthPathVO;
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 toDoTasksService;

    @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 regionalCompaniesCode, 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) {
                //添加待办
                RouthPathVO routhPathVO = new RouthPathVO();
                routhPathVO.setRouthPathId(String.valueOf(dealerReview.getUnitInfoId()));
                String routhPath = toDoTasksService.getRouthPath(TaskTypeStationEnum.经销商审核.getCode(),dealerReview.getNextProcessNode(), routhPathVO);
                String wxRouthPath = toDoTasksService.getWxRouthPath(TaskTypeStationEnum.经销商审核.getCode(),dealerReview.getNextProcessNode(), routhPathVO);
                ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.经销商审核.getCode(), dealerReview.getUnitInfoId(), name +"待审核", regionalCompaniesCode, routhPath,wxRouthPath);
                String roleId = toDoTasksService.getRoleIdByName("户用光伏-管理员");
                List<String> todoUserIds = toDoTasksService.getTodoUserIds(null, roleId);
                toDoTasksService.addToDoTasksByUserIds(todoUserIds, toDoTasks);
            }else{
                ToDoTasks toDoTasks = new ToDoTasks(TaskTypeStationEnum.经销商审核.getCode(), dealerReview.getUnitInfoId());
                toDoTasksService.completeToDoTasks(toDoTasks,meg);
            }
                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;

    }

}
