package cn.palmte.work.service;

import cn.palmte.work.bean.*;
import cn.palmte.work.model.*;
import cn.palmte.work.utils.InterfaceUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.jfunc.common.db.QueryHelper;
import top.jfunc.common.db.bean.Page;
import top.jfunc.common.db.utils.Pagination;
import top.jfunc.common.utils.CollectionUtil;
import top.jfunc.common.utils.StrUtil;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author xiongshiyan at 2021/10/29 , contact me with email yanshixiong@126.com or phone 15208384257
 */
@Service
public class ProjectService {
    @Autowired
    private Pagination pagination;
    @Autowired
    private ProjectRepository projectRepository;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ActTaskDefService actTaskDefService;
    @Autowired
    private ProjectInstanceRelationRepository projectInstanceRelationRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private ProjectVisibleRepository projectVisibleRepository;
    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private ProjectEstimateService projectEstimateService;
    @Autowired
    private ProjectInstanceService projectInstanceService;
    @Autowired
    private ProjectBudgetService projectBudgetService;

    private QueryHelper getQueryHelper(Map<String, String> searchInfo) {
        /*"CASE p.type WHEN 1 THEN '工程集成类' WHEN 2 THEN '设备集成类' WHEN 3 THEN '战略合作类' ELSE '未知' AS typeDesc," +
                "CASE p.status WHEN 0 THEN '草稿' WHEN 1 THEN '项目创建' WHEN 5 THEN '概算完成' WHEN 10 THEN '预算完成' WHEN 15 THEN '结算中' WHEN 20 THEN '决算完成' ELSE '未知' AS statusDesc," +
                "CASE p.approve_status WHEN 0 THEN '待审核' WHEN 1 THEN '审核通过' WHEN 2 THEN '审核不通过' ELSE '未知' AS approveStatusDesc," +
                */
        QueryHelper queryHelper = new QueryHelper("SELECT p.*, FORMAT(p.contract_amount,2) as contractRound, FORMAT(p.huazhi_product_amount,2) as huazhiRound, FORMAT(p.ziguang_other_amount,2) as ziguangRound","project","p");
        if(StrUtil.isNotEmpty(searchInfo.get("status")) && !"-1".equals(searchInfo.get("status"))){
            queryHelper.addCondition("p.status=?", Integer.parseInt(searchInfo.get("status")));
        }
        ///
        /*if(StrUtil.isNotEmpty(searchInfo.get("approveId"))){
            int approveId = Integer.parseInt(searchInfo.get("approveId"));
            queryHelper.addCondition("p.approve_id=?", approveId);
        }*/
        if(StrUtil.isNotEmpty(searchInfo.get("approveStatus")) && !"-1".equals(searchInfo.get("approveStatus"))){
            int approveStatus = Integer.parseInt(searchInfo.get("approveStatus"));
            //四种状态满足其一即可
            queryHelper.addCondition("((p.status=? AND p.approve_status_estimate=?) OR (p.status=? AND p.approve_status_budget=?) OR (p.status=? AND p.approve_status_settle=?) OR (p.status=? AND p.approve_status_final=?))",
                    StatusEnum.ESTIMATE_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.BUDGET_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.SETTLE_ACCOUNTS.getStatus(),approveStatus,
                    StatusEnum.FINAL_ACCOUNTS.getStatus(),approveStatus);
        }
        if(StrUtil.isNotEmpty(searchInfo.get("deptId")) && !"-1".equals(searchInfo.get("deptId"))){
            queryHelper.addCondition("p.dept_id=?", Integer.parseInt(searchInfo.get("deptId")));
        }
        if(StrUtil.isNotEmpty(searchInfo.get("type")) && !"-1".equals(searchInfo.get("type"))){
            queryHelper.addCondition("p.type=?", Integer.parseInt(searchInfo.get("type")));
        }
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("name")),"p.name LIKE ?", "%"+searchInfo.get("name")+"%");
        queryHelper.addCondition(StrUtil.isNotEmpty(searchInfo.get("creatorName")),"p.creator_name LIKE ?", "%"+searchInfo.get("creatorName")+"%");

        /**
         * 只选择了一个时间的情况，就项目时间包括这个时间的
         */
        if(StrUtil.isNotEmpty(searchInfo.get("startDate")) && StrUtil.isEmpty(searchInfo.get("endDate"))){
            String time = searchInfo.get("startDate") + " 00:00:00";
            queryHelper.addCondition("p.start_date<=? AND p.end_date>=?", time, time);
        }
        if(StrUtil.isNotEmpty(searchInfo.get("endDate")) && StrUtil.isEmpty(searchInfo.get("startDate"))){
            String time = searchInfo.get("endDate") + " 00:00:00";
            queryHelper.addCondition("p.start_date<=? AND p.end_date>=?", time, time);
        }
        /**
         * 两个时间都选了，则包含项目时间
         */
        if(StrUtil.isNotEmpty(searchInfo.get("startDate")) && StrUtil.isNotEmpty(searchInfo.get("endDate"))){
            String startTime = searchInfo.get("startDate") + " 00:00:00";
            String endTime = searchInfo.get("endDate") + " 23:59:59";
            queryHelper.addCondition("p.start_date>=? AND p.end_date<=?", startTime, endTime);
        }

        if(StrUtil.isNotEmpty(searchInfo.get("startUpdateDate"))){
            String time = searchInfo.get("startUpdateDate") + " 00:00:00";
            queryHelper.addCondition("p.last_update_time>=?", time);
        }
        if(StrUtil.isNotEmpty(searchInfo.get("endUpdateDate"))){
            String time = searchInfo.get("endUpdateDate") + " 00:00:00";
            queryHelper.addCondition("p.last_update_time<=?", time);
        }

        //项目可见性，根据角色和人员id
        Admin admin = InterfaceUtil.getAdmin();
        int roleId = admin.getRoleId();
        Integer adminId = admin.getId();
        //自己创建的肯定能看见，配置的可以看见，系统管理员可以看见
        SysRole sysRole = sysRoleRepository.findSysRoleById(roleId);
        if(SysRole.ROLE_TYPE_SYSTEM != sysRole.getType()){
            queryHelper.addCondition("(p.creator_id=? OR p.id in (SELECT pv1.project_id FROM project_visible pv1 WHERE pv1.type=1 AND pv1.tid=? UNION SELECT pv2.project_id FROM project_visible pv2 WHERE pv2.type=2 AND pv2.tid=?))", adminId, roleId, adminId);
        }


        queryHelper.addDescOrderProperty("p.last_update_time");

        return queryHelper;
    }

    public Page<Project> list(Map<String, String> searchInfo, int pageNumber, int pageSize){
        QueryHelper queryHelper = getQueryHelper(searchInfo);
        return pagination.paginate(queryHelper.getSql(), Project.class,pageNumber,pageSize);
    }


    /**
     * 找到待我审核项目
     */
    public Page<Project> findMyApproveProjects(Map<String, String> searchInfo, int adminId, int pageNumber, int pageSize){
        //待审核状态的条件
        searchInfo.put("approveStatus", ""+ApproveStatusEnum.APPROVAL_PENDING.getApproveStatus());

        QueryHelper queryHelper = getQueryHelper(searchInfo);
        //在列表基础上增加审核人是我
        queryHelper.addCondition("p.approve_id=?", adminId);
        return pagination.paginate(queryHelper.getSql(), Project.class,pageNumber,pageSize);
    }



    public Project getProject(int id){
        return projectRepository.findOne(id);
    }


    public Project addProject(Project project, Admin admin, ApproveStatusEnum approveStatusEnum) {
        project.setTypeDesc(TypeEnum.parseType(project.getType()).getTypeDesc());
        project.setStatus(StatusEnum.ESTIMATE_ACCOUNTS.getStatus());
        project.setStatusDesc(StatusEnum.ESTIMATE_ACCOUNTS.getStatusDesc());
        project.setApproveStatusEstimate(approveStatusEnum.getApproveStatus());
        project.setCreatorId(admin.getId());
        project.setCreatorName(admin.getRealName());

        ProjectConfigBean projectConfigBeanConfig = sysConfigService.getProjectConfigBeanConfig();
        project.setProjectContributionProfitRateThreshold(projectConfigBeanConfig.getProjectContributionProfitRateThreshold());
        project.setUnderwrittenTaxRate(projectConfigBeanConfig.getUnderwrittenTaxRate());

        project.setApproveId(0);
        project.setApproveName("");

        Dept one = deptRepository.findOne(admin.getDeptId());
        project.setDeptId(one.getId());
        project.setDeptName(one.getName());

        Date now = new Date();
        project.setCreateTime(now);
        project.setLastUpdateTime(now);

        project = projectRepository.saveAndFlush(project);
        return project;
    }

    public Project editProject(Project project, Project projectInDb) {

        //只有如下可以修改
        projectInDb.setName(project.getName());
        projectInDb.setProjectNo(project.getProjectNo());
        projectInDb.setCustomer(project.getCustomer());
        projectInDb.setTerminalCustomer(project.getTerminalCustomer());
        projectInDb.setIndustryScenario(project.getIndustryScenario());
        projectInDb.setType(project.getType());
        projectInDb.setTypeDesc(TypeEnum.parseType(project.getType()).getTypeDesc());
        projectInDb.setUnderwrittenMode(project.getUnderwrittenMode());

        projectInDb.setStartDate(project.getStartDate());
        projectInDb.setEndDate(project.getEndDate());
        projectInDb.setContractAmount(project.getContractAmount());
        projectInDb.setHuazhiProductAmount(project.getHuazhiProductAmount());
        projectInDb.setZiguangOtherAmount(project.getZiguangOtherAmount());
        projectInDb.setMainContractCollectionTerms(project.getMainContractCollectionTerms());
        projectInDb.setValueRisk(project.getValueRisk());
        projectInDb.setOtherName(project.getOtherName());

        projectInDb.setPlanStartStr(project.getPlanStartStr());
        projectInDb.setPlanEndStr(project.getPlanEndStr());
        /// projectInDb.setApproveStatusEstimate(approveStatusEnum.getApproveStatus());

        projectInDb.setLastUpdateTime(new Date());

        return projectInDb;
    }


    public ResponseMsg completeTask(int projectId, String json,int approvetype) {
        List<ProjectInstanceRelation> relationList = projectInstanceRelationRepository.findByProjectIdOrderByCreateTimeDesc(projectId);
        if (relationList == null || relationList.isEmpty()) {
            return ResponseMsg.buildFailedMsg("审核失败");
        }
        ProjectInstanceRelation projectInstanceRelation = relationList.get(0);
        JSONObject obj = JSON.parseObject(json);
        actTaskDefService.completeTaskByProcInsId(projectInstanceRelation.getProcessInsId(),
                obj.getIntValue("type"), obj.getString("message"));

        return ResponseMsg.buildSuccessMsg("审核成功",approvetype);
    }


    /**
     * 会签
     *
     * @param projectId
     * @param json
     * @param approvetype
     * @return
     */
    public ResponseMsg skipTask(int projectId, String json, int approvetype) {
        List<ProjectInstanceRelation> relationList = projectInstanceRelationRepository.findByProjectIdOrderByCreateTimeDesc(projectId);
        if (relationList == null || relationList.isEmpty()) {
            return ResponseMsg.buildFailedMsg("会签失败");
        }

        JSONObject obj = JSON.parseObject(json);
        String fileUrl = obj.getString("fileUrl");

        ProjectInstanceRelation projectInstanceRelation = relationList.get(0);
        return actTaskDefService.skipTaskByProcInsId(projectInstanceRelation.getProcessInsId(), fileUrl, approvetype);
    }

    /**
     * 更新项目状态和审批状态
     */
    public void updateStatusAndApproveStatus(int projectId, StatusEnum statusEnum, ApproveStatusEnum approveStatusEnum, String otherName) {
        Project one = projectRepository.findOne(projectId);
        one.setStatus(statusEnum.getStatus());
        one.setStatusDesc(statusEnum.getStatusDesc());
        one.setOtherName(otherName);

        int approveStatus = approveStatusEnum.getApproveStatus();
        switch (statusEnum) {
            case ESTIMATE_ACCOUNTS:
                one.setApproveStatusEstimate(approveStatus);
                break;
            case BUDGET_ACCOUNTS:
                one.setApproveStatusBudget(approveStatus);
                break;
            case SETTLE_ACCOUNTS:
                one.setApproveStatusSettle(approveStatus);
                break;
            case FINAL_ACCOUNTS:
                one.setApproveStatusFinal(approveStatus);
                break;
            default:
        }

        one.setLastUpdateTime(new Date());
        projectRepository.saveAndFlush(one);
    }


    private static final String PREFIX_ROLE = "r-";
    private static final String PREFIX_USER = "u-";
    /**
     * 把所有的角色和人员按照层级返回
     */
    public List<ZTreeNode> getZTreeNodes(int projectId){
        List<SysRole> roleList = sysRoleRepository.findAllRole();
        //过滤掉系统管理员角色
        roleList = roleList.stream().filter(sysRole -> sysRole.getType()!=SysRole.ROLE_TYPE_SYSTEM).collect(Collectors.toList());


        List<Admin> adminList = adminRepository.getAllEnable();
        List<ZTreeNode> zTreeNodes = new ArrayList<>(roleList.size()+adminList.size());

        List<ProjectVisible> projectVisibles = projectVisibleRepository.findAllByProjectIdEquals(projectId);
        List<ProjectVisible> visibleRoleList = filterByType(projectVisibles, ProjectVisible.TYPE_ROLE);
        List<ProjectVisible> visibleUserList = filterByType(projectVisibles, ProjectVisible.TYPE_USER);


        for (SysRole sysRole : roleList) {
            List<ZTreeNode> filterAdmins = filterAdmins(adminList, sysRole, visibleUserList);
            if(CollectionUtil.isNotEmpty(filterAdmins)){
                //下面有人才要
                zTreeNodes.add(new ZTreeNode(PREFIX_ROLE + sysRole.getId(), "0", sysRole.getName(),
                        isChecked(visibleRoleList, sysRole.getId()), false));
                zTreeNodes.addAll(filterAdmins);
            }
        }

        return zTreeNodes;
    }

    private List<ZTreeNode> filterAdmins(List<Admin> adminList, SysRole sysRole, List<ProjectVisible> visibleUserList) {
        List<Admin> admins = adminList.stream()
                .filter(a -> sysRole.getId() == a.getRoleId())
                .collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(admins)){
            ArrayList<ZTreeNode> zTreeNodes = new ArrayList<>(admins.size());
            for (Admin admin : admins) {
                zTreeNodes.add(new ZTreeNode(PREFIX_USER+admin.getId(),PREFIX_ROLE+sysRole.getId(),admin.getRealName(),
                        isChecked(visibleUserList, admin.getId()),false));
            }
            return zTreeNodes;
        }

        return Collections.emptyList();
    }

    private boolean isChecked(List<ProjectVisible> visibleList, int id) {
        return visibleList.stream().anyMatch(pv->pv.getTid()==id);
    }
    private List<ProjectVisible> filterByType(List<ProjectVisible> projectVisibles, int type){
        if(CollectionUtil.isEmpty(projectVisibles)){
            return Collections.emptyList();
        }
        return projectVisibles.stream().filter(pv -> pv.getType() == type).collect(Collectors.toList());
    }

    public void saveProjectVisible(Integer projectId, String[] idss) {
        //1.先清除以前的
        List<ProjectVisible> projectVisibles = projectVisibleRepository.findAllByProjectIdEquals(projectId);
        if(CollectionUtil.isNotEmpty(projectVisibles)){
            projectVisibleRepository.deleteInBatch(projectVisibles);
        }
        //2.再保存
        List<ProjectVisible> pvs = new ArrayList<>(idss.length);
        for (String s : idss) {
            //只要用户的，角色的不要
            if(s.startsWith(PREFIX_USER)){
                ProjectVisible pv = new ProjectVisible();
                pv.setProjectId(projectId);
                pv.setType(ProjectVisible.TYPE_USER);
                //去掉前缀
                pv.setTid(Integer.parseInt(s.substring(PREFIX_USER.length())));
                pvs.add(pv);
            }
        }
        projectVisibleRepository.save(pvs);
    }

    @Transactional(rollbackFor = Exception.class)
    public ResponseMsg deleteProject(int id) {
        Project one = projectRepository.findOne(id);
        if (one == null) {
            return ResponseMsg.buildFailedMsg("项目不存在");
        }

        if (one.getStatus() != StatusEnum.ESTIMATE_ACCOUNTS.getStatus()
                || one.getApproveStatusEstimate() != ApproveStatusEnum.APPROVAL_UNCOMMIT.getApproveStatus()) {
            return ResponseMsg.buildFailedMsg("项目当前状态下不能删除");
        }

        projectRepository.delete(id);

        projectEstimateService.deleteEstimate(id);

        return ResponseMsg.buildSuccessMsg("删除成功");
    }

    public void saveApprove(Project project, Admin admin) throws Exception {
        if (project.getApproveStatusEstimate() == ApproveStatusEnum.APPROVAL_UNCOMMIT.getApproveStatus()) {
            Integer approveStatusEstimate = project.getApproveStatusEstimate();

            projectEstimateService.estimateApprove(approveStatusEstimate, project, admin);
            project.setApproveStatusEstimate(ApproveStatusEnum.APPROVAL_PENDING.getApproveStatus());
        } else if (project.getApproveStatusBudget() == ApproveStatusEnum.APPROVAL_UNCOMMIT.getApproveStatus()) {
            Integer approveStatusBudget = project.getApproveStatusBudget();

            projectBudgetService.budgetApprove(approveStatusBudget, project, admin);
            project.setApproveStatusBudget(ApproveStatusEnum.APPROVAL_PENDING.getApproveStatus());
        } else if (project.getApproveStatusSettle() == ApproveStatusEnum.APPROVAL_UNCOMMIT.getApproveStatus()) {
            projectInstanceService.startSettleProcessInstance(project, InterfaceUtil.getAdmin());
            project.setApproveStatusSettle(ApproveStatusEnum.APPROVAL_PENDING.getApproveStatus());
        } else if (project.getApproveStatusFinal() == ApproveStatusEnum.APPROVAL_UNCOMMIT.getApproveStatus()) {
            projectInstanceService.startFinalProcessInstance(project.getId(), InterfaceUtil.getAdmin());
            project.setApproveStatusFinal(ApproveStatusEnum.APPROVAL_PENDING.getApproveStatus());
        } else {
            return ;
        }
        projectRepository.save(project);
    }
}
