
package com.yunzhupaas.bsc.service.impl;

import com.yunzhupaas.bsc.entity.*;
import com.yunzhupaas.bsc.mapper.BillingItemMapper;
import com.yunzhupaas.bsc.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.bsc.model.billingitem.*;
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-20
 */
@Service
public class BillingItemServiceImpl extends SuperServiceImpl<BillingItemMapper, BillingItemEntity> implements BillingItemService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<BillingItemEntity> getList(BillingItemPagination billingItemPagination){
        return getTypeList(billingItemPagination,billingItemPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<BillingItemEntity> getTypeList(BillingItemPagination billingItemPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("bc_billing_item",BillingItemEntity.class);

        MPJLambdaWrapper<BillingItemEntity> wrapper = JoinWrappers
                .lambda("bc_billing_item",BillingItemEntity.class)
                .selectAll(BillingItemEntity.class);
        MPJLambdaWrapper<BillingItemEntity> wrapper2 = JoinWrappers
                .lambda("bc_billing_item",BillingItemEntity.class)
                .distinct().select(BillingItemEntity::getBillingItemId);

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

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

    }

    /**
    * 其他条件拼接
    */
    private void otherConditions(BillingItemPagination billingItemPagination, MPJLambdaWrapper<BillingItemEntity> 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(BillingItemEntity::getFlowId);
        //关键词
        if(ObjectUtil.isNotEmpty(billingItemPagination.getYunzhupaasKeyword())){
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(billingItemPagination.getBillingItemName())){
                String value = billingItemPagination.getBillingItemName() instanceof List ?
                    JsonUtil.getObjectToString(billingItemPagination.getBillingItemName()) :
                    String.valueOf(billingItemPagination.getBillingItemName());
                wrapper.like(BillingItemEntity::getBillingItemName,value);
            }

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

        }
        //排序
        if(StringUtil.isEmpty(billingItemPagination.getSidx())){
                wrapper.orderByDesc(BillingItemEntity::getBillingItemId);
        }else{
            try {
                String[] split = billingItemPagination.getSidx().split(",");
                for(String sidx:split){
                BillingItemEntity billingItemEntity = new BillingItemEntity();
                    String oderTableField = billingItemEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = billingItemEntity.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 BillingItemEntity getInfo(String billingitemid){
        MPJLambdaWrapper<BillingItemEntity> wrapper = JoinWrappers
                .lambda("bc_billing_item",BillingItemEntity.class)
                .selectAll(BillingItemEntity.class);
        wrapper.and(
            t->t.eq(BillingItemEntity::getBillingItemId, billingitemid )
            .or().eq(BillingItemEntity::getFlowTaskId, billingitemid)
        );
        return this.selectJoinOne(BillingItemEntity.class,wrapper);
    }
    @Override
    public void create(BillingItemEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String billingitemid, BillingItemEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(BillingItemEntity entity){
        if(entity!=null){
            this.removeById(entity.getBillingItemId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(BillingItemForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getBillingItemId()) && !form.getBillingItemId().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.getBillingItemId();
        }
        //验证业务主键
        String businessErr = checkBusinessKey(form, isUp ? id : null, null);
        if (StringUtil.isNotEmpty(businessErr)) {
            return businessErr;
        }
        //主表字段验证
            fieldTipName =  "计费项目编码"; 
                if(StringUtil.isEmpty(form.getBillingItemCode())){
                    return fieldTipName + canNotNull;
                }
                if(StringUtil.isNotEmpty(form.getBillingItemCode())){
                    form.setBillingItemCode(form.getBillingItemCode().trim());
                    QueryWrapper<BillingItemEntity> billing_item_codeWrapper=new QueryWrapper<>();
                    billing_item_codeWrapper.lambda().eq(BillingItemEntity::getBillingItemCode,form.getBillingItemCode());
                        billing_item_codeWrapper.lambda().isNull(BillingItemEntity::getFlowId);
                    if (isUp){
                        billing_item_codeWrapper.lambda().ne(BillingItemEntity::getBillingItemId, id);
                    }
                    if((int) this.count(billing_item_codeWrapper)>0){
                        countRecover = fieldTipName + canNotRepeated;
                    }
                }
            fieldTipName =  "计费项目名称"; 
                if(StringUtil.isEmpty(form.getBillingItemName())){
                    return fieldTipName + canNotNull;
                }
            fieldTipName =  "费用类别"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 验证业务主键
    */
    private String checkBusinessKey(BillingItemForm form, Object id, List<String> flowIds){
        QueryWrapper<BillingItemEntity> wrapper = new QueryWrapper<>();
        //修改
        if (id != null){
            wrapper.lambda().ne(BillingItemEntity::getBillingItemId, id);
        }
        //是否流程
        if(flowIds == null){
            wrapper.lambda().isNull(BillingItemEntity::getFlowId);
        }else{
            wrapper.lambda().in(BillingItemEntity::getFlowId, flowIds);
        }
                //计费项目编码字段判断
                if(form.getBillingItemCode() == null || form.getBillingItemCode().toString().trim().isEmpty()){
                    wrapper.lambda().isNull(BillingItemEntity::getBillingItemCode);
                }else{
                    wrapper.lambda().eq(BillingItemEntity::getBillingItemCode, form.getBillingItemCode());
                }
        if((int) this.count(wrapper)>0){
            return "计费项目编码已存在，请勿重复提交！";
        }
        return "";
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param billingItemForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(BillingItemForm billingItemForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        billingItemForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(BillingItemConstant.getFormData(),billingItemForm,BillingItemConstant.TABLERENAMES),BillingItemForm.class);
        BillingItemEntity entity = JsonUtil.getJsonToBean(billingItemForm, BillingItemEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
            entity.setBillingItemId(mainUuid);
        } else {
        }
        boolean b = this.saveOrUpdate(entity);
    BillingItemEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
