
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.MaterialMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.material.*;
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-27
 */
@Service
public class MaterialServiceImpl extends SuperServiceImpl<MaterialMapper, MaterialEntity> implements MaterialService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<MaterialEntity> getList(MaterialPagination materialPagination){
        return getTypeList(materialPagination,materialPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<MaterialEntity> getTypeList(MaterialPagination materialPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_material",MaterialEntity.class);

        MPJLambdaWrapper<MaterialEntity> wrapper = JoinWrappers
                .lambda("mdm_material",MaterialEntity.class)
                .selectAll(MaterialEntity.class);
        MPJLambdaWrapper<MaterialEntity> wrapper2 = JoinWrappers
                .lambda("mdm_material",MaterialEntity.class)
                .distinct().select(MaterialEntity::getMaterialId);

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

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

    }

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

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

            if(ObjectUtil.isNotEmpty(materialPagination.getMaterialModel())){
                String value = materialPagination.getMaterialModel() instanceof List ?
                    JsonUtil.getObjectToString(materialPagination.getMaterialModel()) :
                    String.valueOf(materialPagination.getMaterialModel());
                wrapper.like(MaterialEntity::getMaterialModel,value);
            }

            if(ObjectUtil.isNotEmpty(materialPagination.getMaterialCategory())){
                String value = materialPagination.getMaterialCategory() instanceof List ?
                    JsonUtil.getObjectToString(materialPagination.getMaterialCategory()) :
                    String.valueOf(materialPagination.getMaterialCategory());
                wrapper.like(MaterialEntity::getMaterialCategory,value);
            }

        }
        //排序
        if(StringUtil.isEmpty(materialPagination.getSidx())){
                wrapper.orderByDesc(MaterialEntity::getMaterialId);
        }else{
            try {
                String[] split = materialPagination.getSidx().split(",");
                for(String sidx:split){
                MaterialEntity materialEntity = new MaterialEntity();
                    String oderTableField = materialEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = materialEntity.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 MaterialEntity getInfo(String materialid){
        MPJLambdaWrapper<MaterialEntity> wrapper = JoinWrappers
                .lambda("mdm_material",MaterialEntity.class)
                .selectAll(MaterialEntity.class);
        wrapper.and(
            t->t.eq(MaterialEntity::getMaterialId, materialid )
            .or().eq(MaterialEntity::getFlowTaskId, materialid)
        );
        return this.selectJoinOne(MaterialEntity.class,wrapper);
    }
    @Override
    public void create(MaterialEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String materialid, MaterialEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(MaterialEntity entity){
        if(entity!=null){
            this.removeById(entity.getMaterialId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(MaterialForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getMaterialId()) && !form.getMaterialId().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.getMaterialId();
        }
        //验证业务主键
        String businessErr = checkBusinessKey(form, isUp ? id : null, null);
        if (StringUtil.isNotEmpty(businessErr)) {
            return businessErr;
        }
        //主表字段验证
            fieldTipName =  "物料编码"; 
            fieldTipName =  "物料名称"; 
            fieldTipName =  "物料分类"; 
            fieldTipName =  "规格型号"; 
            fieldTipName =  "单位名称"; 
            fieldTipName =  "品牌"; 
            fieldTipName =  "税率"; 
            fieldTipName =  "税收分类"; 
            fieldTipName =  "材质/纹理"; 
            fieldTipName =  "质量标准"; 
            fieldTipName =  "技术标准"; 
            fieldTipName =  "验收标准"; 
            fieldTipName =  "交付要求"; 
            fieldTipName =  "储存条件"; 
        return countRecover;
    }
    /**
    * 验证业务主键
    */
    private String checkBusinessKey(MaterialForm form, Object id, List<String> flowIds){
        QueryWrapper<MaterialEntity> wrapper = new QueryWrapper<>();
        //修改
        if (id != null){
            wrapper.lambda().ne(MaterialEntity::getMaterialId, id);
        }
        //是否流程
        if(flowIds == null){
            wrapper.lambda().isNull(MaterialEntity::getFlowId);
        }else{
            wrapper.lambda().in(MaterialEntity::getFlowId, flowIds);
        }
            //假删除标志
            wrapper.lambda().isNull(MaterialEntity::getDeleteMark);
                //物料名称字段判断
                if(form.getMaterialName() == null || form.getMaterialName().toString().trim().isEmpty()){
                    wrapper.lambda().isNull(MaterialEntity::getMaterialName);
                }else{
                    wrapper.lambda().eq(MaterialEntity::getMaterialName, form.getMaterialName());
                }
                //物料分类字段判断
                if(form.getMaterialCategory() == null || form.getMaterialCategory().toString().trim().isEmpty()
                    ||(form.getMaterialCategory() instanceof List && ((List) form.getMaterialCategory()).size() == 0)){
                    wrapper.lambda().isNull(MaterialEntity::getMaterialCategory);
                }else{
                    Object obj = form.getMaterialCategory() instanceof  List ?JsonUtil.getObjectToString(form.getMaterialCategory()):form.getMaterialCategory();
                    wrapper.lambda().eq(MaterialEntity::getMaterialCategory, obj);
                }
        if((int) this.count(wrapper)>0){
            return "该物料分类下，该物料名称数据已存在，请勿重复提交！";
        }
        return "";
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param materialForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(MaterialForm materialForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        materialForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(MaterialConstant.getFormData(),materialForm,MaterialConstant.TABLERENAMES),MaterialForm.class);
        MaterialEntity entity = JsonUtil.getJsonToBean(materialForm, MaterialEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
                        entity.setMaterialCode(generaterSwapUtil.getBillNumber("materialCode", false));
            entity.setMaterialId(mainUuid);
            entity.setVersion(0);
        } else {
                    if(StringUtil.isEmpty(entity.getMaterialCode()) ){
                        entity.setMaterialCode(generaterSwapUtil.getBillNumber("materialCode", false));
                    }
        }
        boolean b = this.saveOrUpdate(entity);
        if(!b){
            throw new DataException("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
        }
    MaterialEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
