package com.njcn.advance.service.govern.voltage.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.advance.mapper.govern.voltage.SgUserMapper;
import com.njcn.advance.pojo.param.govern.voltage.SgUserParam;
import com.njcn.advance.pojo.po.govern.voltage.SgIncomingLine;
import com.njcn.advance.pojo.po.govern.voltage.SgProductLine;
import com.njcn.advance.pojo.po.govern.voltage.SgUser;
import com.njcn.advance.pojo.vo.govern.voltage.SgUserVO;
import com.njcn.advance.service.govern.voltage.ISgIncomingLineService;
import com.njcn.advance.service.govern.voltage.ISgProductLineService;
import com.njcn.advance.service.govern.voltage.ISgUserService;
import com.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.db.constant.DbConstant;
import com.njcn.advance.enums.AdvanceResponseEnum;
import com.njcn.web.factory.PageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2024-02-29
 */
@Service
@RequiredArgsConstructor
public class SgUserServiceImpl extends ServiceImpl<SgUserMapper, SgUser> implements ISgUserService {

    private final ISgProductLineService productLineService;

    private final ISgIncomingLineService incomingLineService;

    @Override
    public Page<SgUserVO> sgUserList(SgUserParam.SgUserQueryParam sgUserQueryParam) {
        QueryWrapper<SgUserVO> queryWrapper = new QueryWrapper<>();
        //关键字查询，仅支持用户名、行业模糊查询
        if (StrUtil.isNotBlank(sgUserQueryParam.getSearchValue())) {
            queryWrapper
                    .and(param -> param
                            .like("sg_user.user_name", sgUserQueryParam.getSearchValue())
                            .or()
                            .like("sg_user.industry", sgUserQueryParam.getSearchValue()));
        }

        //addr可能是个集合，多选N个区域查询
        if (CollectionUtil.isNotEmpty(sgUserQueryParam.getAddrStrOption())) {
            queryWrapper.in("sg_user.addr", sgUserQueryParam.getAddrStrOption());
        }
        //排序
        if (ObjectUtil.isAllNotEmpty(sgUserQueryParam.getSortBy(), sgUserQueryParam.getOrderBy())) {
            queryWrapper.orderBy(true, sgUserQueryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(sgUserQueryParam.getSortBy()));
        } else {
            //没有排序参数，默认根据sort字段排序，没有排序字段的，根据createTime更新时间排序
            queryWrapper.orderByDesc("sg_user.create_time");
        }
        queryWrapper.eq("sg_user.state", DataStateEnum.ENABLE.getCode());
        Page<SgUserVO> sgUserVOPage = this.baseMapper.page(new Page<>(PageFactory.getPageNum(sgUserQueryParam), PageFactory.getPageSize(sgUserQueryParam)), queryWrapper);
        if (CollectionUtil.isNotEmpty(sgUserVOPage.getRecords())) {
            List<SgUserVO> records = sgUserVOPage.getRecords();
            //获取该用户的生产线数量和进线数量
            for (SgUserVO record : records) {
                LambdaQueryWrapper<SgProductLine> productLineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                productLineLambdaQueryWrapper.eq(SgProductLine::getUserId, record.getId())
                        .eq(SgProductLine::getState, DataStateEnum.ENABLE.getCode());
                record.setProductCount(productLineService.count(productLineLambdaQueryWrapper));
                LambdaQueryWrapper<SgIncomingLine> incomingLineLambdaQueryWrapper = new LambdaQueryWrapper<>();
                incomingLineLambdaQueryWrapper.eq(SgIncomingLine::getUserId, record.getId())
                        .eq(SgIncomingLine::getState, DataStateEnum.ENABLE.getCode());
                record.setLineCount(incomingLineService.count(incomingLineLambdaQueryWrapper));
            }
        }

        return sgUserVOPage;
    }

    /**
     * 新增业务用户数据
     *
     * @param sgUserParam 业务用户数据
     */
    @Override
    public String addUserInfo(SgUserParam sgUserParam) {
        checkSgUserName(sgUserParam, false);
        SgUser sgUser = new SgUser();
        BeanUtil.copyProperties(sgUserParam, sgUser);
        //默认为正常状态
        sgUser.setState(DataStateEnum.ENABLE.getCode());
        sgUser.setAddr(sgUserParam.getAddrStrOption());
        this.save(sgUser);
        return sgUser.getId();
    }

    /**
     * 更新业务用户数据
     *
     * @param updateParam 待更新的业务用户数据
     */
    @Override
    public boolean updateSgUser(SgUserParam.SgUserUpdateParam updateParam) {
        checkSgUserName(updateParam, true);
        SgUser sgUser = new SgUser();
        BeanUtil.copyProperties(updateParam, sgUser);
        sgUser.setAddr(updateParam.getAddrStrOption());
        return this.updateById(sgUser);
    }

    /**
     * 逻辑删除所有指定的业务用户
     *
     * @param ids 用户id集合
     */
    @Override
    public boolean deleteSgUserData(List<String> ids) {
        LambdaQueryWrapper<SgProductLine> sgProductLineLambdaQueryWrapper;
        for (String id : ids) {
            sgProductLineLambdaQueryWrapper = new LambdaQueryWrapper<>();
            sgProductLineLambdaQueryWrapper.eq(SgProductLine::getUserId, id)
                    .eq(SgProductLine::getState, DataStateEnum.ENABLE.getCode());
            int count = productLineService.count(sgProductLineLambdaQueryWrapper);
            if (count > 0) {
                throw new BusinessException(AdvanceResponseEnum.USER_HAS_PRODUCT);
            } else {
                this.lambdaUpdate().set(SgUser::getState, DataStateEnum.DELETED.getCode())
                        .eq(SgUser::getId, id)
                        .update();
            }

        }
        return true;
    }

    @Override
    public List<SgUser> sgUserAllList() {
        LambdaQueryWrapper<SgUser> sgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sgUserLambdaQueryWrapper
                .eq(SgUser::getState, DataStateEnum.ENABLE.getCode())
                .orderByDesc(SgUser::getCreateTime);
        return this.list(sgUserLambdaQueryWrapper);
    }

    /**
     * 校验参数，检查是否存在相同名称的业务用户
     */
    private void checkSgUserName(SgUserParam sgUserParam, boolean isExcludeSelf) {
        LambdaQueryWrapper<SgUser> sgUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        sgUserLambdaQueryWrapper
                .eq(SgUser::getUserName, sgUserParam.getUserName())
                .eq(SgUser::getState, DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if (isExcludeSelf) {
            if (sgUserParam instanceof SgUserParam.SgUserUpdateParam) {
                sgUserLambdaQueryWrapper.ne(SgUser::getId, ((SgUserParam.SgUserUpdateParam) sgUserParam).getId());
            }
        }
        int countByAccount = this.count(sgUserLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new BusinessException(AdvanceResponseEnum.SG_USER_NAME_REPEAT);
        }
    }
}
