package com.fuint.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuint.common.dto.ext.CountryDto;
import com.fuint.framework.annoation.OperationServiceLog;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.framework.exception.BusinessRuntimeException;
import com.fuint.framework.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.repository.model.MtCountry;
import com.fuint.common.service.CountryService;
import com.fuint.common.enums.StatusEnum;
import com.fuint.repository.mapper.MtCountryMapper;
import com.github.pagehelper.PageHelper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;

/**
 * 国家表服务接口
 *
 * Created by pzg
 * CopyRight https://www.fuint.cn
 */
@Service
@AllArgsConstructor
public class CountryServiceImpl extends ServiceImpl<MtCountryMapper, MtCountry> implements CountryService {

    private static final Logger logger = LoggerFactory.getLogger(CountryServiceImpl.class);

    private MtCountryMapper mtCountryMapper;

    /**
     * 分页查询数据列表
     *
     * @param paginationRequest
     * @return
     */
    @Override
    public PaginationResponse<MtCountry> queryCountryListByPagination(PaginationRequest paginationRequest) {
        Page<MtCountry> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        LambdaQueryWrapper<MtCountry> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.ne(MtCountry::getDeleteFlag, 0);

        lambdaQueryWrapper.orderByAsc(MtCountry::getId);
        List<MtCountry> dataList = mtCountryMapper.selectList(lambdaQueryWrapper);

        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dataList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtCountry> paginationResponse = new PaginationResponse(pageImpl, MtCountry.class);
        paginationResponse.setTotalPages(pageHelper.getPages());
        paginationResponse.setTotalElements(pageHelper.getTotal());
        paginationResponse.setContent(dataList);

        return paginationResponse;
    }

    /**
     * 添加国家表
     *
     * @param mtCountry 国家表信息
     * @return
     */
    @Override
    @OperationServiceLog(description = "新增国家表")
    public MtCountry addCountry(MtCountry mtCountry) throws BusinessCheckException {
        mtCountry.setUpdateTime(new Date());
        mtCountry.setCreateTime(new Date());
        Integer id = mtCountryMapper.insert(mtCountry);
        if (id > 0) {
            return mtCountry;
        } else {
            throw new BusinessCheckException("新增国家表数据失败");
        }
    }

    /**
     * 根据ID获国家表取息
     *
     * @param id 国家表ID
     * @return
     */
    @Override
    public MtCountry queryCountryById(Long id) {
        return mtCountryMapper.selectById(id);
    }

    /**
     * 根据ID删除国家表
     *
     * @param id 国家表ID
     * @param operator 操作人
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "删除国家表")
    public void deleteCountry(Long id, String operator) {
        MtCountry mtCountry = queryCountryById(id);
        if (null == mtCountry) {
            return;
        }
        mtCountry.setUpdateTime(new Date());
        mtCountryMapper.updateById(mtCountry);
    }

    /**
     * 修改国家表数据
     *
     * @param countryDto
     * @throws BusinessCheckException
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @OperationServiceLog(description = "更新国家表")
    public boolean updateCountry(CountryDto countryDto, Long accountId) throws BusinessCheckException {
        // 1. 获取原数据
        MtCountry mtCountry = Optional.ofNullable(this.getById(countryDto.getId())).orElseThrow(() ->
                new BusinessRuntimeException("目标记录不存在"));
        // 2. 校验父子关系变更
        validateParentChange(countryDto.getId(), countryDto.getParentId());

        // 3. 构建更新对象
        MtCountry country = new MtCountry();
        BeanUtils.copyProperties(countryDto, country);
        return this.updateById(country);
    }

    private void validateParentChange(Long currentId, Long newParentId) throws BusinessCheckException {
        // 禁止设置自己为父节点
        if (currentId.equals(newParentId)) {
            throw new BusinessCheckException("禁止设置自己为父节点");
        }

        // 检查新父节点是否存在
        if (newParentId != 0L) { // 0表示根节点
            int parentCount = this.baseMapper.checkParentExist(newParentId);
            if (parentCount == 0) {
                throw new BusinessCheckException("新父节点不存在或已被删除");
            }
        }
        // 检查是否形成循环依赖（递归校验）
        checkCircularDependency(currentId, newParentId);
    }

    private void checkCircularDependency(Long currentId, Long checkParentId) throws BusinessCheckException {
        if (checkParentId == 0L) return; // 根节点无需检查

        MtCountry parent = this.getById(checkParentId);
        if (parent == null) return;

        if (currentId.equals(parent.getParentId())) {
            throw new BusinessCheckException("检测到循环依赖");
        }

        // 递归检查父节点的父节点
        checkCircularDependency(currentId, parent.getParentId());
    }
    /**
    * 根据条件搜索国家表
    *
    * @param  params 查询参数
    * @throws BusinessCheckException
    * @return
    * */
    @Override
    public List<MtCountry> queryCountryListByParams(Map<String, Object> params) {
        String status =  params.get("status") == null ? StatusEnum.ENABLED.getKey(): params.get("status").toString();
        String storeId =  params.get("storeId") == null ? "" : params.get("storeId").toString();
        String merchantId =  params.get("merchantId") == null ? "" : params.get("merchantId").toString();

        LambdaQueryWrapper<MtCountry> lambdaQueryWrapper = Wrappers.lambdaQuery();

        lambdaQueryWrapper.orderByAsc(MtCountry::getId);
        List<MtCountry> dataList = mtCountryMapper.selectList(lambdaQueryWrapper);
        return dataList;
    }

    @Override
    public boolean saveCountry(CountryDto countryDto, Long accountInfoId) throws BusinessCheckException {
        // 1. 校验父节点
        if (countryDto.getParentId() != null && countryDto.getParentId() != 0L) {
            int parentCount = this.baseMapper.checkParentExist(countryDto.getParentId());
            if (parentCount == 0) {
                throw new BusinessCheckException("父节点不存在或已被删除");
            }
        }
        // 2. 构建实体
        MtCountry country = new MtCountry();
        BeanUtils.copyProperties(countryDto, country);
        country.setServeState(countryDto.getServeState() != null ? countryDto.getServeState() : 0);
        country.setDeleteFlag(0);
        //保存数据
        return this.save(country);
    }
}
