package com.ruoyi.approvalFlow.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.approvalFlow.domain.AuditItems;
import com.ruoyi.approvalFlow.domain.AuditItemsUsers;
import com.ruoyi.approvalFlow.domain.AuditPathsLevels;
import com.ruoyi.approvalFlow.mapper.AuditItemsMapper;
import com.ruoyi.approvalFlow.mapper.AuditItemsUsersMapper;
import com.ruoyi.approvalFlow.mapper.AuditPathsLevelsMapper;
import com.ruoyi.approvalFlow.service.IAuditItemsService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 审批流任务明细Service业务层处理
 *
 * @author ruoyi
 * @date 2021-01-21
 */
@Service
public class AuditItemsServiceImpl implements IAuditItemsService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AuditItemsMapper auditItemsMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private AuditItemsUsersMapper auditItemsUsersMapper;

    @Autowired
    private AuditPathsLevelsMapper auditPathsLevelsMapper;

    /**
     * 查询审批流任务明细
     *
     * @param id 审批流任务明细ID
     * @return 审批流任务明细
     */
    @Override
    public AuditItems selectAuditItemsById(Long id) {
        return auditItemsMapper.selectAuditItemsById(id);
    }

    /**
     * 查询审批流任务明细列表
     *
     * @param auditItems 审批流任务明细
     * @return 审批流任务明细
     */
    @Override
    public List<AuditItems> selectAuditItemsList(AuditItems auditItems) {
        return auditItemsMapper.selectAuditItemsList(auditItems);
    }

    /**
     * 生成审批流
     *
     * @param auditItems 第一级审批
     * @return 结果
     */
    @Transactional
    public AjaxResult createApprovalFlow(AuditItems auditItems) {
        List<AuditPathsLevels> auditPathsLevelsList = auditPathsLevelsMapper.queryAuditLevels(auditItems);
        if (auditPathsLevelsList.size() <= 0) {
            return AjaxResult.error("未找到审批流, 请确认");
        }
        auditItemsMapper.insertAuditItems(auditItems);
        int num = 0;
        for (AuditPathsLevels levels : auditPathsLevelsList) {
            num++;
            JSONArray jsonArray = JSONArray.parseArray(levels.getAuditUserId());
            List<Long> userIdList = JSONObject.parseArray(jsonArray.toJSONString(), Long.class);
            AuditItems auditItem = new AuditItems();
            auditItem.setBillNo(auditItems.getBillNo());
            auditItem.setActId(auditItems.getActId());
            auditItem.setLevelId(levels.getLevelId());
            auditItem.setTimes(auditItems.getTimes());
            auditItem.setBillId(auditItems.getBillId());
            auditItem.setRefno1(auditItems.getRefno1());
            auditItem.setRefno2(auditItems.getRefno2());
            auditItem.setRefno3(auditItems.getRefno3());
            auditItem.setFidStatus(auditItems.getFidStatus());
            auditItem.setIffinalItem(levels.getIffinalItem());
            auditItem.setSendUserId(auditItems.getSendUserId());
            auditItem.setSendName(auditItems.getSendName());
            auditItem.setSendTime(new Date());
            if (Objects.equals(num, 1)) {
                auditItem.setAuditStatus("S");
            } else {
                auditItem.setAuditStatus("N");
            }
            if ("F".equals(levels.getIffixAuditUser())) {
                long userId = 0L;
                boolean reviewer = false;
                for (Long usId : userIdList) {
                    List<SysUser> userList = sysUserRoleMapper.selectUserRoleByRoleId(usId);
                    if (userList.size() != 0) {
                        reviewer = true;
                        for (SysUser use : userList) {
                            if (Objects.equals(num, 1)) {
                                auditItem.setAuditUserId(use.getUserId());
                            }
                            int addAuditItem = auditItemsMapper.insertAuditItems(auditItem);
                            if (addAuditItem <= 0) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.error("生成审批流明细失败，请联系管理员");
                            }
                            AuditItemsUsers auditItemsUsers = createAuditItemsUsers(num, use.getUserId(), auditItem);
                            int addAuditUser = auditItemsUsersMapper.insertAuditItemsUsers(auditItemsUsers);
                            if (addAuditUser <= 0) {
                                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.error("生成审批流明细用户失败，请联系管理员");
                            }
                        }
                    }
                }
                if (!reviewer) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("审批流第" + num + "级所选角色中没有用户");
                }
            } else {
                if(userIdList.size() ==0){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("生成审批流明细失败，请联系管理员添加审批人员");
                }
                auditItem.setAuditUserId(userIdList.get(0));
                int addAuditItem = auditItemsMapper.insertAuditItems(auditItem);
                if (addAuditItem <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("生成审批流明细失败，请联系管理员");
                }
                for (Long usId : userIdList) {
                    AuditItemsUsers auditItemsUsers = createAuditItemsUsers(num, usId, auditItem);
                    int addAuditUser = auditItemsUsersMapper.insertAuditItemsUsers(auditItemsUsers);
                    if (addAuditUser <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("生成审批流明细用户失败，请联系管理员");
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    public AuditItemsUsers createAuditItemsUsers(int num, long userId, AuditItems auditItem) {
        AuditItemsUsers auditItemsUsers = new AuditItemsUsers();
        auditItemsUsers.setUserId(userId);
        auditItemsUsers.setPid(auditItem.getId());
        auditItemsUsers.setTimes(auditItem.getTimes());
        auditItemsUsers.setActId(auditItem.getActId());
        auditItemsUsers.setBillNo(auditItem.getBillNo());
        auditItemsUsers.setFidStatus(auditItem.getFidStatus());
        if (Objects.equals(num, 1)) {
            auditItemsUsers.setAuditStatus("S");
        } else {
            auditItemsUsers.setAuditStatus("N");
        }
        return auditItemsUsers;
    }

    /**
     * 新增审批流任务明细
     *
     * @param auditItems 审批流任务明细
     * @return 结果
     */
    @Override
    public int insertAuditItems(AuditItems auditItems) {
        return auditItemsMapper.insertAuditItems(auditItems);
    }

    /**
     * 修改审批流任务明细
     *
     * @param auditItems 审批流任务明细
     * @return 结果
     */
    @Override
    public int updateAuditItems(AuditItems auditItems) {
        return auditItemsMapper.updateAuditItems(auditItems);
    }

    /**
     * 批量删除审批流任务明细
     *
     * @param ids 需要删除的审批流任务明细ID
     * @return 结果
     */
    @Override
    public int deleteAuditItemsByIds(Long[] ids) {
        return auditItemsMapper.deleteAuditItemsByIds(ids);
    }

    /**
     * 删除审批流任务明细信息
     *
     * @param id 审批流任务明细ID
     * @return 结果
     */
    @Override
    public int deleteAuditItemsById(Long id) {
        return auditItemsMapper.deleteAuditItemsById(id);
    }
}
