package com.storlead.sales.service.impl.systemrule;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.systemrule.ApproveEntity;
import com.storlead.sales.pojo.entity.systemrule.ApproveLogEntity;
import com.storlead.sales.pojo.entity.systemrule.ApproveNodeEntity;
import com.storlead.sales.mapper.systemrule.ApproveMapper;
import com.storlead.sales.service.systemrule.ApproveNodeService;
import com.storlead.sales.service.systemrule.ApproveService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.system.pojo.entity.SystemConfigItemEntity;
import com.storlead.system.service.SystemConfigItemService;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-07-26
 */
@Service
public class ApproveServiceImpl extends MyBaseServiceImpl<ApproveMapper, ApproveEntity> implements ApproveService {

    @Resource
    private SystemConfigItemService systemConfigItemService;
    @Resource
    private ApproveNodeService approveNodeService;
    @Resource
    private IUserService userService;
    @Resource
    private ApproveLogServiceImpl approveLogService;
    @Resource
    private ApproveMapper approveMapper;
    @Override
    public Result submitApprove(ApproveEntity approve) {

        if (null == approve || approve.getDataYear() == null || approve.getDataMonth() == null) {
            return Result.error("参数传入错误");
        }

        if (approve.getApproveType() == null || approve.getApproveType().equals("")) {
            return Result.error("未传入审批类型");
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();

        //查询已有审批流
        LambdaQueryWrapper<ApproveNodeEntity> approveNodeWrapper = new LambdaQueryWrapper<>();
        approveNodeWrapper.eq(ApproveNodeEntity::getApproveType,approve.getApproveType());
        //如果有分公司id，通过分公司id审批
        if (ObjectUtils.isNotEmpty(approve.getSubCompanyId())){
            approveNodeWrapper.eq(ApproveNodeEntity::getSubCompanyId,approve.getSubCompanyId());
        }
        approveNodeWrapper.orderByAsc(ApproveNodeEntity::getNodeSort);
        List<ApproveNodeEntity> approveNodeList = approveNodeService.list(approveNodeWrapper);
        if (CollectionUtils.isEmpty(approveNodeList)){
            return Result.error("审批流不存在，请先创建");
        }
        //获取第一个审批节点
        ApproveNodeEntity firstApproveNode = approveNodeList.get(0);

        //1、查询是否已经提交并且是未审核状态
        LambdaQueryWrapper<ApproveEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(ApproveEntity::getDataYear, approve.getDataYear());
        queryWrapper.eq(ApproveEntity::getDataMonth, approve.getDataMonth());
        queryWrapper.eq(ApproveEntity::getApproveType, approve.getApproveType());
        //如果有分公司id，通过分公司id审批
        if (ObjectUtils.isNotEmpty(approve.getSubCompanyId())){
            queryWrapper.eq(ApproveEntity::getSubCompanyId,approve.getSubCompanyId());
        }
        ApproveEntity approveNew = this.getOne(queryWrapper);

        //获取系统配置数据
        Map<String, SystemConfigItemEntity> systemConfigItemMap = systemConfigItemService.getSystemConfigItemMap();

//        String msgTitle = ApproveType.getReturnNameByType(approve.getApproveType())+"审核通知";
//        String returnUrl =  ApproveType.getReturnUrlByType(approve.getApproveType());
//        String noticeMsg =approve.getDataYear() + "-" + approve.getDataMonth() + "月份的"+firstApproveNode.getApproveMessage();


        //查询第一个审核人
        UserEntity currentApproveUser = userService.getById(firstApproveNode.getApproveUserId());
        if (ObjectUtils.isEmpty(approveNew)) {
            approve.setCreateBy(loginUser.getId());
            approve.setCreateTime(new Date());
            approve.setUpdateBy(loginUser.getId());
            approve.setUpdateTime(new Date());
            approve.setApproveStatus("0");
            approve.setCurrentNode(firstApproveNode.getNodeSort().toString());
            approve.setApproveUserName(currentApproveUser.getRealName());
            approve.setApproveUserId(currentApproveUser.getId());
            if (!this.save(approve)) {
                return Result.error("提交失败");
            }
        } else if (approveNew.getApproveStatus().equals("2")) {
            approve.setId(approveNew.getId());
            //更新原来审核不通过记录
            approveNew.setCreateBy(loginUser.getId());
            approveNew.setCreateTime(new Date());
            approve.setUpdateBy(loginUser.getId());
            approve.setUpdateTime(new Date());
            approve.setApproveStatus("0");
            approveNew.setApproveStatus("0");
            approveNew.setCurrentNode(firstApproveNode.getNodeSort().toString());
            approveNew.setApproveUserId(currentApproveUser.getId());
            approveNew.setApproveUserName(currentApproveUser.getRealName());
            if (!this.updateById(approveNew)) {
                return Result.error("提交失败");
            }
        } else{
            return Result.error("当前月份已提交审核，无需再次提交");
        }

        //消息接收人列表
        List<Long> sendUserIds = Arrays.stream(firstApproveNode.getSendUserids().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<UserEntity> userList = userService.listByIds(sendUserIds);
//        String url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + returnUrl
//                +"?dataYear="+approve.getDataYear()+"&dataMonth="+approve.getDataMonth()+"&approveStatus=0&approveId="+approve.getId()+"&subCompanyId="+approve.getSubCompanyId()+"&isDetail=false&reviewTag=1";

//        log.info("通知跳转url为{}", url);
        ApproveLogEntity approveLog = new ApproveLogEntity();
        approveLog.setApproveContent("提交审核");
        approveLog.setApproveStatus("4");
        approveLog.setApproveUserId(loginUser.getId());
        approveLog.setApproveUserName(loginUser.getRealName());
        approveLog.setApproveTime(LocalDateTime.now());
        approveLog.setApproveId(approve.getId());

        approveLogService.save(approveLog);
        approve.setApproveStatus("1");
        approve.setApproveContent("系统自动审批");
        Result nextResult  = approveApprove(approve);

        if (nextResult.getCode()==1000){
            return Result.result("提交审核成功");
        }

//        corpWeChatService.sendTextCardMsg(msgTitle, noticeMsg, url, Set.of(currentApproveUser), null);
//        corpWeChatService.sendTextCardMsg(msgTitle, noticeMsg, toFinalUrl(url), userList, null);
        return Result.result("提交审核成功");
    }

    //薪资调整添加审批逻辑
    private Result submitApproveEntityOfChangeSalary(ApproveEntity approve) {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        //查询已有审批流
        LambdaQueryWrapper<ApproveNodeEntity> approveNodeWrapper = new LambdaQueryWrapper<>();
        approveNodeWrapper.eq(ApproveNodeEntity::getApproveType,approve.getApproveType());
        //查询员工分公司id，通过分公司id审批

        approveNodeWrapper.orderByAsc(ApproveNodeEntity::getNodeSort);
        approveNodeWrapper.last("limit 1");
        ApproveNodeEntity firstApproveNode = approveNodeService.getOne(approveNodeWrapper);
        if (ObjectUtils.isEmpty(firstApproveNode)){
            return Result.error("审批流不存在，请先创建");
        }

        //查询是否有审批中或者已审核通过的审批流
//        LambdaQueryWrapper<ApproveEntity> inWrapper = new LambdaQueryWrapper<>();
//        inWrapper.eq(ApproveEntity::getDataYear,approve.getDataYear());
//        inWrapper.eq(ApproveEntity::getDataMonth,approve.getDataMonth());
//        inWrapper.eq(ApproveEntity::getApproveType,ApproveType.CHANGE_SALARY_TYPE.getType());
//        inWrapper.in(ApproveEntity::getApproveStatus,Arrays.asList("0","1"));
//
//        String sql = " CONCAT(',',sub_company_id,',') regexp REPLACE(',',',',',"+ StringUtils.join(Arrays.asList(approve.getSubCompanyId().split(",")),",|,")+",')";
//        inWrapper.apply(sql);
//        List<ApproveEntity> hasApproveEntityList = this.list(inWrapper);
//        if (!CollectionUtils.isEmpty(ApproveEntityList)) {
//            return Result.error("存在审批中/审核通过的用户，无需再次提交");
//        }
        //查询第一个审核人
        UserEntity currentApproveUser = userService.getById(firstApproveNode.getApproveUserId());

        //获取系统配置数据
        Map<String,SystemConfigItemEntity> systemConfigItemMap = systemConfigItemService.getSystemConfigItemMap();

//        String msgTitle = ApproveType.getReturnNameByType(approve.getApproveType())+"审核通知";
//        String returnUrl =  ApproveType.getReturnUrlByType(approve.getApproveType());
//        String noticeMsg =approve.getDataYear() + "-" + approve.getDataMonth() + "月份的"+firstApproveNode.getApproveMessage();

        //查询是否存在审批不通过的数据
        LambdaQueryWrapper<ApproveEntity> noWrapper = new LambdaQueryWrapper<>();
        noWrapper.eq(ApproveEntity::getDataYear,approve.getDataYear());
        noWrapper.eq(ApproveEntity::getDataMonth,approve.getDataMonth());
        noWrapper.eq(ApproveEntity::getApproveStatus,"2");
        noWrapper.eq(ApproveEntity::getSubCompanyId,approve.getSubCompanyId());
        noWrapper.last("limit 1");
        ApproveEntity noApproveEntity = this.getOne(noWrapper);
        String url = "";
        if (ObjectUtils.isNotEmpty(noApproveEntity)){
            //更新原来审核不通过记录
            noApproveEntity.setSubCompanyId(approve.getSubCompanyId());
            noApproveEntity.setCreateBy(loginUser.getId());
            noApproveEntity.setCreateTime(new Date());
            noApproveEntity.setUpdateBy(loginUser.getId());
            noApproveEntity.setUpdateTime(new Date());
            noApproveEntity.setApproveStatus("0");
            noApproveEntity.setCurrentNode(firstApproveNode.getNodeSort().toString());
            noApproveEntity.setApproveUserId(currentApproveUser.getId());
            noApproveEntity.setApproveUserName(currentApproveUser.getRealName());
            if (!this.updateById(noApproveEntity)) {
                return Result.error("提交失败");
            }
            approve.setId(noApproveEntity.getId());
//            url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + returnUrl
//                    +"?dataYear="+ noApproveEntity.getDataYear()+"&dataMonth="+ ApproveEntity.getDataMonth()+"&approveStatus=0&approveId="+ ApproveEntity.getId()+"&subCompanyId="+ ApproveEntity.getSubCompanyId()+"&isDetail=false&reviewTag=1";

        }else {
            noApproveEntity = new ApproveEntity();
            noApproveEntity.setApproveType(approve.getApproveType());
            noApproveEntity.setSubCompanyId(approve.getSubCompanyId());
            noApproveEntity.setDataYear(approve.getDataYear());
            noApproveEntity.setDataMonth(approve.getDataMonth());
            noApproveEntity.setCreateBy(loginUser.getId());
            noApproveEntity.setCreateTime(new Date());
            noApproveEntity.setUpdateBy(loginUser.getId());
            noApproveEntity.setUpdateTime(new Date());
            noApproveEntity.setApproveStatus("0");
            noApproveEntity.setCurrentNode(firstApproveNode.getNodeSort().toString());
            noApproveEntity.setApproveUserId(currentApproveUser.getId());
            noApproveEntity.setApproveUserName(currentApproveUser.getRealName());
            if (!this.save(noApproveEntity)) {
                return Result.error("提交失败");
            }
            approve.setId(noApproveEntity.getId());
//            url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + returnUrl
//                    +"?dataYear="+ noApproveEntity.getDataYear()+"&dataMonth="+ ApproveEntity.getDataMonth()+"&approveStatus=0&approveId="+ ApproveEntity.getId()+"&subCompanyId="+ ApproveEntity.getSubCompanyId()+"&isDetail=false&reviewTag=1";
        }


        System.out.println("url="+url);
        ApproveLogEntity approveLog = new ApproveLogEntity();
        approveLog.setApproveContent("提交审核");
        approveLog.setApproveStatus("4");
        approveLog.setApproveUserId(loginUser.getId());
        approveLog.setApproveUserName(loginUser.getRealName());
        approveLog.setApproveTime(LocalDateTime.now());
        approveLog.setApproveId(approve.getId());

        approveLogService.save(approveLog);
        noApproveEntity.setApproveStatus("1");
        noApproveEntity.setApproveContent("系统自动审批");
        Result nextResult  = approveApprove(noApproveEntity);
        if (nextResult.getCode()==1000){
            return Result.result("提交审核成功");
        }
        //消息接收人列表
        List<Long> sendUserIds = Arrays.stream(firstApproveNode.getSendUserids().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        List<UserEntity> userList = userService.listByIds(sendUserIds);
//        corpWeChatService.sendTextCardMsg(msgTitle, noticeMsg, toFinalUrl(url), userList, null);
        return Result.result("提交审核成功");
    }

    @Override
    public Result approveApprove(ApproveEntity approve) {
        return autoRecursionApprove(approve,false);
    }

    public Result autoRecursionApprove(ApproveEntity approve,boolean auto) {
        if (approve == null || approve.getId() == null) {
            return Result.error("参数不正确");
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        ApproveEntity approveNew = this.getById(approve.getId());

        if (approveNew == null) {
            return Result.error("审核记录不存在！");
        }
        if (!approveNew.getApproveUserId().equals(loginUser.getId())){
            return Result.error("当前用户与审批人不一致！");
        }

        //获取系统配置数据
        ApproveLogEntity approveLog = new ApproveLogEntity();
        if (auto) {
            approveLog.setApproveContent("系统自动审批");
        } else {
            approveLog.setApproveContent(approve.getApproveContent());
        }
        approveLog.setApproveStatus(approve.getApproveStatus());
        approveLog.setApproveUserId(loginUser.getId());
        approveLog.setApproveUserName(loginUser.getRealName());
        approveLog.setApproveTime(LocalDateTime.now());
        approveLog.setApproveId(approve.getId());

        //查询已有审批流
        LambdaQueryWrapper<ApproveNodeEntity> approveNodeWrapper = new LambdaQueryWrapper<>();
        approveNodeWrapper.eq(ApproveNodeEntity::getApproveType,approveNew.getApproveType());
        approveNodeWrapper.ge(ApproveNodeEntity::getNodeSort,approveNew.getCurrentNode());
        approveNodeWrapper.orderByAsc(ApproveNodeEntity::getNodeSort);
        List<ApproveNodeEntity> approveNodeList = approveNodeService.list(approveNodeWrapper);
        if (CollectionUtils.isEmpty(approveNodeList)){
            return Result.error("审批流异常，请联系管理员");
        }

        Map<String,SystemConfigItemEntity> systemConfigItemMap = systemConfigItemService.getSystemConfigItemMap();

        //审批不通过
        if (approve.getApproveStatus().equals("2")){
            approve.setUpdateBy(loginUser.getId());
            approve.setUpdateTime(new Date());
            if (this.updateById(approve) && approveLogService.save(approveLog)) {
//                UserEntity createUser = userService.getById(approveNew.getCreateBy());
//                String url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + ApproveType.getReturnUrlByType(approveNew.getApproveType())
//                        +"?dataYear="+approveNew.getDataYear()+"&dataMonth="+approveNew.getDataMonth()+"&approveStatus=2&approveId="+approveNew.getId()+"&subCompanyId="+approveNew.getSubCompanyId()+"&isDetail=false&reviewTag=1";
//                corpWeChatService.sendTextCardMsg(ApproveType.getReturnNameByType(approveNew.getApproveType())+"审核通知", approveNew.getDataYear() + "-" + approveNew.getDataMonth() + "月份"+approveNodeList.get(0).getErrorMessage(),
//                        toFinalUrl(url), Set.of(createUser), null);
            } else {
                return Result.error("审核结果提交失败，请重新审核！");
            }
        }

        //审核成功
        if (approve.getApproveStatus().equals("1")) {
            //如果是最后一个审核节点
            if (approveNodeList.size()==1) {
                approveNew.setUpdateBy(loginUser.getId());
                approveNew.setUpdateTime(new Date());
                approveNew.setApproveStatus("1");
                boolean a = this.updateById(approveNew);
                boolean b = approveLogService.save(approveLog);
                //工资条审核通过之后调取该方法
                //发送审核成功消息
                if (a && b) {
//                    User createUser = userService.getById(approveNew.getCreateBy());
//                    String url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + ApproveType.getReturnUrlByType(approveNew.getApproveType())
//                            +"?dataYear="+approveNew.getDataYear()+"&dataMonth="+approveNew.getDataMonth()+"&approveStatus=1&approveId="+approveNew.getId()+"&subCompanyId="+approveNew.getSubCompanyId()+"&isDetail=false&reviewTag=1";
//                    corpWeChatService.sendTextCardMsg(ApproveType.getReturnNameByType(approveNew.getApproveType())+"审核通知", approveNew.getDataYear() + "-" + approveNew.getDataMonth() + "月份的"+approveNodeList.get(0).getSuccessMessage(),
//                            toFinalUrl(url), Set.of(createUser), null);
                } else {
                    return Result.error("审核结果提交失败，请重新审核！");
                }
            }
            //还有后续审核节点
            if (approveNodeList.size() > 1) {
                ApproveNodeEntity nextApproveNode = approveNodeList.get(1);
                UserEntity approveUser = userService.getById(nextApproveNode.getApproveUserId());

                approveNew.setCurrentNode(approveNodeList.get(1).getNodeSort().toString());
                approveNew.setApproveUserId(approveUser.getId());
                approveNew.setApproveUserName(approveUser.getRealName());
                approveNew.setUpdateBy(loginUser.getId());
                approveNew.setUpdateTime(new Date());

                boolean a = this.updateById(approveNew);
                boolean b = approveLogService.save(approveLog);
                if (a && b) {
                    if (nextApproveNode.getApproveUserId().equals(loginUser.getId())) {
                        autoRecursionApprove(approve,true);
                    } else {
                        List<Long> sendUserIds = Arrays.stream(nextApproveNode.getSendUserids().split(","))
                                .map(Long::parseLong)
                                .collect(Collectors.toList());
                        List<UserEntity> userList = userService.listByIds(sendUserIds);
//                        String url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + ApproveType.getReturnUrlByType(approveNew.getApproveType())
//                                +"?dataYear="+approveNew.getDataYear()+"&dataMonth="+approveNew.getDataMonth()+"&approveStatus=0&approveId="+approveNew.getId()+"&subCompanyId="+approveNew.getSubCompanyId()+"&isDetail=false&reviewTag=1";
//                        corpWeChatService.sendTextCardMsg(ApproveType.getReturnNameByType(approveNew.getApproveType())+"审核通知", approveNew.getDataYear() + "-" + approveNew.getDataMonth() + "月份的"+nextApproveNode.getApproveMessage(),
//                                toFinalUrl(url), userList, null);
                    }
                } else {
                    return Result.error("审核结果提交失败，请重新审核！");
                }
            }
        }
        return Result.result("审核成功");
    }

    /***
     * @Description: 审批驳回/回撤逻辑
     * @Param: approve
     * @return:
     * @Author: YPZ
     * @Date: 2023/11/30 18:02
     */
    @Override
    public Result approveApproveBak( ApproveEntity approve) {
        if (ObjectUtils.isEmpty(approve.getId())) {
            return Result.error("参数不正确");
        }
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        ApproveEntity approveNew = this.getById(approve.getId());

        if (ObjectUtils.isEmpty(approveNew)) {
            return Result.error("审核记录不存在！");
        }
        if (!approveNew.getApproveStatus().equals("1")){
            return Result.error("只能重新审批已通过的数据！");
        }
        //查看工资条是否已提交审批
        //1、查询是否已经提交并且是未审核状态
//        LambdaQueryWrapper<ApproveEntity> hasQueryWrapper = new LambdaQueryWrapper();
//        hasQueryWrapper.eq(ApproveEntity::getDataYear, approveNew.getDataYear());
//        hasQueryWrapper.eq(ApproveEntity::getDataMonth, approveNew.getDataMonth());
//        hasQueryWrapper.eq(ApproveEntity::getApproveType, ApproveType.SALARY_TYPE);
//        hasQueryWrapper.in(ApproveEntity::getApproveStatus,Arrays.asList("0","1"));
//        //如果有分公司id，通过分公司id审批
//        if (ObjectUtils.isNotEmpty(approveNew.getSubCompanyId())&& !approveNew.getApproveType().equals(ApproveType.CHANGE_SALARY_TYPE.getType())){
//            hasQueryWrapper.eq(ApproveEntity::getSubCompanyId,approveNew.getSubCompanyId());
//        }
//        ApproveEntity hasApproveEntity= approveService.getOne(hasQueryWrapper);
//        if (ObjectUtils.isNotEmpty(ApproveEntity)){
//            return Result.error("存在当月已提交审批的工资条！");
//        }

        approveNew.setApproveStatus("2");
        approveNew.setUpdateBy(loginUser.getId());
        approveNew.setUpdateTime(new Date());

        boolean isOk = this.updateById(approveNew);
        if (!isOk){
            return Result.error("审批流撤回失败");
        }
//        Map<String,SystemConfigItemEntity> systemConfigItemMap = systemConfigItemService.getSystemConfigItemMap();
//        String url = systemConfigItemMap.get("wechat_base_url").getItemFormatValue() + ApproveType.getReturnUrlByType(approveNew.getApproveType())
//                +"?dataYear="+approveNew.getDataYear()+"&dataMonth="+approveNew.getDataMonth()+"&approveStatus=2&approveId="+approveNew.getId()+"&subCompanyId="+approveNew.getSubCompanyId()+"&isDetail=false&reviewTag=1";
//        UserEntity createUser = userService.getById(approveNew.getCreateBy());
//        corpWeChatService.sendTextCardMsg(ApproveType.getReturnNameByType(approveNew.getApproveType()) +"审核通知", approveNew.getDataYear() + "-" + approveNew.getDataMonth() + "月份的审核已撤回",
//                toFinalUrl(url), Arrays.asList(createUser), null);
        ApproveLogEntity approveLog = new ApproveLogEntity();
        approveLog.setApproveContent(approve.getApproveContent());
        approveLog.setApproveStatus("2");
        approveLog.setApproveUserId(loginUser.getId());
        approveLog.setApproveUserName(loginUser.getRealName());
        approveLog.setApproveTime(LocalDateTime.now());
        approveLog.setApproveId(approveNew.getId());
        boolean logIsOk = approveLogService.save(approveLog);
        if (!logIsOk){
            return Result.error("审批流撤回日志写入失败");
        }

        return Result.result("撤回成功");
    }


//    @Override
//    public Result listApproveByUserId(ApproveEntity approve) {
//
//        LoginUser loginUser = LoginUserUtil.getLoginUser();
//        Page<ApproveEntity> page = new Page<>();
//        if (approve.getPageIndex() != null && approve.getPageSize() != null) {
//            approve.setPageIndex((approve.getPageIndex() - 1) * approve.getPageSize());
//        }
//        page.setRecords(approveMapper.listApprovePaySlipByUserId(approve, loginUser.getId()));
//        page.setTotal(approveMapper.listApprovePaySlipByUserIdCount(approve, loginUser.getId()));
//        return Result.result(page);
//    }
//
//    @Override
//    public List<ApproveEntity> listApproveByUserId(ApproveEntity approve,Long userId){
//        return approveMapper.listApprovePaySlipByUserId(approve, userId);
//    }

    @Override
    public String selectApproveStatus(ResourceTypeEnum approveType, Integer dataYear, Integer dataMonth) {
        LambdaQueryWrapper<ApproveEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveEntity::getApproveType,approveType.code);
        wrapper.eq(ApproveEntity::getDataYear,dataYear);
        wrapper.eq(ApproveEntity::getDataMonth,dataMonth);
        wrapper.last("limit 1");
        ApproveEntity approve = this.getOne(wrapper);
        if (ObjectUtils.isNotEmpty(approve)){
            return approve.getApproveStatus();
        }
        return null;
    }

    @Override
    public boolean isApprove(int year, int month) {
        return isApprove(year, month,null,"");
    }

    @Override
    public boolean isApprove(int year, int month, ResourceTypeEnum approveType) {
        return isApprove(year, month,null,approveType);
    }

    @Override
    public boolean isApprove(int year, int month, Long subCompanyId, ResourceTypeEnum approveType) {
        return isApprove(year, month,subCompanyId,approveType.code);
    }

    @Override
    public boolean isApprove(int year, int month, Long subCompanyId, String approveType) {
        LambdaQueryWrapper<ApproveEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveEntity::getDataYear, year);
        wrapper.eq(ApproveEntity::getDataMonth, month);
        wrapper.eq(!ObjectUtils.isEmpty(subCompanyId),ApproveEntity::getSubCompanyId,subCompanyId);
        if (StrUtil.isNotBlank(approveType)){
            wrapper.eq(ApproveEntity::getApproveType, approveType);
        }
        wrapper.in(ApproveEntity::getApproveStatus, Arrays.asList('0','1'));
        return approveMapper.selectCount(wrapper) > 0;
    }


//    @Override
//    public void approveTest() {
//        User user = userService.getById(400);
////        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww5323bd8ab4394132&redirect_uri=https://salary.storlead.com?&response_type=code&scope=snsapi_base&agentid=1000012&state=/management/SetIncomeDetail?dataYear=2023&dataMonth=11&approveStatus=0&approveId=38&subCompanyId=2&isDetail=false#wechat_redirect";
////        String url = "https%3A%2F%2Fsalary.test.storlead.com%2Fmanagement%2FSetIncomeDetail%3FdataYear%3D2023%26dataMonth%3D11%26approveStatus%3D0%26approveId%3D38%26subCompanyId%3D2%26isDetail%3Dfalse";
//        String url = "https://salary.test.storlead.com/management/SetIncomeDetail?dataYear=2023&dataMonth=11&approveStatus=0&approveId=38&subCompanyId=2&isDetail=false";
//        corpWeChatService.sendTextCardMsg("审核通知", "审核测试",
//                toFinalUrl(url), Arrays.asList(user), null);
//    }

    @Override
    public boolean isChangeSalaryApprove(int year, int month, String userId) {

        //查询是否有审批中或者已审核通过的审批流
        LambdaQueryWrapper<ApproveEntity> inWrapper = new LambdaQueryWrapper<>();
        inWrapper.eq(ApproveEntity::getDataYear,year);
        inWrapper.eq(ApproveEntity::getDataMonth,month);
        inWrapper.in(ApproveEntity::getApproveStatus,Arrays.asList("0","1"));
        inWrapper.apply("find_in_set("+userId+",sub_company_id)");
        Integer count = this.count(inWrapper);
        if (count>0) {
            return true;
        }
        return false;
    }


    /***
     * @Description: 通过员工id查询当月工资调整是否审核通过
     * @Param:
     * @return: true,审核通过
     * @Author: YPZ
     * @Date: 2023/12/1 9:06
     */
    @Override
    public boolean userChangeHasApproved(int year, int month, Long userId) {

        //通过员工id查询当月工资调整是否审核通过
        LambdaQueryWrapper<ApproveEntity> inWrapper = new LambdaQueryWrapper<>();
        inWrapper.eq(ApproveEntity::getDataYear,year);
        inWrapper.eq(ApproveEntity::getDataMonth,month);
        inWrapper.eq(ApproveEntity::getApproveStatus,"1");
        inWrapper.apply("find_in_set("+userId.toString()+",sub_company_id)");
        Integer count = count(inWrapper);
        if (count > 0){
            return true;
        }
        return false;
    }

    /***
     * @Description: 转换URL
     * @Param:
     * @return:
     * @Author: YPZ
     * @Date: 2023/11/29 10:13
     */
//    private String toFinalUrl(String url){
//        String finalUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_base&agentid={agentid}&state=msg#wechat_redirect";
//        finalUrl = finalUrl.replace("{appid}",appid);
//        finalUrl = finalUrl.replace("{agentid}",agentid);
//        try {
//            finalUrl = finalUrl.replace("{redirect_uri}", URLEncoder.encode(url,"UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            throw new RuntimeException(e);
//        }
//        return finalUrl;
//    }
}
