
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.ProductsMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.product.*;
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 ProductsServiceImpl extends SuperServiceImpl<ProductsMapper, ProductEntity> implements ProductsService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<ProductEntity> getList(ProductPagination productPagination){
        return getTypeList(productPagination,productPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<ProductEntity> getTypeList(ProductPagination productPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_product",ProductEntity.class);

        MPJLambdaWrapper<ProductEntity> wrapper = JoinWrappers
                .lambda("mdm_product",ProductEntity.class)
                .selectAll(ProductEntity.class);
        MPJLambdaWrapper<ProductEntity> wrapper2 = JoinWrappers
                .lambda("mdm_product",ProductEntity.class)
                .distinct().select(ProductEntity::getProductId);

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

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

    }

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

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

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

            if(ObjectUtil.isNotEmpty(productPagination.getProductType())){
                wrapper.eq(ProductEntity::getProductType,productPagination.getProductType());
            }

        }
        //排序
        if(StringUtil.isEmpty(productPagination.getSidx())){
                wrapper.orderByDesc(ProductEntity::getProductId);
        }else{
            try {
                String[] split = productPagination.getSidx().split(",");
                for(String sidx:split){
                ProductEntity productEntity = new ProductEntity();
                    String oderTableField = productEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = productEntity.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 ProductEntity getInfo(String productid){
        MPJLambdaWrapper<ProductEntity> wrapper = JoinWrappers
                .lambda("mdm_product",ProductEntity.class)
                .selectAll(ProductEntity.class);
        wrapper.and(
            t->t.eq(ProductEntity::getProductId, productid )
            .or().eq(ProductEntity::getFlowTaskId, productid)
        );
        return this.selectJoinOne(ProductEntity.class,wrapper);
    }
    @Override
    public void create(ProductEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String productid, ProductEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(ProductEntity entity){
        if(entity!=null){
            this.removeById(entity.getProductId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(ProductForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getProductId()) && !form.getProductId().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.getProductId();
        }
        //验证业务主键
        String businessErr = checkBusinessKey(form, isUp ? id : null, null);
        if (StringUtil.isNotEmpty(businessErr)) {
            return businessErr;
        }
        //主表字段验证
            fieldTipName =  "商品编码"; 
            fieldTipName =  "商品名称"; 
                if(StringUtil.isEmpty(form.getProductName())){
                    return fieldTipName + canNotNull;
                }
            fieldTipName =  "商品类型"; 
            fieldTipName =  "商品分类"; 
            fieldTipName =  "商品简称"; 
            fieldTipName =  "品牌"; 
            fieldTipName =  "规格型号"; 
            fieldTipName =  "颜色"; 
            fieldTipName =  "尺寸/规格"; 
            fieldTipName =  "重量"; 
            fieldTipName =  "最小起订量"; 
            fieldTipName =  "标准销售单价"; 
            fieldTipName =  "毛重"; 
            fieldTipName =  "净重"; 
            fieldTipName =  "单位名称"; 
            fieldTipName =  "包装尺寸"; 
            fieldTipName =  "成本价"; 
            fieldTipName =  "保修期"; 
            fieldTipName =  "税率"; 
            fieldTipName =  "税收分类"; 
            fieldTipName =  "保修条款"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 验证业务主键
    */
    private String checkBusinessKey(ProductForm form, Object id, List<String> flowIds){
        QueryWrapper<ProductEntity> wrapper = new QueryWrapper<>();
        //修改
        if (id != null){
            wrapper.lambda().ne(ProductEntity::getProductId, id);
        }
        //是否流程
        if(flowIds == null){
            wrapper.lambda().isNull(ProductEntity::getFlowId);
        }else{
            wrapper.lambda().in(ProductEntity::getFlowId, flowIds);
        }
            //假删除标志
            wrapper.lambda().isNull(ProductEntity::getDeleteMark);
                //商品名称字段判断
                if(form.getProductName() == null || form.getProductName().toString().trim().isEmpty()){
                    wrapper.lambda().isNull(ProductEntity::getProductName);
                }else{
                    wrapper.lambda().eq(ProductEntity::getProductName, form.getProductName());
                }
                //商品分类字段判断
                if(form.getProductCategory() == null || form.getProductCategory().toString().trim().isEmpty()
                    ||(form.getProductCategory() instanceof List && ((List) form.getProductCategory()).size() == 0)){
                    wrapper.lambda().isNull(ProductEntity::getProductCategory);
                }else{
                    Object obj = form.getProductCategory() instanceof  List ?JsonUtil.getObjectToString(form.getProductCategory()):form.getProductCategory();
                    wrapper.lambda().eq(ProductEntity::getProductCategory, obj);
                }
        if((int) this.count(wrapper)>0){
            return "商品分类下，商品名称数据已存在，请勿重复提交！";
        }
        return "";
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param productForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(ProductForm productForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        productForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(ProductsConstant.getFormData(),productForm,ProductsConstant.TABLERENAMES),ProductForm.class);
        ProductEntity entity = JsonUtil.getJsonToBean(productForm, ProductEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
                        entity.setProductCode(generaterSwapUtil.getBillNumber("productCode", false));
            entity.setProductId(mainUuid);
            entity.setVersion(0);
        } else {
                    if(StringUtil.isEmpty(entity.getProductCode()) ){
                        entity.setProductCode(generaterSwapUtil.getBillNumber("productCode", false));
                    }
        }
        boolean b = this.saveOrUpdate(entity);
        if(!b){
            throw new DataException("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
        }
    ProductEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
