
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.WorkTypeMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.worktype.*;
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-18
 */
@Service
public class WorkTypeServiceImpl extends SuperServiceImpl<WorkTypeMapper, WorkTypeEntity> implements WorkTypeService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<WorkTypeEntity> getList(WorkTypePagination workTypePagination){
        return getTypeList(workTypePagination,workTypePagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<WorkTypeEntity> getTypeList(WorkTypePagination workTypePagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_work_type",WorkTypeEntity.class);

        MPJLambdaWrapper<WorkTypeEntity> wrapper = JoinWrappers
                .lambda("mdm_work_type",WorkTypeEntity.class)
                .selectAll(WorkTypeEntity.class);
        MPJLambdaWrapper<WorkTypeEntity> wrapper2 = JoinWrappers
                .lambda("mdm_work_type",WorkTypeEntity.class)
                .distinct().select(WorkTypeEntity::getWorkTypeId);

        QueryAllModel queryAllModel = new QueryAllModel();
        queryAllModel.setWrapper(wrapper);
        queryAllModel.setClassMap(tableClassMap);
        queryAllModel.setDbLink(WorkTypeConstant.DBLINKID);
        //数据过滤
        boolean isPc = ServletUtil.getHeader("yunzhupaas-origin").equals("pc");
        String columnData = !isPc ? WorkTypeConstant.getAppColumnData() : WorkTypeConstant.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(workTypePagination.getSuperQueryJson());
        }
        //数据权限
        boolean pcPermission = true;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            queryAllModel.setModuleId(workTypePagination.getMenuId());
        }
        if (!isPc && appPermission) {
            queryAllModel.setModuleId(workTypePagination.getMenuId());
        }
        //拼接复杂条件
        wrapper = generaterSwapUtil.getConditionAllTable(queryAllModel);
        if(wrapper == null) return new ArrayList<>();
        queryAllModel.setWrapper(wrapper2);
        wrapper2 = generaterSwapUtil.getConditionAllTable(queryAllModel);
        //其他条件拼接
        otherConditions(workTypePagination, wrapper, isPc);
        otherConditions(workTypePagination, wrapper2, isPc);

        if("0".equals(dataType)){
            com.github.pagehelper.Page<Object> objects = PageHelper.startPage((int) workTypePagination.getCurrentPage(), (int) workTypePagination.getPageSize(), true);
            List<WorkTypeEntity> userIPage = this.selectJoinList(WorkTypeEntity.class, wrapper2);
            List<Object> collect = userIPage.stream().map(t -> t.getWorkTypeId()).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(collect)){
                wrapper.in(WorkTypeEntity::getWorkTypeId,collect);
            }
            List<WorkTypeEntity> result = this.selectJoinList(WorkTypeEntity.class, wrapper);
            return workTypePagination.setData(result,objects.getTotal());
        }else{
            List<WorkTypeEntity> list = this.selectJoinList(WorkTypeEntity.class, wrapper);
            if("2".equals(dataType)){
                List<Object> selectIds = Arrays.asList(workTypePagination.getSelectIds());
                return list.stream().filter(t -> selectIds.contains(t.getWorkTypeId())).collect(Collectors.toList());
            }else{
                return list;
            }
        }

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(WorkTypePagination workTypePagination, MPJLambdaWrapper<WorkTypeEntity> 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(WorkTypeEntity::getDeleteMark);

        wrapper.isNull(WorkTypeEntity::getFlowId);
        //关键词
        if(ObjectUtil.isNotEmpty(workTypePagination.getYunzhupaasKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(workTypePagination.getWorkTypeName())){
                String value = workTypePagination.getWorkTypeName() instanceof List ?
                    JsonUtil.getObjectToString(workTypePagination.getWorkTypeName()) :
                    String.valueOf(workTypePagination.getWorkTypeName());
                wrapper.like(WorkTypeEntity::getWorkTypeName,value);
            }

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

        }
        //排序
        if(StringUtil.isEmpty(workTypePagination.getSidx())){
                wrapper.orderByDesc(WorkTypeEntity::getWorkTypeId);
        }else{
            try {
                String[] split = workTypePagination.getSidx().split(",");
                for(String sidx:split){
                WorkTypeEntity workTypeEntity = new WorkTypeEntity();
                    String oderTableField = workTypeEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = workTypeEntity.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 WorkTypeEntity getInfo(String worktypeid){
        MPJLambdaWrapper<WorkTypeEntity> wrapper = JoinWrappers
                .lambda("mdm_work_type",WorkTypeEntity.class)
                .selectAll(WorkTypeEntity.class);
        wrapper.and(
            t->t.eq(WorkTypeEntity::getWorkTypeId, worktypeid )
            .or().eq(WorkTypeEntity::getFlowTaskId, worktypeid)
        );
        return this.selectJoinOne(WorkTypeEntity.class,wrapper);
    }
    @Override
    public void create(WorkTypeEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String worktypeid, WorkTypeEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(WorkTypeEntity entity){
        if(entity!=null){
            this.removeById(entity.getWorkTypeId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(WorkTypeForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getWorkTypeId()) && !form.getWorkTypeId().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.getWorkTypeId();
        }
        //主表字段验证
            fieldTipName =  "工种编码"; 
            fieldTipName =  "工种名称"; 
                if(StringUtil.isEmpty(form.getWorkTypeName())){
                    return fieldTipName + canNotNull;
                }
            fieldTipName =  "工种分类"; 
            fieldTipName =  "技能等级"; 
            fieldTipName =  "计价单位"; 
            fieldTipName =  "参考单价"; 
            fieldTipName =  "单价下限"; 
            fieldTipName =  "单价上限"; 
            fieldTipName =  "排序号"; 
            fieldTipName =  "工种描述"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param workTypeForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(WorkTypeForm workTypeForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        workTypeForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(WorkTypeConstant.getFormData(),workTypeForm,WorkTypeConstant.TABLERENAMES),WorkTypeForm.class);
        WorkTypeEntity entity = JsonUtil.getJsonToBean(workTypeForm, WorkTypeEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
                        entity.setWorkTypeCode(generaterSwapUtil.getBillNumber("workTypeCode", false));
            entity.setWorkTypeId(mainUuid);
        } else {
                    if(StringUtil.isEmpty(entity.getWorkTypeCode()) ){
                        entity.setWorkTypeCode(generaterSwapUtil.getBillNumber("workTypeCode", false));
                    }
        }
        boolean b = this.saveOrUpdate(entity);
    WorkTypeEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
