package org.dromara.project.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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 jakarta.annotation.Resource;
import org.dromara.common.core.constant.HttpStatus;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ObjectUtils;
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.satoken.utils.LoginHelper;
import org.dromara.project.domain.BusConstructionUser;
import org.dromara.project.domain.BusContractor;
import org.dromara.project.domain.req.contractor.ContractorCreateReq;
import org.dromara.project.domain.req.contractor.ContractorQueryReq;
import org.dromara.project.domain.req.contractor.ContractorUpdateReq;
import org.dromara.project.domain.vo.BusContractorVo;
import org.dromara.project.mapper.BusContractorMapper;
import org.dromara.project.service.IBusConstructionUserService;
import org.dromara.project.service.IBusContractorService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分包单位Service业务层处理
 *
 * @author lcj
 * @date 2025-03-07
 */
@Service
public class BusContractorServiceImpl extends ServiceImpl<BusContractorMapper, BusContractor>
    implements IBusContractorService {

    @Resource
    private IBusConstructionUserService constructionUserService;

    /**
     * 查询分包单位
     *
     * @param id 主键
     * @return 分包单位
     */
    @Override
    public BusContractorVo queryById(Long id) {
        BusContractor contractor = this.getById(id);
        if (contractor == null) {
            throw new ServiceException("分包单位信息不存在", HttpStatus.NOT_FOUND);
        }
        return this.getVo(contractor);
    }

    /**
     * 分页查询分包单位列表
     *
     * @param req       查询条件
     * @param pageQuery 分页参数
     * @return 分包单位分页列表
     */
    @Override
    public TableDataInfo<BusContractorVo> queryPageList(ContractorQueryReq req, PageQuery pageQuery) {
        // 查询数据库
        Page<BusContractor> result = this.page(pageQuery.build(), this.buildQuery(req));
        return TableDataInfo.build(this.getVoPage(result));
    }

    /**
     * 查询符合条件的分包单位列表
     *
     * @param req 查询条件
     * @return 分包单位列表
     */
    @Override
    public List<BusContractorVo> queryList(ContractorQueryReq req) {
        LambdaQueryWrapper<BusContractor> lqw = this.buildQuery(req);
        List<BusContractor> list = this.list(lqw);
        return list.stream().map(this::getVo).toList();
    }

    /**
     * 新增分包单位
     *
     * @param req 分包单位
     * @return 新增id
     */
    @Override
    public Long insertByBo(ContractorCreateReq req) {
        // 将实体类和 DTO 进行转换
        BusContractor contractor = new BusContractor();
        BeanUtils.copyProperties(req, contractor);
        // 数据转换
        Map<String, Long> fileMap = req.getFileMap();
        String fileMapStr = JSONUtil.toJsonStr(fileMap);
        contractor.setFiles(fileMapStr);
        // 数据校验
        validEntityBeforeSave(contractor, true);
        // 操作数据库
        boolean save = this.save(contractor);
        if (!save) {
            throw new ServiceException("新增施工人员失败，数据库异常", HttpStatus.ERROR);
        }
        return contractor.getId();
    }

    /**
     * 修改分包单位
     *
     * @param req 分包单位
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ContractorUpdateReq req) {
        // 将实体类和 DTO 进行转换
        BusContractor contractor = new BusContractor();
        BeanUtils.copyProperties(req, contractor);
        // 数据转换
        Map<String, Long> fileMap = req.getFileMap();
        String fileMapStr = JSONUtil.toJsonStr(fileMap);
        contractor.setFiles(fileMapStr);
        // 数据校验
        validEntityBeforeSave(contractor, false);
        // 判断是否存在
        BusContractor oldContractor = this.getById(contractor.getId());
        if (oldContractor == null) {
            throw new ServiceException("修改施工人员失败，数据不存在", HttpStatus.NOT_FOUND);
        }
        // 操作数据库
        return this.updateById(contractor);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusContractor entity, Boolean add) {
        // 做一些数据校验,如唯一约束
        if (add) {
            String name = entity.getName();
            if (StringUtils.isBlank(name)) {
                throw new ServiceException("分包单位名称不能为空", HttpStatus.BAD_REQUEST);
            }
            String principal = entity.getPrincipal();
            if (StringUtils.isBlank(principal)) {
                throw new ServiceException("分包单位负责人不能为空", HttpStatus.BAD_REQUEST);
            }
        }
    }

    /**
     * 校验并批量删除分包单位信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        Long userId = LoginHelper.getUserId();
        List<BusContractor> contractorList = this.listByIds(ids);
        // 做一些业务上的校验,判断是否需要校验
        if (isValid) {
            // 仅创建用户可以删除
            contractorList.forEach(contractor -> {
                if (!contractor.getCreateBy().equals(userId)) {
                    throw new ServiceException("您无权删除该分包单位", HttpStatus.FORBIDDEN);
                }
            });
            // 判断当前分包公司下是否还包含施工人员
            QueryWrapper<BusConstructionUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("contractor_id", ids);
            if (constructionUserService.count(queryWrapper) > 0) {
                throw new ServiceException("删除分包单位失败，删除分包单位下存在施工人员", HttpStatus.BAD_REQUEST);
            }
        }
        // 判断对应数据是否都存在
        if (contractorList.size() != ids.size()) {
            throw new ServiceException("删除分包单位失败，数据缺失", HttpStatus.BAD_REQUEST);
        }
        return this.removeBatchByIds(ids);
    }

    /**
     * 获取分包公司视图对象
     *
     * @param contractor 分包公司对象
     * @return 分包公司视图对象
     */
    @Override
    public BusContractorVo getVo(BusContractor contractor) {
        // 对象转封装类
        BusContractorVo contractorVo = new BusContractorVo();
        if (contractor == null) {
            return contractorVo;
        }
        BeanUtils.copyProperties(contractor, contractorVo);
        // 关联对象存储文件信息
        String files = contractor.getFiles();
        if (StringUtils.isEmpty(files)) {
            return contractorVo;
        }
        Map<String, Long> fileMap = new HashMap<>();
        JSONObject parseObj = JSONUtil.parseObj(files);
        parseObj.forEach((key, value) -> fileMap.put(key, (Long) value));
        contractorVo.setFileMap(fileMap);
        return contractorVo;
    }

    /**
     * 获取分包公司查询条件封装
     *
     * @param req 分包公司查询条件
     * @return 分包公司查询条件封装
     */
    @Override
    public LambdaQueryWrapper<BusContractor> buildQuery(ContractorQueryReq req) {
        LambdaQueryWrapper<BusContractor> lqw = new LambdaQueryWrapper<>();
        if (req == null) {
            return lqw;
        }
        // 从对象中取值
        Long id = req.getId();
        String name = req.getName();
        String principal = req.getPrincipal();
        String principalPhone = req.getPrincipalPhone();
        String custodian = req.getCustodian();
        String custodianPhone = req.getCustodianPhone();
        String remark = req.getRemark();
        // 模糊查询
        lqw.like(StringUtils.isNotBlank(name), BusContractor::getName, name);
        lqw.like(StringUtils.isNotBlank(principal), BusContractor::getPrincipal, principal);
        lqw.like(StringUtils.isNotBlank(principalPhone), BusContractor::getPrincipalPhone, principalPhone);
        lqw.like(StringUtils.isNotBlank(custodian), BusContractor::getCustodian, custodian);
        lqw.like(StringUtils.isNotBlank(custodianPhone), BusContractor::getCustodianPhone, custodianPhone);
        lqw.like(StringUtils.isNotBlank(remark), BusContractor::getRemark, remark);
        // 精确查询
        lqw.eq(ObjectUtils.isNotEmpty(id), BusContractor::getId, id);
        return lqw;
    }

    /**
     * 获取分包公司分页对象视图
     *
     * @param contractorPage 分包公司分页对象
     * @return 分包公司分页对象视图
     */
    @Override
    public Page<BusContractorVo> getVoPage(Page<BusContractor> contractorPage) {
        List<BusContractor> contractorList = contractorPage.getRecords();
        Page<BusContractorVo> contractorVoPage = new Page<>(
            contractorPage.getCurrent(),
            contractorPage.getSize(),
            contractorPage.getTotal());
        if (CollUtil.isEmpty(contractorList)) {
            return contractorVoPage;
        }
        List<BusContractorVo> contractorVoList = contractorList.stream().map(this::getVo).toList();
        contractorVoPage.setRecords(contractorVoList);
        return contractorVoPage;
    }
}
