package com.yuchen.saas.park.service.service.fire.inspect.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuchen.saas.manage.system.api.entity.NestOrgUser;
import com.yuchen.saas.manage.system.api.feign.IOrgUserClient;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectFormReqDTO;
import com.yuchen.saas.park.api.dto.fire.inspect.FireInspectFormSubmitReqDTO;
import com.yuchen.saas.park.api.entity.fire.inspect.SaasParkFireInspectForm;
import com.yuchen.saas.park.api.vo.fire.inspect.FireInspectFormVO;
import com.yuchen.saas.park.service.mapper.fire.inspect.SaasParkFireInspectFormMapper;
import com.yuchen.saas.park.service.service.fire.inspect.ISaasParkFireInspectFormService;
import com.yuchen.saas.park.service.service.fire.inspect.ISaasParkFireInspectTypeService;
import com.yuchen.saas.park.service.util.PageConverterUtils;
import lombok.RequiredArgsConstructor;
import org.nest.springwrap.core.log.exception.ServiceException;
import org.nest.springwrap.core.mp.base.BaseEntity;
import org.nest.springwrap.core.mp.base.BaseServiceImpl;
import org.nest.springwrap.core.mp.support.Condition;
import org.nest.springwrap.core.mp.support.NestPage;
import org.nest.springwrap.core.mp.support.Query;
import org.nest.springwrap.core.secure.ContextUser;
import org.nest.springwrap.core.secure.utils.AuthUtil;
import org.nest.springwrap.core.tool.api.R;
import org.nest.springwrap.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouhanwei
 * @since 2024-04-01
 */
@Service
@RequiredArgsConstructor
public class SaasParkFireInspectFormServiceImpl extends BaseServiceImpl<SaasParkFireInspectFormMapper, SaasParkFireInspectForm> implements ISaasParkFireInspectFormService {

    private final ISaasParkFireInspectTypeService inspectTypeService;

    private final IOrgUserClient iOrgUserClient;

