package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.module.ugp.api.Enum.OrgEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectInitiationEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectMapper;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectResourceMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProjectService;
import com.yeejoin.amos.boot.module.ugp.biz.framework.BusinessIdentify;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 项目信息表服务实现类
 *
 * @author system_generator
 * @date 2022-09-22
 */
@Service
public class ProjectServiceImpl extends BaseService<ProjectDto, Project, ProjectMapper> implements IProjectService {

    @Autowired
    ProjectMapper projectMapper;

    @Autowired
    ProjectResourceServiceImpl projectResourceService;

    @Autowired
    AttachmentServiceImpl attachmentService;

    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    @Autowired
    EquipmentServiceImpl equipmentService;

    @Autowired
    OrgServiceImpl orgService;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleService;

    @Autowired
    ProjectResourceMapper projectResourceMapper;


    @Autowired
    AttachmentServiceImpl attachmentServiceImpl;
    /**
     * 分页查询
     */
    public Page<ProjectDto> queryForProjectPage(Page<ProjectDto> page ,String name,String constructionUnit) {
        Page<ProjectDto> projectDtoPage = this.queryForPage(page, null, false,name,constructionUnit);
        List<ProjectDto> projects = projectDtoPage.getRecords();
        for(ProjectDto project:projects){
            getProjectState(project);
        }
        return projectDtoPage;
    }

    private void getProjectState(ProjectDto project) {
        String state = "",insDep = "",insPerson = "";
        LambdaQueryWrapper<ProjectInitiation> lambdaQueryWrap = new LambdaQueryWrapper<>();
        lambdaQueryWrap.eq(ProjectInitiation::getInstanceId,project.getInstanceId())
//                .eq(ProjectInitiation ::getTaskName, ProjectInitiationEnum.平台审核.getName())
                .orderByDesc(ProjectInitiation::getSequenceNbr);

        List<ProjectInitiation> projectInitiationList = projectInitiationService.list(lambdaQueryWrap);
        if(!ValidationUtil.isEmpty(projectInitiationList)){
            ProjectInitiation projectInitiation = projectInitiationList.iterator().next();
            JSONObject jsonObject = JSON.parseObject(projectInitiation.getContext());
            if(ProjectInitiationEnum.平台审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.审批人审批.getName().equals(project.getStatus()) || ProjectInitiationEnum.审核人审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检科室分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员分配.getName().equals(project.getStatus()) || ProjectInitiationEnum.监检员审核.getName().equals(project.getStatus()) || ProjectInitiationEnum.流程结束.getName().equals(project.getStatus()) || ProjectInitiationEnum.项目关闭.getName().equals(project.getStatus())){
                if(!ValidationUtil.isEmpty(jsonObject)){
                    state = jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE);
                    insDep = jsonObject.getString(XJConstant.INS_DEP);
                    insPerson = jsonObject.getString(XJConstant.INS_PRESON);
                }
            }
        }
        if(ProjectInitiationEnum.平台审核.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "项目待审核";
            }
        } else if (ProjectInitiationEnum.告知申请.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "告知待申请";
            }
        } else if (ProjectInitiationEnum.接受告知.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "告知待接收";
            }
        } else if (ProjectInitiationEnum.审查项目.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "告知待接收";
            }
        } else if (ProjectInitiationEnum.提交资料.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "资料待上传";
            }
        } else if(ProjectInitiationEnum.项目立项.getName().equals(project.getStatus())){
            if(ValidationUtil.isEmpty(state)){
                state = "项目被驳回";
            }
        }

        project.setExamineProjectState(state);
        project.setInsDep(insDep);
        project.setInsPerson(insPerson);
    }


    /**
     * 列表查询 示例
     */
    public List<ProjectDto> queryForProjectList() {
        return this.queryForList("", false);
    }

    /**
     * 查询项目名称
     */
    @BusinessIdentify
    public List<JSONObject> selectName() {
        List<JSONObject> names = new ArrayList<>();

        Long companySequenceNbr = orgService.getReginParams().getBusinessInfo().getCompanySequenceNbr();
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getCompanyId,companySequenceNbr);
        //查询所有项目
        List<Project> projects = projectResourceService.getProjectList();
        for (Project i : projects) {
            JSONObject name = new JSONObject();
            name.put("name", i.getName());
            name.put("sequenceNbr", i.getSequenceNbr());
            names.add(name);
        }

        return names;
    }


    /**
     * 通过多个主键sequence_nbr查询数据
     * @param ids
     * @return
     */
    public List<Project> selectByidList(List<Long> ids){
        return projectMapper.selectBatchIds(ids);
    }

    public ProjectDto getDetail(Long sequenceNbr){

        ProjectDto project = projectMapper.getDetail(sequenceNbr);
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId,sequenceNbr);
        try{
            JSONArray jsonArray = JSON.parseArray(attachmentService.getOne(wrapper).getInfo());
            project.setSubForm(jsonArray);
        }catch (Exception e) {
            System.out.println("该项目暂无附件");
        }
        project.getInstanceId();
        getProjectState(project);
        return project;
    }


    public String saveOrUpdateFile(JSONObject jsonObject){
        JSONArray subForm = jsonObject.getJSONArray("subForm");
        Long sequenceNbr = jsonObject.getLong("sequenceNbr");
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Attachment::getSourceId,sequenceNbr);
        Attachment attachment = attachmentService.getOne(wrapper);
        if(ValidationUtil.isEmpty(attachment)){
            equipmentService.saveAttachment(subForm,sequenceNbr);
        }else {
            attachment.setInfo(JSON.toJSONString(subForm));
            attachmentService.updateById(attachment);
        }
        if(ValidationUtil.isEmpty(jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE))){
            jsonObject.put(XJConstant.PROCESS_PROJECT_STATE,"资料已上传");
        }
        Project project = this.getById(sequenceNbr);
        ProjectDto projectDto = new ProjectDto();
        BeanUtils.copyProperties(project,projectDto);
        projectDto.setInsDep(jsonObject.getString("insDep"));
        projectDto.setInsDep(jsonObject.getString("insPerson"));
        projectDto.setProcessProjectState(jsonObject.getString(XJConstant.PROCESS_PROJECT_STATE));
        boolean design=false,install=false;
        for(Object object:subForm){
            JSONObject jo = JSON.parseObject(JSON.toJSONString(object));
            String type = jo.getString("type");
            if (OrgEnum.设计单位.getKey().equals(type)){
                design=true;
            }
            if (OrgEnum.安装单位.getKey().equals(type)){
                install=true;
            }
        }

        if(design && install){
            projectInitiationService.execute(project.getInstanceId(),projectDto,"1");
        }
        return "ok";
    }

