package com.chinaweal.aiccs.aiccs.business.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinaweal.aiccs.aiccs.business.entity.XrActivity;
import com.chinaweal.aiccs.aiccs.business.entity.XrOpinion;
import com.chinaweal.aiccs.aiccs.business.entity.XrTaskList;
import com.chinaweal.aiccs.aiccs.business.mapper.XrTaskListMapper;
import com.chinaweal.aiccs.aiccs.business.rules.model.NodeModel;
import com.chinaweal.aiccs.aiccs.business.service.IXrActivityService;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskAnnexService;
import com.chinaweal.aiccs.aiccs.business.service.IXrTaskListService;
import com.chinaweal.aiccs.aiccs.seriousillegalPerson.entity.dto.PersonSpeSaveIvdDto;
import com.chinaweal.aiccs.common.constant.BaseDataConstant;
import com.chinaweal.aiccs.common.constant.FlowConstant;
import com.chinaweal.aiccs.common.util.HandleWorkFlowUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.org.entity.TUsers;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
 * <p>
 * 待办列表 服务实现类
 * </p>
 *
 * @author quebh
 * @since 2023-05-04
 */

@Service
public class XrTaskListServiceImpl extends ServiceImpl<XrTaskListMapper, XrTaskList> implements IXrTaskListService {

    @Resource
    private IXrActivityService iXrActivityService;
    @Resource
    private TUsersService itUsersService;
    @Resource
    private IXrTaskAnnexService iXrTaskAnnexService;


    @Override
    public void updateWorkFlow(XrOpinion opinion, XrTaskList xrTaskList, String nextNodeID, String[] nextPerformerIds, String permission) {
        List<AICUser> userList = new ArrayList<>();

        if (nextPerformerIds.length > 0) {
            List<TUsers> tUsersList = itUsersService.listByUserIds(nextPerformerIds);
            tUsersList.forEach(user -> userList.add(itUsersService.toAICUser(user)));
        }
        updateWorkFlow(opinion, xrTaskList, nextNodeID, userList, permission);
    }

    @Override
    public void updateWorkFlow(XrOpinion opinion, XrTaskList xrTaskList, String nextNodeID, List<AICUser> userList, String permission) {
        AICUser user = SSOUtil.getUser();

        // 添加意见 TODO：后续交由opinionService处理
        if (opinion != null) {
            opinion.setHandlerId(user.getPrimaryKey());
            opinion.setHandler(user.getName());
            opinion.setTaskListId(xrTaskList.getTaskLikeId());
            opinion.setOpinionType(xrTaskList.getLinkName() == null ? "经办" : xrTaskList.getLinkName());
            opinion.setOpinionId(UUID.randomUUID().toString());
            if (opinion.getHandelDate() == null) {
                opinion.setHandelDate(LocalDate.now());
            }
            if (StringUtils.endsWith(nextNodeID, FlowConstant.LINK_TYPE_RETURN)) { //回退
                opinion.setAgree("2");
            } else if (nextNodeID.equals(FlowConstant.LINK_TYPE_EXAMINE) || nextNodeID.equals(FlowConstant.LINK_TYPE_APPROVE) || nextNodeID.equals(FlowConstant.LINK_TYPE_END)) { //通过
                opinion.setAgree("0");
            } else if (nextNodeID.equals(FlowConstant.LINK_TYPE_EXAMINE_FINISH) || nextNodeID.equals(FlowConstant.LINK_TYPE_APPROVE_FINISH) || nextNodeID.equals(FlowConstant.LINK_TYPE_NULLIFY)) { //不通过
                opinion.setAgree("1");
            }
        }

        // 回退查找人员
        if (StringUtils.endsWith(nextNodeID, FlowConstant.LINK_TYPE_RETURN)){
            XrActivity operator = iXrActivityService.findOperator(xrTaskList.getTaskLikeId(), nextNodeID.substring(0, nextNodeID.indexOf(FlowConstant.LINK_TYPE_RETURN)));
            userList = ListUtil.toList((itUsersService.getUserById(operator.getOpenId())));
        }
        String ident = StringUtils.isNotBlank(permission) ? (StringUtils.isNotBlank(xrTaskList.getNextOrgId()) ? xrTaskList.getNextOrgId() : xrTaskList.getAreaCode()) + ":" + permission : null;
        String linkName = iXrActivityService.processWorkByTemplate(xrTaskList, userList, nextNodeID, opinion, ident);
        xrTaskList.setLinkName(linkName);
        if (StringUtils.isNotEmpty(ident)) {
            if(userList.size()>0){
                AICUser signUser = userList.get(0);
                xrTaskList.setSenderUserId(signUser.getPrimaryKey());
                xrTaskList.setSendToOrgId(signUser.getOrgID());
            }
        }
        xrTaskList.setSignUserId(user.getPrimaryKey());
        xrTaskList.setSenderOrgId(user.getOrgID());
        xrTaskList.setSignTime(LocalDateTime.now());
        NodeModel nodeModel = iXrActivityService.findCurrentNode(xrTaskList.getTaskLikeId());
        if (nodeModel != null && nodeModel.isEnd()) {
            xrTaskList.setBusStatus(BaseDataConstant.BUSINESS_STATUS_END);
        }
        updateById(xrTaskList);
    }

