
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.CrmLeadMapper;
import com.yunzhupaas.mdm.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunzhupaas.mdm.model.crmlead.*;
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;
/**
 *
 * crm_lead
 * 版本： V5.2.7
 * 版权： Copyright @ 2025  深圳市乐程软件有限公司版权所有
 * 作者： 深圳市乐程软件有限公司
 * 日期： 2026-05-18
 */
@Service
public class CrmLeadServiceImpl extends SuperServiceImpl<CrmLeadMapper, CrmLeadEntity> implements CrmLeadService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Override
    public List<CrmLeadEntity> getList(CrmLeadPagination crmLeadPagination){
        return getTypeList(crmLeadPagination,crmLeadPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<CrmLeadEntity> getTypeList(CrmLeadPagination crmLeadPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("crm_lead",CrmLeadEntity.class);

        MPJLambdaWrapper<CrmLeadEntity> wrapper = JoinWrappers
                .lambda("crm_lead",CrmLeadEntity.class)
                .selectAll(CrmLeadEntity.class);
        MPJLambdaWrapper<CrmLeadEntity> wrapper2 = JoinWrappers
                .lambda("crm_lead",CrmLeadEntity.class)
                .distinct().select(CrmLeadEntity::getLeadId);

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

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

    }

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

        //流程数据隔离
        List<String> flowIds = generaterSwapUtil.getFlowIds(crmLeadPagination.getFlowId());
        wrapper.in(CrmLeadEntity::getFlowId,flowIds);
        //关键词
        if(ObjectUtil.isNotEmpty(crmLeadPagination.getYunzhupaasKeyword())){
            if(isPc){
                wrapper.and(t -> {
                    t.like(CrmLeadEntity::getMobile,crmLeadPagination.getYunzhupaasKeyword()).or();
                });
            }
        }
        //普通查询
        if(isPc){
            if(ObjectUtil.isNotEmpty(crmLeadPagination.getMobile())){
                String value = crmLeadPagination.getMobile() instanceof List ?
                    JsonUtil.getObjectToString(crmLeadPagination.getMobile()) :
                    String.valueOf(crmLeadPagination.getMobile());
                wrapper.like(CrmLeadEntity::getMobile,value);
            }

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

        }
        //排序
        if(StringUtil.isEmpty(crmLeadPagination.getSidx())){
                wrapper.orderByDesc(CrmLeadEntity::getLeadId);
        }else{
            try {
                String[] split = crmLeadPagination.getSidx().split(",");
                for(String sidx:split){
                CrmLeadEntity crmLeadEntity = new CrmLeadEntity();
                    String oderTableField = crmLeadEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = crmLeadEntity.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 CrmLeadEntity getInfo(String leadid){
        MPJLambdaWrapper<CrmLeadEntity> wrapper = JoinWrappers
                .lambda("crm_lead",CrmLeadEntity.class)
                .selectAll(CrmLeadEntity.class);
        wrapper.and(
            t->t.eq(CrmLeadEntity::getLeadId, leadid )
            .or().eq(CrmLeadEntity::getFlowTaskId, leadid)
        );
        return this.selectJoinOne(CrmLeadEntity.class,wrapper);
    }
    @Override
    public void create(CrmLeadEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String leadid, CrmLeadEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(CrmLeadEntity entity){
        if(entity!=null){
            this.removeById(entity.getLeadId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(CrmLeadForm form,int i) {
        List<String> flowIds = generaterSwapUtil.getFlowIds(form.getFlowId());
        boolean isUp =StringUtil.isNotEmpty(form.getLeadId()) && !form.getLeadId().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.getLeadId();
        }
        //主表字段验证
            fieldTipName =  "线索名称"; 
                if(StringUtil.isEmpty(form.getLeadName())){
                    return fieldTipName + canNotNull;
                }
            fieldTipName =  "手机号"; 
                if(StringUtil.isEmpty(form.getMobile())){
                    return fieldTipName + canNotNull;
                }
                if(StringUtil.isNotEmpty(form.getMobile())){
                    form.setMobile(form.getMobile().trim());
                    QueryWrapper<CrmLeadEntity> mobileWrapper=new QueryWrapper<>();
                    mobileWrapper.lambda().eq(CrmLeadEntity::getMobile,form.getMobile());
                        mobileWrapper.lambda().in(CrmLeadEntity::getFlowId, flowIds);
                        //假删除标志
                        mobileWrapper.lambda().isNull(CrmLeadEntity::getDeleteMark);
                    if (isUp){
                        mobileWrapper.lambda().ne(CrmLeadEntity::getLeadId, id);
                    }
                    if((int) this.count(mobileWrapper)>0){
                        countRecover = fieldTipName + canNotRepeated;
                    }
                }
        if(StringUtil.isNotEmpty(form.getMobile())){
            if(!Pattern.compile("^1[3456789]\\d{9}$").matcher(String.valueOf(form.getMobile())).matches()){
            return I18nUtil.getMessageStr("sys.validate.mobilePhone", "请输入正确的手机号码"); 
            }
        }
            fieldTipName =  "邮箱"; 
        if(StringUtil.isNotEmpty(form.getEmail())){
            if(!Pattern.compile("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$").matcher(String.valueOf(form.getEmail())).matches()){
            return I18nUtil.getMessageStr("sys.validate.email", "请输入正确的邮箱"); 
            }
        }
            fieldTipName =  "状态"; 
            fieldTipName =  "销售人员"; 
            fieldTipName =  "来源"; 
            fieldTipName =  "备注"; 
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param crmLeadForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(CrmLeadForm crmLeadForm,String id, boolean isSave) throws Exception{
        List<Map<String, Object>> formOperates = crmLeadForm.getFormOperates();
        List<String> hasOperate = new ArrayList<>();
        boolean noOperate = false;
        if(CollectionUtils.isNotEmpty(formOperates)){
            for (Map<String, Object> formOperate : formOperates) {
                String formOperateId = formOperate.get("id").toString();
                boolean formOperateWrite = formOperate.get("write") ==null? false : (boolean) formOperate.get("write");
                if(formOperateWrite){
                    hasOperate.add(formOperateId);
                }
            }
        }else{
            noOperate = true;
        }
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        crmLeadForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(CrmLeadConstant.getFormData(),crmLeadForm,CrmLeadConstant.TABLERENAMES),CrmLeadForm.class);
        CrmLeadEntity entity = JsonUtil.getJsonToBean(crmLeadForm, CrmLeadEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        entity.setFlowId(crmLeadForm.getFlowId());
        if(isSave){
            entity.setFlowTaskId(mainUuid);
            entity.setLeadId(mainUuid);
            entity.setVersion(0);
        } else {
        }
        boolean b = this.saveOrUpdate(entity);
        if(!b){
            throw new DataException("当前表单原数据已被调整，请重新进入该页面编辑并提交数据");
        }
    CrmLeadEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

    }
}
