
package com.yunzhupaas.mdm.service.impl;

import com.yunzhupaas.mdm.entity.*;
import com.yunzhupaas.mdm.mapper.CompanyMapper;
import com.yunzhupaas.mdm.service.*;
import com.yunzhupaas.mdm.model.custinfo.*;
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.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 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 org.springframework.transaction.annotation.Transactional;
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 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-24
 */
@Service
public class CustinfoServiceImpl extends SuperServiceImpl<CompanyMapper, CompanyEntity> implements CustinfoService{
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;
    @Autowired
    private UserProvider userProvider;
    @Autowired
	private  CustomerService customerService;
    @Autowired
    private CompanyInvoiceService companyInvoiceService;
    @Autowired
    private CompanyBankService companyBankService;
    @Override
    public List<CompanyEntity> getList(CustinfoPagination companyPagination){
        return getTypeList(companyPagination,companyPagination.getDataType());
    }
    /** 列表查询 */
    @Override
    public List<CompanyEntity> getTypeList(CustinfoPagination companyPagination,String dataType){
        String userId=userProvider.get().getUserId();
        Map<String,Class> tableClassMap=new HashMap<>();
        tableClassMap.put("mdm_company",CompanyEntity.class);
        tableClassMap.put("mdm_company_bank",CompanyBankEntity.class);
        tableClassMap.put("mdm_company_invoice",CompanyInvoiceEntity.class);
        tableClassMap.put("mdm_customer",CustomerEntity.class);

        MPJLambdaWrapper<CompanyEntity> wrapper = JoinWrappers
                .lambda("mdm_company",CompanyEntity.class)
                .selectCollection(CompanyBankEntity.class,CompanyEntity::getCompanyBank)
                .leftJoin(CompanyBankEntity.class,"mdm_company_bank",CompanyBankEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectCollection(CompanyInvoiceEntity.class,CompanyEntity::getCompanyInvoice)
                .leftJoin(CompanyInvoiceEntity.class,"mdm_company_invoice",CompanyInvoiceEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectAssociation(CustomerEntity.class,CompanyEntity::getCustomer)
                .leftJoin(CustomerEntity.class,"mdm_customer",CustomerEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectAll(CompanyEntity.class);
        MPJLambdaWrapper<CompanyEntity> wrapper2 = JoinWrappers
                .lambda("mdm_company",CompanyEntity.class)
                .leftJoin(CompanyBankEntity.class,"mdm_company_bank",CompanyBankEntity::getCompanyId,CompanyEntity::getCompanyId)
                .leftJoin(CompanyInvoiceEntity.class,"mdm_company_invoice",CompanyInvoiceEntity::getCompanyId,CompanyEntity::getCompanyId)
                .leftJoin(CustomerEntity.class,"mdm_customer",CustomerEntity::getCompanyId,CompanyEntity::getCompanyId)
                .distinct().select(CompanyEntity::getCompanyId);

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

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

    }

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

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

        }
        //排序
        if(StringUtil.isEmpty(companyPagination.getSidx())){
                wrapper.orderByDesc(CompanyEntity::getCompanyId);
        }else{
            try {
                String[] split = companyPagination.getSidx().split(",");
                for(String sidx:split){
                CompanyEntity companyEntity = new CompanyEntity();
                    String oderTableField = companyEntity.getClass().getAnnotation(TableName.class).value();
                    boolean descFlag = sidx.startsWith("-");
                    String sidxField = descFlag ? sidx.substring(1) : sidx;
                    try{
                        Field declaredField = companyEntity.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 CompanyEntity getInfo(String companyid){
        MPJLambdaWrapper<CompanyEntity> wrapper = JoinWrappers
                .lambda("mdm_company",CompanyEntity.class)
                .selectCollection(CompanyBankEntity.class,CompanyEntity::getCompanyBank)
                .leftJoin(CompanyBankEntity.class,"mdm_company_bank",CompanyBankEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectCollection(CompanyInvoiceEntity.class,CompanyEntity::getCompanyInvoice)
                .leftJoin(CompanyInvoiceEntity.class,"mdm_company_invoice",CompanyInvoiceEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectAssociation(CustomerEntity.class,CompanyEntity::getCustomer)
                .leftJoin(CustomerEntity.class,"mdm_customer",CustomerEntity::getCompanyId,CompanyEntity::getCompanyId)
                .selectAll(CompanyEntity.class);
        wrapper.and(
            t->t.eq(CompanyEntity::getCompanyId, companyid )
            .or().eq(CompanyEntity::getFlowTaskId, companyid)
        );
        return this.selectJoinOne(CompanyEntity.class,wrapper);
    }
    @Override
    public void create(CompanyEntity entity){
        this.save(entity);
    }
    @Override
    public boolean update(String companyid, CompanyEntity entity){
        return this.updateById(entity);
    }
    @Override
    public void delete(CompanyEntity entity){
        if(entity!=null){
            this.removeById(entity.getCompanyId());
        }
    }
    /** 验证表单唯一字段，正则，非空 i-0新增-1修改*/
    @Override
    public String checkForm(CustinfoForm form,int i) {
        boolean isUp =StringUtil.isNotEmpty(form.getCompanyId()) && !form.getCompanyId().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.getCompanyId();
        }
        //主表字段验证
            fieldTipName =  "客户编码"; 
            fieldTipName =  "客户名称"; 
                if(StringUtil.isEmpty(form.getCompanyName())){
                    return fieldTipName + canNotNull;
                }
                if(StringUtil.isNotEmpty(form.getCompanyName())){
                    form.setCompanyName(form.getCompanyName().trim());
                    QueryWrapper<CompanyEntity> company_nameWrapper=new QueryWrapper<>();
                    company_nameWrapper.lambda().eq(CompanyEntity::getCompanyName,form.getCompanyName());
                        company_nameWrapper.lambda().isNull(CompanyEntity::getFlowId);
                    if (isUp){
                        company_nameWrapper.lambda().ne(CompanyEntity::getCompanyId, id);
                    }
                    if((int) this.count(company_nameWrapper)>0){
                        countRecover = fieldTipName + canNotRepeated;
                    }
                }
            fieldTipName =  "简称/昵称"; 
            fieldTipName =  "类型"; 
            fieldTipName =  "社会信用代码"; 
                if(StringUtil.isEmpty(form.getCreditCode())){
                    return fieldTipName + canNotNull;
                }
                if(StringUtil.isNotEmpty(form.getCreditCode())){
                    form.setCreditCode(form.getCreditCode().trim());
                    QueryWrapper<CompanyEntity> credit_codeWrapper=new QueryWrapper<>();
                    credit_codeWrapper.lambda().eq(CompanyEntity::getCreditCode,form.getCreditCode());
                        credit_codeWrapper.lambda().isNull(CompanyEntity::getFlowId);
                    if (isUp){
                        credit_codeWrapper.lambda().ne(CompanyEntity::getCompanyId, id);
                    }
                    if((int) this.count(credit_codeWrapper)>0){
                        countRecover = fieldTipName + canNotRepeated;
                    }
                }
            fieldTipName =  "归属组织"; 
            fieldTipName =  "所属地区"; 
            fieldTipName =  "纳税人类别"; 
            fieldTipName =  "企业规模"; 
            fieldTipName =  "企业类型"; 
            fieldTipName =  "行业代码"; 
            fieldTipName =  "成立日期"; 
            fieldTipName =  "注册资本"; 
            fieldTipName =  "法定代表人"; 
            fieldTipName =  "联系电话"; 
        if(StringUtil.isNotEmpty(form.getPhone())){
            if(!Pattern.compile("^1[3456789]\\d{9}$|^0\\d{2,3}-?\\d{7,8}$").matcher(String.valueOf(form.getPhone())).matches()){
            return I18nUtil.getMessageStr("sys.validate.telephone", "请输入正确的电话号码"); 
            }
        }
            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 =  "备注"; 
        //副表字段验证
                fieldTipName =  "销售责任人"; 
                if( form.getYunzhupaas_customer_yunzhupaas_personId() == null ){
                    return fieldTipName + canNotNull;
                }
                fieldTipName =  "客户级别"; 
                fieldTipName =  "客户来源"; 
        //子表字段验证
            if (form.getCompanyInvoiceList()!=null){

                    fieldTipName =  "设计子表" 
                            + "-" +  "发票抬头编码"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "发票抬头名称"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "纳税人识别号"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "纳税人类别"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "地址"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "电话"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "开户银行"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "银行账户"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "是否默认"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "是否有效"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "备注"; 

            }
            if (form.getCompanyBankList()!=null){

                    fieldTipName =  "设计子表" 
                            + "-" +  "开户行"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "账户名"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "银行账号"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "开户行城市"; 


                    fieldTipName =  "设计子表" 
                            + "-" +  "备注"; 

            }
        return countRecover;
    }
    /**
    * 新增修改数据(事务回滚)
    * @param id
    * @param companyForm
    * @return
    */
    @Override
    @Transactional
    public void saveOrUpdate(CustinfoForm companyForm,String id, boolean isSave) throws Exception{
        UserInfo userInfo=userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        companyForm = JsonUtil.getJsonToBean(
        generaterSwapUtil.swapDatetime(CustinfoConstant.getFormData(),companyForm,CustinfoConstant.TABLERENAMES),CustinfoForm.class);
        CompanyEntity entity = JsonUtil.getJsonToBean(companyForm, CompanyEntity.class);
        String mainUuid = StringUtil.isEmpty(id) ? RandomUtil.uuId() : id;
        if(isSave){
            entity.setFlowTaskId(mainUuid);
                        entity.setCompanyCode(generaterSwapUtil.getBillNumber("companyCode", false));
            entity.setCompanyId(mainUuid);
        } else {
                    if(StringUtil.isEmpty(entity.getCompanyCode()) ){
                        entity.setCompanyCode(generaterSwapUtil.getBillNumber("companyCode", false));
                    }
        }
        boolean b = this.saveOrUpdate(entity);
    CompanyEntity info = this.getInfo(mainUuid);
    if (info == null) throw new RuntimeException(MsgCode.FA001.get());

        //CompanyInvoice子表数据新增修改
        QueryWrapper<CompanyInvoiceEntity> CompanyInvoicequeryWrapper = new QueryWrapper<>();
        CompanyInvoicequeryWrapper.lambda().eq(CompanyInvoiceEntity::getCompanyId, info.getCompanyId());
        if(!isSave && !CollectionUtils.isNotEmpty(companyForm.getCompanyInvoiceList())){
            companyInvoiceService.remove(CompanyInvoicequeryWrapper);
        }
        if (CollectionUtils.isNotEmpty(companyForm.getCompanyInvoiceList())){
            List<CompanyInvoiceEntity> tableField46dc53 = JsonUtil.getJsonToList(companyForm.getCompanyInvoiceList(),CompanyInvoiceEntity.class);
            //移除的数据
            List<Object> childIds = tableField46dc53.stream().filter(t->t.getInvoiceId()!=null).map(CompanyInvoiceEntity::getInvoiceId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                CompanyInvoicequeryWrapper.lambda().notIn(CompanyInvoiceEntity::getInvoiceId,childIds);
            }
            companyInvoiceService.remove(CompanyInvoicequeryWrapper);
            for(CompanyInvoiceEntity entitys : tableField46dc53){
                entitys.setCompanyId(entity.getCompanyId());
                if(isSave || entitys.getInvoiceId()==null){
                        entitys.setTitleCode(generaterSwapUtil.getBillNumber("InvoiceTitleCode", false));
                }else{
                    if(StringUtil.isEmpty(entitys.getTitleCode()) || entitys.getInvoiceId() == null ){
                        entitys.setTitleCode(generaterSwapUtil.getBillNumber("InvoiceTitleCode", false));
                    }
                }
                if(entitys.getInvoiceId()==null){
                    entitys.setInvoiceId(RandomUtil.uuId());
                }
                companyInvoiceService.saveOrUpdate(entitys);
            }
        }
        //CompanyBank子表数据新增修改
        QueryWrapper<CompanyBankEntity> CompanyBankqueryWrapper = new QueryWrapper<>();
        CompanyBankqueryWrapper.lambda().eq(CompanyBankEntity::getCompanyId, info.getCompanyId());
        if(!isSave && !CollectionUtils.isNotEmpty(companyForm.getCompanyBankList())){
            companyBankService.remove(CompanyBankqueryWrapper);
        }
        if (CollectionUtils.isNotEmpty(companyForm.getCompanyBankList())){
            List<CompanyBankEntity> tableFieldad9d92 = JsonUtil.getJsonToList(companyForm.getCompanyBankList(),CompanyBankEntity.class);
            //移除的数据
            List<Object> childIds = tableFieldad9d92.stream().filter(t->t.getBankId()!=null).map(CompanyBankEntity::getBankId).collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(childIds)){
                CompanyBankqueryWrapper.lambda().notIn(CompanyBankEntity::getBankId,childIds);
            }
            companyBankService.remove(CompanyBankqueryWrapper);
            for(CompanyBankEntity entitys : tableFieldad9d92){
                entitys.setCompanyId(entity.getCompanyId());
                if(entitys.getBankId()==null){
                    entitys.setBankId(RandomUtil.uuId());
                }
                companyBankService.saveOrUpdate(entitys);
            }
        }
        //mdm_customer副表数据新增修改
        Map<String, Object> CustomerMap = generaterSwapUtil.getMastTabelData(companyForm,"mdm_customer");
        CustomerEntity  customerentity = JsonUtil.getJsonToBean(CustomerMap,CustomerEntity.class);
        //自动生成的字段
        if(isSave){
            customerentity.setCustomerId(RandomUtil.uuId());
            customerentity.setCompanyId(entity.getCompanyId());
        }else{
            QueryWrapper<CustomerEntity> queryWrapperCustomer =new QueryWrapper<>();
            queryWrapperCustomer.lambda().eq(CustomerEntity::getCompanyId,info.getCompanyId());
            CustomerEntity customerOneEntity= customerService.getOne(queryWrapperCustomer);
            customerentity.setCustomerId(customerOneEntity.getCustomerId());
            customerentity.setCompanyId(entity.getCompanyId());
        }

        customerService.saveOrUpdate(customerentity);
    }
}
