
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.AssetMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.asset.*;
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-04-28
 */
@Service
public class AssetServiceImpl extends SuperServiceImpl<AssetMapper, AssetEntity> implements AssetService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<AssetEntity> getList(AssetPagination assetPagination){
        return getTypeList(assetPagination,assetPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<AssetEntity> getTypeList(AssetPagination assetPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_asset",AssetEntity.class);

        MPJLambdaWrapper<AssetEntity> wrapper = JoinWrappers
                .lambda("mdm_asset",AssetEntity.class)
                .selectAll(AssetEntity.class);
        MPJLambdaWrapper<AssetEntity> wrapper2 = JoinWrappers
                .lambda("mdm_asset",AssetEntity.class)
                .distinct().select(AssetEntity::getAssetId);

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

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

    }

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

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

            if(ObjectUtil.isNotEmpty(assetPagination.getAssetName())){
                String value = assetPagination.getAssetName() instanceof List ?
                        JsonUtil.getObjectToString(assetPagination.getAssetName()) :
                        String.valueOf(assetPagination.getAssetName());
                wrapper.like(AssetEntity::getAssetName,value);
            }

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

            if(ObjectUtil.isNotEmpty(assetPagination.getPurchaseDate())){
                List PurchaseDateList =  JsonUtil.getJsonToList(assetPagination.getPurchaseDate(),String.class);
                for(int i=0;i<PurchaseDateList.size();i++){
                    String id = String.valueOf(PurchaseDateList.get(i));
                    boolean idAll = StringUtil.isNotEmpty(id) && !id.equals("null");
                    if(idAll){
                        Object b= new Date(Long.valueOf(id));
                        if(i==0){
                            wrapper.ge(AssetEntity::getPurchaseDate,b);
                        }else{
                            wrapper.le(AssetEntity::getPurchaseDate,b);
                        }
                    }
                }
            }

            if(ObjectUtil.isNotEmpty(assetPagination.getCommissioningDate())){
                List CommissioningDateList =  JsonUtil.getJsonToList(assetPagination.getCommissioningDate(),String.class);
                for(int i=0;i<CommissioningDateList.size();i++){
                    String id = String.valueOf(CommissioningDateList.get(i));
                    boolean idAll = StringUtil.isNotEmpty(id) && !id.equals("null");
                    if(idAll){
                        Object b= new Date(Long.valueOf(id));
                        if(i==0){
                            wrapper.ge(AssetEntity::getCommissioningDate,b);
                        }else{
                            wrapper.le(AssetEntity::getCommissioningDate,b);
                        }
                    }
                }
            }

            if(ObjectUtil.isNotEmpty(assetPagination.getAssetType())){
                wrapper.eq(AssetEntity::getAssetType,assetPagination.getAssetType());
            }

        }
        //排序
        if(StringUtil.isEmpty(assetPagination.getSidx())){
            wrapper.orderByDesc(AssetEntity::getAssetId);
        }else{
            try {
                String[] split = assetPagination.getSidx().split(",");
                for(String sidx:split){
                    AssetEntity assetEntity = new AssetEntity();
                    String oderTableField = assetEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = assetEntity.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 AssetEntity getInfo(String assetid){
        MPJLambdaWrapper<AssetEntity> wrapper = JoinWrappers
                .lambda("mdm_asset",AssetEntity.class)
                .selectAll(AssetEntity.class);
        wrapper.and(
                t->t.eq(AssetEntity::getAssetId, assetid )
                        .or().eq(AssetEntity::getFlowTaskId, assetid)
        );
        return this.selectJoinOne(AssetEntity.class,wrapper);
    }
    @Override
    public void create(AssetEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String assetid, AssetEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(AssetEntity entity){
        if(entity!=null){
            this.removeById(entity.getAssetId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(AssetForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getAssetId()) && !form.getAssetId().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.getAssetId();
        }
        //主表字段验证
        fieldTipName =  "资产编码";
        fieldTipName =  "资产名称";
        if(StringUtil.isEmpty(form.getAssetName())){
            return fieldTipName + canNotNull;
        }
        fieldTipName =  "资产类型";
        fieldTipName =  "资产分类";
        fieldTipName =  "资产状态";
        fieldTipName =  "资产位置";
        fieldTipName =  "使用组织";
        fieldTipName =  "保管用户";
        fieldTipName =  "资产权属";
        fieldTipName =  "单位";
        fieldTipName =  "数量";
        fieldTipName =  "购置日期";
        fieldTipName =  "启用日期";
        fieldTipName =  "预计使用年限";
        fieldTipName =  "供应商";
        fieldTipName =  "备注";
        return countRecover;
    }
    /**
     * 新增修改数据(事务回滚)
     * @param id
     * @param assetForm
     * @return
     */
    @Override
    @Transactional
    public void saveOrUpdate(AssetForm assetForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        assetForm = JsonUtil.getJsonToBean(
                generaterSwapUtil.swapDatetime(AssetConstant.getFormData(),assetForm,AssetConstant.TABLERENAMES),AssetForm.class);
        AssetEntity entity = JsonUtil.getJsonToBean(assetForm, AssetEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
            entity.setAssetCode(generaterSwapUtil.getBillNumber("assetCode", false));
            entity.setAssetId(mainUuid);
        } else {
            if(StringUtil.isEmpty(entity.getAssetCode()) ){
                entity.setAssetCode(generaterSwapUtil.getBillNumber("assetCode", false));
            }
        }
        boolean b = this.saveOrUpdate(entity);
        AssetEntity info = this.getInfo(mainUuid);
        if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