    @Override
    public NestPage<FireInspectFormVO> findFireInspectFormPage(FireInspectFormReqDTO reqDTO) {
        ContextUser contextUser = AuthUtil.getUser();
        if (Objects.isNull(contextUser)) {
            throw new ServiceException("用户不存在");
        }
        Long customerId = contextUser.getCustomerManageId();
        Page<FireInspectFormVO> resultPage = new Page<>();
        // 赋值数据
        LambdaQueryWrapper<SaasParkFireInspectForm> lambdaWrapper = Wrappers.lambdaQuery();
        lambdaWrapper.eq(SaasParkFireInspectForm::getCustomerId, customerId);
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getProjectId()), SaasParkFireInspectForm::getProjectId, reqDTO.getProjectId());
        lambdaWrapper.eq(Func.isNotEmpty(reqDTO.getInspectTypeId()), SaasParkFireInspectForm::getInspectTypeId, reqDTO.getInspectTypeId());
        lambdaWrapper.like(StrUtil.isNotBlank(reqDTO.getInspectTitle()), SaasParkFireInspectForm::getInspectTitle, reqDTO.getInspectTitle());
        lambdaWrapper.orderByDesc(BaseEntity::getCreateTime);
        IPage<SaasParkFireInspectForm> page = page(Condition.getPage(reqDTO),lambdaWrapper);
        List<SaasParkFireInspectForm> fireInspectFormList = page.getRecords();
        // 数据列表
        List<FireInspectFormVO> resultList = new ArrayList<>();
        if (CollUtil.isNotEmpty(fireInspectFormList)) {
            // 根据客户id获取当前巡检类型列表
            List<Long> typeIds = fireInspectFormList.stream().map(SaasParkFireInspectForm::getInspectTypeId).collect(Collectors.toList());
            Map<Long, String> inspectTypeMap = inspectTypeService.findFireInspectTypeMap(typeIds);
            // 组织用户列表
            Map<Long, String> orgUserMap = new HashMap<>();
            if (StrUtil.isNotBlank(contextUser.getDeptId())) {
                R<List<NestOrgUser>> feignResult = iOrgUserClient.findOrgUserList(Long.valueOf(contextUser.getDeptId()));
                if (feignResult.isSuccess()) {
                    orgUserMap = feignResult.getData().stream().collect(Collectors.toMap(BaseEntity::getId, NestOrgUser::getName));
                }
            }
            for (SaasParkFireInspectForm saasParkFireInspectForm : fireInspectFormList) {
                FireInspectFormVO vo = new FireInspectFormVO();
                BeanUtil.copyProperties(saasParkFireInspectForm, vo);
                // 赋值巡检类型信息
                vo.setInspectTypeName(inspectTypeMap.get(vo.getInspectTypeId()));
                // 赋值添加人名称
                vo.setOrgUserName(orgUserMap.get(vo.getCreateOrgUser()));
                resultList.add(vo);
            }
        }
        resultPage.setTotal(page.getTotal());
        resultPage.setSize(page.getSize());
        resultPage.setCurrent(page.getCurrent());
        resultPage.setRecords(resultList);
        return PageConverterUtils.convert(resultPage);
    }

    @Override
    public FireInspectFormVO getFireInspectTypeById(Long inspectFormId) {
        FireInspectFormVO vo = new FireInspectFormVO();
        SaasParkFireInspectForm saasParkFireInspectForm = getById(inspectFormId);
        if (Objects.isNull(saasParkFireInspectForm)) {
            throw new ServiceException("巡检表单数据不存在");
        }
        BeanUtil.copyProperties(saasParkFireInspectForm, vo);
        return vo;
    }

    @Override
    public Boolean addFireInspectForm(FireInspectFormSubmitReqDTO reqDTO) {
        SaasParkFireInspectForm saasParkFireInspectForm = new SaasParkFireInspectForm();
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectForm);
        // 判断去重
        validRepeat(saasParkFireInspectForm);
        saasParkFireInspectForm.setCustomerId(AuthUtil.getUser().getCustomerManageId());
        saasParkFireInspectForm.setCreateOrgUser(AuthUtil.getUser().getOrgUserId());
        return save(saasParkFireInspectForm);
    }

    @Override
    public Boolean editFireInspectForm(FireInspectFormSubmitReqDTO reqDTO) {
        SaasParkFireInspectForm saasParkFireInspectForm = getById(reqDTO.getId());
        if (Objects.isNull(saasParkFireInspectForm)) {
            throw new ServiceException("巡检表单数据不存在");
        }
        BeanUtil.copyProperties(reqDTO, saasParkFireInspectForm);
        // 判断去重
        validRepeat(saasParkFireInspectForm);
        saasParkFireInspectForm.setUpdateOrgUser(AuthUtil.getUser().getOrgUserId());
        return updateById(saasParkFireInspectForm);
    }

    @Override
    public Boolean removeFireInspectForm(Long inspectFormId) {
        SaasParkFireInspectForm saasParkFireInspectForm = getById(inspectFormId);
        if (Objects.isNull(saasParkFireInspectForm)) {
            throw new ServiceException("巡检表单数据不存在");
        }
        return removeById(inspectFormId);
    }

    private void validRepeat(SaasParkFireInspectForm saasParkFireInspectForm) {
        int count = count(new LambdaQueryWrapper<SaasParkFireInspectForm>()
                .eq(SaasParkFireInspectForm::getInspectTitle, saasParkFireInspectForm.getInspectTitle())
                .eq(SaasParkFireInspectForm::getProjectId, saasParkFireInspectForm.getProjectId())
                .notIn(Objects.nonNull(saasParkFireInspectForm.getId()), BaseEntity::getId, saasParkFireInspectForm.getId()));
        if (count > 0) {
            throw new ServiceException("巡检内容标题不能重复");
        }
    }
}
