
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.ProjectsMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.projects.*;
import org.springframework.stereotype.Service;
import com.yunzhupaas.base.service.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import com.yunzhupaas.util.GeneraterSwapUtil;
import java.sql.Connection;
import java.sql.SQLException;
import lombok.Cleanup;
import com.yunzhupaas.database.plugins.DynamicSourceGeneratorInterface;
import com.yunzhupaas.database.util.DynamicDataSourceUtil;
import org.apache.commons.collections4.CollectionUtils;
import com.yunzhupaas.i18n.util.I18nUtil;
import com.yunzhupaas.exception.DataException;
import com.yunzhupaas.constant.MsgCode;
import java.math.BigDecimal;
import cn.hutool.core.util.ObjectUtil;
import java.lang.reflect.Field;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.yunzhupaas.base.model.ColumnDataModel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yunzhupaas.model.QueryAllModel;
import java.text.SimpleDateFormat;
import com.yunzhupaas.util.*;
import java.util.*;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.permission.entity.UserEntity;
import com.github.pagehelper.PageHelper;
/**
 *
 * 项目信息
 * 版本： V5.2.7
 * 版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * 作者： 深圳市乐程软件有限公司
 * 日期： 2026-05-19
 */
@Service
public class ProjectsServiceImpl extends SuperServiceImpl<ProjectsMapper, ProjectsEntity> implements ProjectsService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private ProjectsMapper projectsMapper;

    @Override
    public List<ProjectsEntity> getList(ProjectsPagination projectsPagination){
        return getTypeList(projectsPagination,projectsPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<ProjectsEntity> getTypeList(ProjectsPagination projectsPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_project",ProjectsEntity.class);

        MPJLambdaWrapper<ProjectsEntity> wrapper = JoinWrappers
                .lambda("mdm_project",ProjectsEntity.class)
                .selectAll(ProjectsEntity.class);
        MPJLambdaWrapper<ProjectsEntity> wrapper2 = JoinWrappers
                .lambda("mdm_project",ProjectsEntity.class)
                .distinct().select(ProjectsEntity::getProjectId);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        queryAllModel.setDbLink(ProjectsConstant.DBLINKID);
        //数据过滤
        boolean isPc = ServletUtil.getHeader("yunzhupaas-origin").equals("pc");
        String columnData = !isPc ? ProjectsConstant.getAppColumnData() : ProjectsConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());
        queryAllModel.setRuleJson(ruleJson);
        //高级查询
        boolean hasSuperQuery =  true;
        if (hasSuperQuery) {
            queryAllModel.setSuperJson(projectsPagination.getSuperQueryJson());
        }
        //数据权限
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            queryAllModel.setModuleId(projectsPagination.getMenuId());
        }
        if (!isPc && appPermission) {
            queryAllModel.setModuleId(projectsPagination.getMenuId());
        }
        //拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        if(wrapper == null) return new ArrayList<>();
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        //其他条件拼接
        otherConditions(projectsPagination, wrapper, isPc);
        otherConditions(projectsPagination, wrapper2, isPc);

        //分组和树形生成这个代码,pc端返回全部数据  !"2".equals(dataType)导出选中数据
        if(isPc && !"2".equals(dataType)){
            dataType = "1";
        }
        if("0".equals(dataType)){
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage((int) projectsPagination.getCurrentPage(), (int) projectsPagination.getPageSize(), true);
            List<ProjectsEntity> userIPage = this.selectJoinList(ProjectsEntity.class, wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getProjectId()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                wrapper.in(ProjectsEntity::getProjectId,collect);
            }
            List<ProjectsEntity> result = this.selectJoinList(ProjectsEntity.class, wrapper);
            return projectsPagination.setData(result,objects.getTotal());
        }else{
            List<ProjectsEntity> list = this.selectJoinList(ProjectsEntity.class, wrapper);
            if("2".equals(dataType)){
                List<Object> selectIds = Arrays.asList(projectsPagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getProjectId())).collect(Collectors.toList());
            }else{
                return list;
            }
        }

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(ProjectsPagination projectsPagination, MPJLambdaWrapper<ProjectsEntity> wrapper, boolean isPc) {
        String databaseName;
        try {
            @Cleanup Connection cnn = DynamicDataSourceUtil.getCurrentConnection();
            databaseName = cnn.getMetaData().getDatabaseProductName().trim();
        } catch (SQLException e) {
            throw new DataException(e.getMessage());
        }
        wrapper.isNull(ProjectsEntity::getFlowId);
        //关键词
        if(ObjectUtil.isNotEmpty(projectsPagination.getYunzhupaasKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(projectsPagination.getProjectName())){
                String value = projectsPagination.getProjectName() instanceof List ?
                    JsonUtil.getObjectToString(projectsPagination.getProjectName()) :
                    String.valueOf(projectsPagination.getProjectName());
                wrapper.like(ProjectsEntity::getProjectName,value);
            }

            if(ObjectUtil.isNotEmpty(projectsPagination.getOrgId())){
                List<String> idList = new ArrayList<>();
                try {
                    String[][] orgId = JsonUtil.getJsonToBean(projectsPagination.getOrgId(),String[][].class);
                    for(int i=0;i<orgId.length;i++){
                        if(orgId[i].length>0){
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(orgId[i])));
                        }
                    }
                }catch (Exception e1){
                    try {
                        List<String> orgId = JsonUtil.getJsonToList(projectsPagination.getOrgId(),String.class);
                        if(orgId.size()>0){
                            idList.add(JsonUtil.getObjectToString(orgId));
                        }
                    }catch (Exception e2){
                        idList.add(String.valueOf(projectsPagination.getOrgId()));
                    }
                }
                wrapper.and(t->{
                    idList.forEach(tt->{
                        if(StringUtil.isNotEmpty(tt) && "Microsoft SQL Server".equalsIgnoreCase(databaseName)){
                            tt = tt.replaceFirst("\\[","[[]");
                        }
                        t.like(ProjectsEntity::getOrgId, tt).or();
                    });
                });
            }

        }
        //排序
        if(StringUtil.isEmpty(projectsPagination.getSidx())){
                wrapper.orderByDesc(ProjectsEntity::getProjectId);
        }else{
            try {
                String[] split = projectsPagination.getSidx().split(",");
                for(String sidx:split){
                ProjectsEntity projectsEntity = new ProjectsEntity();
                    String oderTableField = projectsEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = projectsEntity.getClass().getDeclaredField(sidxField);
                        declaredField.setAccessible(true);
                        sidxField = declaredField.getAnnotation(TableField.class).value();
                    }catch (Exception e){
                    }
                    String finalOderTableField = oderTableField;
                    String finalSidxField = sidxField;
                    Object select = wrapper.getSelectColumns().stream().filter(t -> Objects.equals(finalOderTableField, t.getTableAlias())
                            && Objects.equals(finalSidxField, t.getColumn())).findFirst().orElse(null);
                    oderTableField = oderTableField + "." + sidxField;
                    if (select == null) {
                        wrapper.select(oderTableField);
                    }
                    if (descFlag) {
                        wrapper.orderByDesc(oderTableField);
                    } else {
                        wrapper.orderByAsc(oderTableField);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public ProjectsEntity getInfo(String projectid){
        MPJLambdaWrapper<ProjectsEntity> wrapper = JoinWrappers
                .lambda("mdm_project",ProjectsEntity.class)
                .selectAll(ProjectsEntity.class);
        wrapper.and(
            t->t.eq(ProjectsEntity::getProjectId, projectid )
            .or().eq(ProjectsEntity::getFlowTaskId, projectid)
        );
        return this.selectJoinOne(ProjectsEntity.class,wrapper);
    }
    @Override
    public void create(ProjectsEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String projectid, ProjectsEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ProjectsEntity entity){
        if(entity!=null){
            this.removeById(entity.getProjectId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(ProjectsForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getProjectId()) && !form.getProjectId().equals("0");
        Object id= null;
        String countRecover = "";
        String fieldTipName = "";
        String canNotNull = I18nUtil.getMessageStr("sys.validate.textRequiredSuffix", "不能为空");
        String canNotRepeated = I18nUtil.getMessageStr("EXIST103", "不能重复");
        if (isUp){
            id = form.getProjectId();
        }
        //主表字段验证
            fieldTipName =  "项目编码"; 
            fieldTipName =  "项目名称"; 
            fieldTipName =  "项目类型"; 
            fieldTipName =  "归属组织"; 
            fieldTipName =  "上级项目"; 
            fieldTipName =  "顺序号"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param projectsForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(ProjectsForm projectsForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        projectsForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(ProjectsConstant.getFormData(),projectsForm,ProjectsConstant.TABLERENAMES),ProjectsForm.class);
        ProjectsEntity entity = JsonUtil.getJsonToBean(projectsForm, ProjectsEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
            entity.setProjectId(mainUuid);
        } else {
        }
        boolean b = this.saveOrUpdate(entity);
    ProjectsEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }

    @Override
    public List<Map<String, Object>> getTreeList() {
        List<Map<String, Object>> result = new ArrayList<>();
        List<ProjectsEntity> list = projectsMapper.selectList(null);
        for (ProjectsEntity node : list) {
            if (node.getPid() == null || node.getPid().isEmpty() || "0".equals(node.getPid())) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", node.getProjectId());
                map.put("projectName", node.getProjectName());
                map.put("children", getChildrenSimple(list, node.getProjectId()));
                result.add(map);
            }
        }

        return result;
    }

    @Override
    public String getProjettype(String  projectstypeId) {
        return projectsMapper.getProjettype(projectstypeId);

    }

    private List<Map<String, Object>> getChildrenSimple(List<ProjectsEntity> list, String parentId) {
        List<Map<String, Object>> children = new ArrayList<>();
        for (ProjectsEntity node : list) {
            if (parentId.equals(node.getPid())) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", node.getProjectId());
                map.put("projectName", node.getProjectName());
                map.put("children", getChildrenSimple(list, node.getProjectId()));
                children.add(map);
            }
        }
        return children;
    }
}
