package org.dromara.elevator.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.mybatis.helper.DataBaseHelper;
import org.dromara.elevator.constant.ElevatorConstant;
import org.dromara.elevator.domain.EElevatorInfo;
import org.dromara.elevator.mapper.EElevatorInfoMapper;
import org.dromara.system.domain.SysDept;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.mapper.SysDeptMapper;
import org.dromara.system.service.ISysConfigService;
import org.dromara.system.service.ISysOssService;
import org.springframework.stereotype.Service;
import org.dromara.elevator.domain.bo.ERelevancyCodeBo;
import org.dromara.elevator.domain.vo.ERelevancyCodeVo;
import org.dromara.elevator.domain.ERelevancyCode;
import org.dromara.elevator.mapper.ERelevancyCodeMapper;
import org.dromara.elevator.service.IERelevancyCodeService;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.Objects;

/**
 * 电梯二维码关联信息;Service业务层处理
 *
 * @author zy
 * @date 2024-07-31
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ERelevancyCodeServiceImpl implements IERelevancyCodeService {

    private final ERelevancyCodeMapper baseMapper;
    private final SysDeptMapper deptMapper;
    private final WxMaService wxMaService;
    private final EElevatorInfoMapper elevatorInfoMapper;
    private final ISysOssService ossService;
    private final ISysConfigService sysConfigService;

    /**
     * 查询电梯二维码关联信息;
     *
     * @param id 主键
     * @return 电梯二维码关联信息;
     */
    @Override
    public ERelevancyCodeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询电梯二维码关联信息;列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 电梯二维码关联信息;分页列表
     */
    @Override
    public TableDataInfo<ERelevancyCodeVo> queryPageList(ERelevancyCodeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ERelevancyCode> lqw = buildQueryWrapper(bo);
        Page<ERelevancyCodeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的电梯二维码关联信息;列表
     *
     * @param bo 查询条件
     * @return 电梯二维码关联信息;列表
     */
    @Override
    public List<ERelevancyCodeVo> queryList(ERelevancyCodeBo bo) {
        LambdaQueryWrapper<ERelevancyCode> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ERelevancyCode> buildQueryWrapper(ERelevancyCodeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ERelevancyCode> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getRegisterCode()), ERelevancyCode::getRegisterCode, bo.getRegisterCode());
        lqw.eq(StringUtils.isNotBlank(bo.getElevatorNum()), ERelevancyCode::getElevatorNum, bo.getElevatorNum());
        lqw.eq(StringUtils.isNotBlank(bo.getQrCode()), ERelevancyCode::getQrCode, bo.getQrCode());
        lqw.like(StringUtils.isNotBlank(bo.getElevatorName()), ERelevancyCode::getElevatorName, bo.getElevatorName());
        lqw.eq(StringUtils.isNotBlank(bo.getElevatorAddress()), ERelevancyCode::getElevatorAddress, bo.getElevatorAddress());
        lqw.eq(bo.getStartTime() != null, ERelevancyCode::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, ERelevancyCode::getEndTime, bo.getEndTime());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectId()), ERelevancyCode::getProjectId, bo.getProjectId());
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), ERelevancyCode::getProjectName, bo.getProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getContacts()), ERelevancyCode::getContacts, bo.getContacts());
        lqw.eq(StringUtils.isNotBlank(bo.getContactsPhone()), ERelevancyCode::getContactsPhone, bo.getContactsPhone());
        lqw.eq(StringUtils.isNotBlank(bo.getRelevancyAccount()), ERelevancyCode::getRelevancyAccount, bo.getRelevancyAccount());
        lqw.eq(bo.getIsRelevancy() != null, ERelevancyCode::getIsRelevancy, bo.getIsRelevancy());

        lqw.and(ObjectUtil.isNotNull(bo.getDeptId()), w -> {
            List<SysDept> deptList = deptMapper.selectList(new LambdaQueryWrapper<SysDept>()
                .select(SysDept::getDeptId)
                .apply(DataBaseHelper.findInSet(bo.getDeptId(), "ancestors")));
            List<Long> ids = StreamUtils.toList(deptList, SysDept::getDeptId);
            ids.add(bo.getDeptId());
            w.in(ERelevancyCode::getDeptId, ids);
        }).orderByDesc(ERelevancyCode::getCreateTime);

        return lqw;
    }

    /**
     * 新增电梯二维码关联信息;
     *
     * @param bo 电梯二维码关联信息;
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ERelevancyCodeBo bo) {
        ERelevancyCode add = MapstructUtils.convert(bo, ERelevancyCode.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改电梯二维码关联信息;
     *
     * @param bo 电梯二维码关联信息;
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ERelevancyCodeBo bo) {
        ERelevancyCode update = MapstructUtils.convert(bo, ERelevancyCode.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ERelevancyCode entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除电梯二维码关联信息;信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public ERelevancyCodeVo createQrCode(Long id) {
        ERelevancyCode relevancyCode = this.baseMapper.selectById(id);
        if (Objects.isNull(relevancyCode) || StringUtils.isBlank(relevancyCode.getElevatorNum())) {
            return null;
        }
        EElevatorInfo elevatorInfo = elevatorInfoMapper.selectOne(Wrappers.<EElevatorInfo>lambdaQuery()
            .eq(EElevatorInfo::getElevatorNum, relevancyCode.getElevatorNum()).last(" limit 1 "));
        if (Objects.isNull(elevatorInfo)) {
            return null;
        }
        String qrCodePage = sysConfigService.selectConfigByKey(ElevatorConstant.ELE_QRCODE_PAGE_CONFIG_KEY);
        if (StringUtils.isBlank(qrCodePage)) {
            return null;
        }
        try {

            File file = wxMaService.getQrcodeService()
                .createWxaCodeUnlimit(elevatorInfo.getId().toString(), qrCodePage);
            SysOssVo sysOss = ossService.upload(file);
            relevancyCode.setQrCodeUrl(sysOss.getUrl());
            this.baseMapper.updateById(relevancyCode);
        } catch (Exception e) {
            log.error("创建小程序二维码失败:{}", JsonUtils.toJsonString(relevancyCode), e);
            return null;
        }
        return MapstructUtils.convert(relevancyCode, ERelevancyCodeVo.class);
    }
}
