package com.ruoyi.project.production.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.page.PageDomain;
import com.ruoyi.framework.web.page.TableSupport;
import com.ruoyi.project.production.controller.vo.SaiApplyQueryVO;
import com.ruoyi.project.production.domain.TSaiApply;
import com.ruoyi.project.production.mapper.TSaiApplyMapper;
import com.ruoyi.project.production.service.ITSaiApplyService;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.SysRole;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.mapper.SysUserRoleMapper;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * SAI开项管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-03-15
 */
@Service
public class TSaiApplyServiceImpl implements ITSaiApplyService
{
    @Resource
    private TSaiApplyMapper tSaiApplyMapper;

    @Resource
    private SysDeptMapper sysDeptMapper;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private ISysDictTypeService iSysDictTypeService;

    @Resource
    private SysUserRoleMapper userRoleMapper;

    @Resource
    private ISysUserService userService;

    protected final Logger logger = LoggerFactory.getLogger(BaseController.class);

    /**
     * 查询SAI开项管理
     *
     * @param saiApplyId SAI开项管理ID
     * @return SAI开项管理
     */
    @Override
    public TSaiApply selectTSaiApplyById(Long saiApplyId)
    {
        TSaiApply tSaiApply = tSaiApplyMapper.selectTSaiApplyById(saiApplyId);
        if (tSaiApply.getApplicant() != null) {
            tSaiApply.setApplicantName(sysUserMapper.selectUserById(Long.parseLong(tSaiApply.getApplicant())).getNickName());
        }
        return tSaiApply;
    }