//    //项目模糊筛选
//    @Override
//    public Page<ProjectDto> queryProjectPage(Page<ProjectDto> page, Project project) {
//        Page<ProjectDto> projectDtoPage = projectMapper.queryProjectPage(page,project);
//        List<ProjectDto> projects = projectDtoPage.getRecords();
//        for(ProjectDto projectDto:projects){
//            getProjectState(projectDto);
//        }
//        return projectDtoPage;
//    }




    //项目模糊筛选

//    @BusinessIdentify
//    @Override
//    public IPage<ProjectDto> queryProjectPage(String current,String size, Project project) {
//        IPage<ProjectDto> page = new Page<>();
//        page.setCurrent(Long.parseLong(current));
//        page.setSize(Long.parseLong(size));
//        ReginParams reginParams = orgService.getReginParams();
//        String companyId = String.valueOf(reginParams.getBusinessInfo().getCompanySequenceNbr());
//        String roleName = reginParams.getRole().getRoleName();
//        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
//        String reginCode = "";
//        if(OrgEnum.监察部门.getName().equals(roleName)){
//            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
//            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
//        } else if(OrgEnum.监检机构.getName().equals(roleName)){
//            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
//            reginCode = superviseRuleService.getOne(wrapper).getAdminRegion();
//        } else {
//            page =  projectMapper.queryProjectPage(page, project, roleName, companyId);
//        }
//        if(!ValidationUtil.isEmpty(reginCode)){
//            page = projectMapper.queryProjectPage(page, project, roleName, reginCode);
//        }
//        List<ProjectDto> projects = page.getRecords();
//        for(ProjectDto projectDto:projects){
//            getProjectState(projectDto);
//        }
//        return page;
//    }
//

    @BusinessIdentify
    @Override
    public IPage<ProjectDto> queryProjectPage(String current,String size, Project project) {
        IPage<ProjectDto> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        ReginParams reginParams = orgService.getReginParams();
        String companyId = String.valueOf(reginParams.getBusinessInfo().getCompanySequenceNbr());
        String roleName = reginParams.getRole().getRoleName();
        LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
        Set<String> codes = new HashSet<>();
        if(OrgEnum.监察部门.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getSuperviseDeptId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else if(OrgEnum.监检机构.getName().equals(roleName)){
            wrapper.eq(SuperviseRule::getInspectionUnitId,companyId);
            List<SuperviseRule> superviseRuleList = superviseRuleService.list(wrapper);
            for (SuperviseRule superviseRule :superviseRuleList){
                codes.add(String.valueOf(superviseRule.getAdminRegionCode()));
            }
        } else {
            page =  projectMapper.queryProjectPage(page, project, roleName, companyId,codes);
        }
        if(!ValidationUtil.isEmpty(codes)){
            page = projectMapper.queryProjectPage(page, project, roleName,companyId,codes);
        }
        List<ProjectDto> projects = page.getRecords();
        for(ProjectDto projectDto:projects){
            getProjectState(projectDto);
        }
        return page;
    }





}