package org.dromara.main.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.main.domain.MainAudit;
import org.dromara.main.domain.MainCompanyApply;
import org.dromara.main.domain.bo.MainCompanyApplyBo;
import org.dromara.main.domain.dto.GeoPointDto;
import org.dromara.main.domain.vo.MainCompanyApplyVo;
import org.dromara.main.mapper.MainAuditMapper;
import org.dromara.main.mapper.MainCompanyApplyMapper;
import org.dromara.main.service.CompanyGeoService;
import org.dromara.main.service.IMainCompanyApplyService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

@RequiredArgsConstructor
@Service
public class MainCompanyApplyServiceImpl implements IMainCompanyApplyService {

    private final MainCompanyApplyMapper baseMapper;
    private final MainAuditMapper mainAuditMapper;
    private final CompanyGeoService companyGeoService;

    @Override
    public TableDataInfo<MainCompanyApplyVo> queryPageList(MainCompanyApplyBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<MainCompanyApply> lqw = buildQueryWrapper(bo);
        Page<MainCompanyApplyVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<MainCompanyApplyVo> queryList(MainCompanyApplyBo bo) {
        LambdaQueryWrapper<MainCompanyApply> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public MainCompanyApplyVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    @Override
    public Boolean insertByBo(MainCompanyApplyBo bo) {
        MainCompanyApply add = MapstructUtils.convert(bo, MainCompanyApply.class);
        fillGeoPoint(add);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    @Override
    public Boolean updateByBo(MainCompanyApplyBo bo) {
        MainCompanyApply update = MapstructUtils.convert(bo, MainCompanyApply.class);
        fillGeoPoint(update);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public boolean checkCompanyNameUnique(MainCompanyApplyBo bo) {
        LambdaQueryWrapper<MainCompanyApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(MainCompanyApply::getCompanyName, bo.getCompanyName());
        lqw.ne(bo.getId() != null, MainCompanyApply::getId, bo.getId());
        return baseMapper.selectCount(lqw) == 0;
    }

    @Override
    public boolean checkCreditCodeUnique(MainCompanyApplyBo bo) {
        LambdaQueryWrapper<MainCompanyApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(MainCompanyApply::getCreditCode, bo.getCreditCode());
        lqw.ne(bo.getId() != null, MainCompanyApply::getId, bo.getId());
        return baseMapper.selectCount(lqw) == 0;
    }

    @Override
    public boolean checkMobileUnique(MainCompanyApplyBo bo) {
        LambdaQueryWrapper<MainCompanyApply> lqw = Wrappers.lambdaQuery();
        lqw.eq(MainCompanyApply::getMobile, bo.getMobile());
        lqw.ne(bo.getId() != null, MainCompanyApply::getId, bo.getId());
        return baseMapper.selectCount(lqw) == 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean applyCompany(MainCompanyApplyBo bo) {
        String smsKey = GlobalConstants.CAPTCHA_CODE_KEY + bo.getMobile();
        String cachedCode = RedisUtils.getCacheObject(smsKey);
        if (StringUtils.isBlank(cachedCode)) {
            throw new ServiceException("验证码已过期，请重新获取");
        }
        if (!StringUtils.equals(cachedCode, bo.getSmsCode())) {
            throw new ServiceException("验证码错误");
        }
        RedisUtils.deleteObject(smsKey);

        if (!checkCompanyNameUnique(bo)) {
            throw new ServiceException("企业名称已存在");
        }
        if (!checkCreditCodeUnique(bo)) {
            throw new ServiceException("统一社会信用代码已存在");
        }
        if (!checkMobileUnique(bo)) {
            throw new ServiceException("联系人手机号已被使用");
        }

        MainCompanyApply apply = new MainCompanyApply();
        apply.setApplyNo(generateApplyNo());
        apply.setCompanyName(bo.getCompanyName());
        apply.setOfficialAccount(bo.getOfficialAccount());
        apply.setOfficeAddress(bo.getOfficeAddress());
        apply.setCreditCode(bo.getCreditCode());
        apply.setSurname(bo.getSurname());
        apply.setName(bo.getName());
        apply.setMobile(bo.getMobile());
        apply.setApplyStatus(0);
        apply.setAuthLetter(parseFirstOssId(bo.getAuthLetter()));
        apply.setAvatar(parseFirstOssId(bo.getAvatar()));
        fillGeoPoint(apply);

        validEntityBeforeSave(apply);
        boolean insertResult = baseMapper.insert(apply) > 0;
        if (insertResult) {
            MainAudit audit = new MainAudit();
            audit.setAuditType(1);
            audit.setTargetId(apply.getId());
            audit.setAuditResult(0);
            mainAuditMapper.insert(audit);

            apply.setAuditId(audit.getId());
            baseMapper.updateById(apply);
        }
        return insertResult;
    }

    private LambdaQueryWrapper<MainCompanyApply> buildQueryWrapper(MainCompanyApplyBo bo) {
        LambdaQueryWrapper<MainCompanyApply> lqw = Wrappers.lambdaQuery();
        lqw.like(ObjectUtil.isNotNull(bo.getApplyNo()), MainCompanyApply::getApplyNo, bo.getApplyNo());
        lqw.like(ObjectUtil.isNotNull(bo.getCompanyName()), MainCompanyApply::getCompanyName, bo.getCompanyName());
        lqw.eq(ObjectUtil.isNotNull(bo.getCreditCode()), MainCompanyApply::getCreditCode, bo.getCreditCode());
        lqw.eq(ObjectUtil.isNotNull(bo.getApplyStatus()), MainCompanyApply::getApplyStatus, bo.getApplyStatus());
        lqw.eq(ObjectUtil.isNotNull(bo.getMobile()), MainCompanyApply::getMobile, bo.getMobile());
        lqw.orderByDesc(MainCompanyApply::getCreateTime);
        return lqw;
    }

    private void validEntityBeforeSave(MainCompanyApply entity) {
    }

    private String generateApplyNo() {
        String dateStr = cn.hutool.core.date.DateUtil.format(cn.hutool.core.date.DateUtil.date(), "yyyyMMdd");
        return "AP" + dateStr + RandomUtil.randomNumbers(6);
    }

    private Long parseFirstOssId(String rawValue) {
        if (StringUtils.isBlank(rawValue)) {
            return null;
        }
        String first = rawValue.split(",")[0].trim();
        if (StringUtils.isBlank(first)) {
            return null;
        }
        try {
            return Long.valueOf(first);
        } catch (NumberFormatException ex) {
            throw new ServiceException("上传文件标识格式错误");
        }
    }

    private void fillGeoPoint(MainCompanyApply entity) {
        GeoPointDto geoPoint = companyGeoService.geocode(entity.getOfficeAddress());
        entity.setLatitude(geoPoint.getLatitude());
        entity.setLongitude(geoPoint.getLongitude());
    }
}