    @Override
    public void startWorkFlowPerson(XrTaskList xrTaskList, String[] nextPerformerIds, String permission, List<PersonSpeSaveIvdDto> personList) {
        List<AICUser> userList = new ArrayList<>();
        if (nextPerformerIds.length > 0) {
            List<TUsers> tUsersList = itUsersService.listByUserIds(nextPerformerIds);
            tUsersList.forEach(user -> userList.add(itUsersService.toAICUser(user)));
        }
        if (StringUtils.isBlank(xrTaskList.getApplyOrgId())) {
            throw new BusinessException("业务逻辑错误，发起机构为空");
        }
        String ident = StringUtils.isNotBlank(permission) ? xrTaskList.getApplyOrgId() + ":" + permission : null;
        HandleWorkFlowUtil.createXrTaskList(xrTaskList, SSOUtil.getUser());
        xrTaskList.setTaskLikeId(IdUtil.randomUUID());
        String linkName = iXrActivityService.startWorkFlowByTemplate(xrTaskList, userList, ident);
        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime now = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = now.format(formatter);  // 将日期格式化为字符串
        xrTaskList.setAcceptNo("7"+ formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));

        xrTaskList.setLinkName(linkName);
        save(xrTaskList);
        iXrTaskAnnexService.saveTaskAnnexByPersonListOnTaskId(personList, xrTaskList.getTaskLikeId());
    }

    @Override
//    @DSTransactional
    public String startWorkFlow(XrTaskList xrTaskList, String[] nextPerformerIds, String permission,
                                List<String> pripIdList, AICUser aicUser) {
        List<AICUser> userList = new ArrayList<>();
        if (nextPerformerIds.length > 0) {
            List<TUsers> tUsersList = itUsersService.listByUserIds(nextPerformerIds);
            tUsersList.forEach(user -> userList.add(itUsersService.toAICUser(user)));
        }
        return startWorkFlow(xrTaskList, userList, permission, pripIdList, aicUser);
    }

    @Override
    public String startWorkFlow(XrTaskList xrTaskList, List<AICUser> userList, String permission,
                                List<String> pripIdList, AICUser user) {
        if (StringUtils.isBlank(xrTaskList.getApplyOrgId())) {
            throw new BusinessException("业务逻辑错误，发起机构为空");
        }
        String ident = StringUtils.isNotBlank(permission) ? xrTaskList.getApplyOrgId() + ":" + permission : null;
        HandleWorkFlowUtil.createXrTaskList(xrTaskList, user);
        xrTaskList.setTaskLikeId(IdUtil.randomUUID());
        String linkName = iXrActivityService.startWorkFlowByTemplate(xrTaskList, userList, ident);
//        xrTaskList.setAcceptNo(uuidUtil.getCurAcceptNo());

        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime now = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = now.format(formatter);  // 将日期格式化为字符串
        xrTaskList.setAcceptNo("7"+ formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));

        xrTaskList.setLinkName(linkName);
        save(xrTaskList);
        iXrTaskAnnexService.saveTaskAnnexByPripIdListOnTaskId(pripIdList, xrTaskList.getTaskLikeId());
        return null;
    }

    @Override
    @Transactional
    public String startWorkFlow(XrTaskList xrTaskList, String[] nextPerformerIds, String permission, List<String> pripIdList) {
        List<AICUser> userList = new ArrayList<>();
        if (nextPerformerIds.length > 0) {
            List<TUsers> tUsersList = itUsersService.listByUserIds(nextPerformerIds);
            tUsersList.forEach(user -> userList.add(itUsersService.toAICUser(user)));
        }
        return startWorkFlow(xrTaskList, userList, permission, pripIdList);
    }

    @Override
    public String startWorkFlow(XrTaskList xrTaskList, List<AICUser> userList, String permission, List<String> pripIdList) {
        if (StringUtils.isBlank(xrTaskList.getApplyOrgId())) {
            throw new BusinessException("业务逻辑错误，发起机构为空");
        }
        AICUser currentAICUser = SSOUtil.getUser();
        String ident = StringUtils.isNotBlank(permission) ? xrTaskList.getApplyOrgId() + ":" + permission : null;
        HandleWorkFlowUtil.createXrTaskList(xrTaskList, currentAICUser);
        xrTaskList.setTaskLikeId(IdUtil.randomUUID());
        String linkName = iXrActivityService.startWorkFlowByTemplate(xrTaskList, userList, ident);
//        xrTaskList.setAcceptNo(uuidUtil.getCurAcceptNo());

        //因xr_id_maker容易被锁，临时用新的生成规则生成受理编号
        LocalDateTime now = LocalDateTime.now();  // 获取当前日期和时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");  // 定义格式化模式
        String formattedDate = now.format(formatter);  // 将日期格式化为字符串
        xrTaskList.setAcceptNo("7"+ formattedDate + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8));

        xrTaskList.setLinkName(linkName);
        save(xrTaskList);
        iXrTaskAnnexService.saveTaskAnnexByPripIdListOnTaskId(pripIdList, xrTaskList.getTaskLikeId());
        return null;
    }
}