    /**
     * 查询SAI开项管理列表
     *
     * @param tSaiApply SAI开项管理
     * @return SAI开项管理
     */
    @Override
    public List<TSaiApply> selectTSaiApplyList(SaiApplyQueryVO tSaiApply)
    {
//        // 当前登录用户userId
//        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
//        Long userId = loginUser.getUser().getUserId();
//
//        List<TSaiApply> result = tSaiApplyMapper.selectTSaiApplyList(tSaiApply);
//
//        List<TSaiApply> tSaiApplies = new ArrayList<>();
//
//        for (TSaiApply saiApply : result) {
//            // 待处理：当前用户为流程当前处理人（之一），申请流程未结束
//            if (tSaiApply.getTab() == 1) {
//                if (saiApply.getHandler().indexOf(userId.toString()) != -1 && saiApply.getApplyStatus() != 4 && saiApply.getApplyStatus() != 5) {
//                    tSaiApplies.add(saiApply);
//                }
//            }
//            // 我的：当前用户为登记人、评估人、整改负责人或验证人（之一）
//            else if (tSaiApply.getTab() == 2) {
//                if ((saiApply.getApplicant() != null && saiApply.getApplicant().indexOf(userId.toString()) != -1)
//                     || (saiApply.getAssessor() != null && saiApply.getAssessor().indexOf(userId.toString()) != -1)
//                     || (saiApply.getExecutor() != null && saiApply.getExecutor().indexOf(userId.toString()) != -1)
//                     || (saiApply.getInspectors() != null && saiApply.getInspectors().indexOf(userId.toString()) != -1)) {
//                    tSaiApplies.add(saiApply);
//                }
//            }
//            // 总数据
//            else if (tSaiApply.getTab() == 3) {
//                tSaiApplies.add(saiApply);
//            }
//        }

        List<TSaiApply> tSaiApplies = tSaiApplyMapper.selectTSaiApplyList(tSaiApply);

        List<SysDictData> staffUnitDict = iSysDictTypeService.selectDictDataByType("STAFF_UNIT");

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        final CountDownLatch latch = new CountDownLatch(tSaiApplies.size()); //相同线程数量的计数

        for (TSaiApply saiApply : tSaiApplies) {
            executorService.execute(() -> {
                try {
                    String applicantDept = saiApply.getApplicantDept();
                    String applicant = saiApply.getApplicant();
                    String handler = saiApply.getHandler();
                    String executor = saiApply.getExecutor();
                    if (applicantDept != null) {
                        for (SysDictData sysDictData : staffUnitDict) {
                            if (sysDictData.getDictValue().equals(applicantDept)) {
                                saiApply.setApplicantDeptName(sysDictData.getDictLabel());
                            }
                        }
                    }
                    if (applicant != null) {
                        SysUser sysUser = sysUserMapper.selectNickNameById(Long.parseLong(applicant));
                        if (sysUser!=null) {
                            String applicantName = sysUser.getNickName();
                            if (applicantName != null && !"null".equals(applicantName)) {
                                saiApply.setApplicantName(applicantName);
                            }
                        }
                    }
                    if (handler != null) {
                        if (handler.contains(",")) {
                            String[] split = handler.split(",");
                            StringBuilder handlerName = new StringBuilder();
                            for (int i = 0; i < split.length; i++) {
                                SysUser sysUser = sysUserMapper.selectNickNameById(Long.parseLong(split[i]));
                                if (sysUser!=null) {
                                    String name = sysUser.getNickName();
                                    if (name != null && !"null".equals(name)) {
                                        handlerName.append(name);
                                        if (i < split.length - 1) {
                                            handlerName.append(",");
                                        }
                                    }
                                }
                            }
                            saiApply.setHandlerName(handlerName.toString());
                        } else {
                            SysUser sysUser = sysUserMapper.selectNickNameById(Long.parseLong(handler));
                            if (sysUser!=null) {
                                String handlerName = sysUser.getNickName();
                                if (handlerName != null && !"null".equals(handlerName)) {
                                    saiApply.setHandlerName(handlerName);
                                }
                            }
                        }
                    }
                    if (executor != null) {
                        SysUser sysUser = sysUserMapper.selectNickNameById(Long.parseLong(executor));
                        if (sysUser!=null) {
                            String executorName = sysUser.getNickName();
                            if (executorName != null && !"null".equals(executorName)) {
                                saiApply.setExecutorName(executorName);
                            }
                        }
                    }
                }catch (Exception e) {
                    logger.error("e:", e);
                }finally {
                    latch.countDown(); //线程计数
                }
            });
        }
        try {
            latch.await(); //线程计数完毕后继续执行
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executorService.shutdown();

//        boolean specialRole = this.isSpecialRole();
//        if (specialRole) {  // 当前登录用户是特殊角色
//            for (TSaiApply saiApply : tSaiApplies) {
//                long applyStatus = saiApply.getApplyStatus();
//                if (Long.toString(applyStatus).equals("5")) {   // 申请状态为“已取消”的数据
//                    tSaiApplies.remove(saiApply);   // 从列表中移除
//                }
//            }
//        }

        return tSaiApplies;
    }

    /**
     * 当前登录用户是否为特殊角色（供SAI功能展示使用）
     *
     * @return 是否为特殊角色
     */
    private boolean isSpecialRole() {
        boolean isSpecialRole = false;
        LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        List<SysRole> roles = user.getRoles();
        for (SysRole role : roles) {
            Long roleId = role.getRoleId();
            if (roleId.toString().equals("23140")) {
                isSpecialRole = true;
            }
        }
        return isSpecialRole;
    }

    /**
     * 新增SAI开项管理
     *
     * @param tSaiApply SAI开项管理
     * @return 结果
     */
    @Override
    public int insertTSaiApply(TSaiApply tSaiApply)
    {
        tSaiApply.setCreateTime(DateUtils.getNowDate());
        return tSaiApplyMapper.insertTSaiApply(tSaiApply);
    }

    /**
     * 修改SAI开项管理
     *
     * @param tSaiApply SAI开项管理
     * @return 结果
     */
    @Override
    public int updateTSaiApply(TSaiApply tSaiApply)
    {
        tSaiApply.setUpdateTime(DateUtils.getNowDate());
        return tSaiApplyMapper.updateTSaiApply(tSaiApply);
    }

    /**
     * 批量删除SAI开项管理
     *
     * @param saiApplyIds 需要删除的SAI开项管理ID
     * @return 结果
     */
    @Override
    public int deleteTSaiApplyByIds(Long[] saiApplyIds)
    {
        return tSaiApplyMapper.deleteTSaiApplyByIds(saiApplyIds);
    }

    /**
     * 删除SAI开项管理信息
     *
     * @param saiApplyId SAI开项管理ID
     * @return 结果
     */
    @Override
    public int deleteTSaiApplyById(Long saiApplyId)
    {
        return tSaiApplyMapper.deleteTSaiApplyById(saiApplyId);
    }
}
