package com.junmp.jyzb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.api.bean.query.ApplicationReq;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.CabinetExceptionEnum;
import com.junmp.jyzb.api.exception.enums.PublicExceptionEnum;
import com.junmp.jyzb.entity.Application;
import com.junmp.jyzb.service.ApplicationService;
import com.junmp.jyzb.mapper.ApplicationMapper;
import com.junmp.jyzb.utils.DateTimeUtil;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import com.junmp.v2.db.api.factory.PageFactory;
import com.junmp.v2.db.api.factory.PageResultFactory;
import com.junmp.v2.db.api.page.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author lxh专属坐骑
* @description 针对表【sys_application】的数据库操作Service实现
* @createDate 2023-09-11 14:59:13
*/
@Service
public class ApplicationServiceImpl extends ServiceImpl<ApplicationMapper, Application>
    implements ApplicationService{


    @Resource
    private ApplicationMapper applicationMapper;

    //获取应用的分页信息
    @Override
    public PageResult<Application> GetAllUpdateCfg(ApplicationReq req) {
        LambdaQueryWrapper<Application> wrapper = createWrapper(req);
        Page<Application> page = page(PageFactory.getDefaultPage(req.getPageNo(), req.getPageSize()), wrapper);
        return PageResultFactory.createPageResult(page);
    }

    //获取应用信息的列表
    public List<Application> GetAllUpdateCfgList(ApplicationReq req) {
        LambdaQueryWrapper<Application> wrapper = createWrapper(req);
        list(wrapper);
        return list(wrapper);
    }

    //获取应用信息一个
    public Application GetOne(ApplicationReq req) {
        LambdaQueryWrapper<Application> wrapper = createWrapper(req);
        Application one = getOne(wrapper);
        return ObjectUtil.isNull(one)?new Application():one;
    }

    //新增或者修改应用信息
    @Override
    public String AddOrUpdateCfg(ApplicationReq req) {
        Application application = new Application();
        BeanPlusUtil.copyProperties(req,application);

        List<Application> list = list(new LambdaQueryWrapper<Application>()
                .eq(Application::getAppCode, req.getAppCode()).or().eq(Application::getName,req.getName()));

        //判断id是否传递，如果传递则默认他是修改，根据数据库对比id，判断是否id传递错误；如果不传递默认新增
        if (req.getId()==null || req.getId().trim().isEmpty()){
            //判断应用代码和应用名称是否重复，如果重复直接抛出异常
            if (CollectionUtil.isNotEmpty(list)){
                for (Application app:list) {
                    if (app.getName().equals(req.getName())){
                        throw new ServiceException(PublicExceptionEnum.APP_NAME_IS_EXIST);
                    }
                    if (app.getAppCode().equals(req.getAppCode())){
                        throw new ServiceException(PublicExceptionEnum.APP_CODE_IS_EXIST);
                    }
                }
            }
            application.setCreateTime(DateTimeUtil.getCurrentDateTime());
            save(application);
            return application.getId();
        }else {

            for (Application app:list) {
                if (!req.getId().equals(app.getId())){
                    if (app.getName().equals(req.getName())){
                        throw new ServiceException(PublicExceptionEnum.APP_NAME_IS_EXIST);
                    }
                    if (app.getAppCode().equals(req.getAppCode())){
                        throw new ServiceException(PublicExceptionEnum.APP_CODE_IS_EXIST);
                    }
                }
            }
            application.setUpdateTime(DateTimeUtil.getCurrentDateTime());
            updateById(application);
            return application.getId();
        }

    }

    //删除一个或者多个应用信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean delConfig(ApplicationReq req) {
        if (CollectionUtil.isEmpty(req.getIdsList())){
            throw new ServiceException(CabinetExceptionEnum.PARAMETER_ERROR);
        }
        List<Application> list = list(new LambdaQueryWrapper<Application>().in(Application::getId, req.getIdsList()));
        List<String> nonexistentApp = new ArrayList<>();
        for (String appId:req.getIdsList()) {
            boolean flag=false;
            for (Application app:list) {
                if (appId.equals(app.getId())){
                    flag=true;
                    break;
                }

            }
            if (!flag){
                nonexistentApp.add(appId);
            }
        }
        if (CollectionUtil.isNotEmpty(nonexistentApp)){
            String msg="以下应用不存在：" +String.join(",", nonexistentApp);
            throw new JYZBAppException(PublicExceptionEnum.APP_IS_NOT_EXIST, msg);
        }else {

            return removeBatchByIds(req.getIdsList());
        }

    }


    private LambdaQueryWrapper<Application> createWrapper(ApplicationReq req) {
        LambdaQueryWrapper<Application> wrapper = new LambdaQueryWrapper<>();
        if (ObjectUtil.isEmpty(req)) {
            return wrapper;
        }
        wrapper.like(ObjectUtil.isNotEmpty(req.getName()),Application::getName,req.getName());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getType()),Application::getType,req.getType());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getId()),Application::getId,req.getId());
        wrapper.eq(ObjectUtil.isNotEmpty(req.getAppCode()),Application::getAppCode,req.getAppCode());
        wrapper.orderByDesc(Application::getCreateTime);
        return wrapper;

    }
}




