package com.zcloud.zcGbsServicer.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.cola.dto.PageResponse;
import com.alibaba.cola.dto.SingleResponse;
import com.alibaba.cola.exception.BizException;
import com.zcloud.zcGbsServicer.command.convertor.FireAlarmMeetingUserCoConvertor;
import com.zcloud.zcGbsServicer.api.FireAlarmMeetingUserServiceI;
import com.zcloud.zcGbsServicer.dto.FireAlarmMeetingUserAddCmd;
import com.zcloud.zcGbsServicer.dto.FireAlarmMeetingUserPageQry;
import com.zcloud.zcGbsServicer.dto.FireAlarmMeetingUserUpdateCmd;
import com.zcloud.zcGbsServicer.dto.clientobject.FireAlarmMeetingUserCO;
import com.zcloud.zcGbsServicer.persistence.dataobject.FireAlarmMeetingUserDO;
import com.zcloud.zcGbsServicer.persistence.dataobject.FireBrigadeDO;
import com.zcloud.zcGbsServicer.persistence.repository.FireAlarmMeetingUserRepository;
import com.zcloud.zcGbsServicer.persistence.repository.FireBrigadeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class FireAlarmMeetingUserServiceImpl extends FireAlarmServiceSupport implements FireAlarmMeetingUserServiceI {

    private final FireAlarmMeetingUserRepository fireAlarmMeetingUserRepository;
    private final FireBrigadeRepository fireBrigadeRepository;
    private final FireAlarmMeetingUserCoConvertor fireAlarmMeetingUserCoConvertor;
    private final FireAlarmUserResolver fireAlarmUserResolver;

    @Override
    public PageResponse<FireAlarmMeetingUserCO> listPage(FireAlarmMeetingUserPageQry qry) {
        Map<String, Object> params = new HashMap<>();
        params.put("pageIndex", qry.getPageIndex());
        params.put("pageSize", qry.getPageSize());
        params.put("localUserName", qry.getLocalUserName());
        params.put("fireBrigadeName", qry.getFireBrigadeName());
        params.put("userType", qry.getUserType());
        params.put("authStatus", qry.getAuthStatus());
        params.put("syncStatus", qry.getSyncStatus());
        PageResponse<FireAlarmMeetingUserDO> page = fireAlarmMeetingUserRepository.listPage(params);
        return PageResponse.of(fireAlarmMeetingUserCoConvertor.converDOsToCOs(page.getData()),
                page.getTotalCount(), page.getPageSize(), page.getPageIndex());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<FireAlarmMeetingUserCO> add(FireAlarmMeetingUserAddCmd cmd) {
        Long userTenantId = fireAlarmUserResolver.resolveUserTenantId(cmd.getLocalUserId());
        if (fireAlarmMeetingUserRepository.existsByLocalUserId(cmd.getLocalUserId(), userTenantId, null)) {
            throw new BizException("会议用户已存在");
        }
        FireAlarmMeetingUserDO user = new FireAlarmMeetingUserDO();
        user.setId(nextId());
        user.setFireAlarmMeetingUserId(nextBizId());
        fillCreateAudit(user);
        fireAlarmUserResolver.applyLocalUserTenant(user, cmd.getLocalUserId());
        fillMeetingUser(user, cmd);
        fireAlarmMeetingUserRepository.save(user);
        return SingleResponse.of(fireAlarmMeetingUserCoConvertor.converDOToCO(user));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(FireAlarmMeetingUserUpdateCmd cmd) {
        FireAlarmMeetingUserDO user = fireAlarmMeetingUserRepository.getById(cmd.getId());
        if (user == null) {
            throw new BizException("会议用户不存在");
        }
        if (fireAlarmMeetingUserRepository.existsByLocalUserId(cmd.getLocalUserId(),
                fireAlarmUserResolver.resolveUserTenantId(cmd.getLocalUserId()), cmd.getId())) {
            throw new BizException("会议用户已存在");
        }
        fillUpdateAudit(user);
        fireAlarmUserResolver.applyLocalUserTenant(user, cmd.getLocalUserId());
        fillMeetingUser(user, cmd);
        fireAlarmMeetingUserRepository.updateById(user);
    }

    @Override
    public FireAlarmMeetingUserCO get(Long id) {
        FireAlarmMeetingUserDO user = fireAlarmMeetingUserRepository.getById(id);
        if (user == null) {
            throw new BizException("会议用户不存在");
        }
        return fireAlarmMeetingUserCoConvertor.converDOToCO(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void remove(Long id) {
        FireAlarmMeetingUserDO user = fireAlarmMeetingUserRepository.getById(id);
        if (user == null) {
            throw new BizException("会议用户不存在");
        }
        fireAlarmMeetingUserRepository.removeById(id);
    }

    private void fillMeetingUser(FireAlarmMeetingUserDO user, FireAlarmMeetingUserAddCmd cmd) {
        user.setLocalUserId(cmd.getLocalUserId());
        user.setLocalUserName(cmd.getLocalUserName());
        user.setLocalPhone(cmd.getLocalPhone());
        user.setUserType(cmd.getUserType());
        FireBrigadeDO brigade = cmd.getFireBrigadePkId() == null ? null : fireBrigadeRepository.getById(cmd.getFireBrigadePkId());
        user.setFireBrigadeId(brigade == null ? null : brigade.getFireBrigadeId());
        user.setFireBrigadeName(brigade == null ? cmd.getFireBrigadeName() : brigade.getBrigadeName());
        user.setThirdUserId(cmd.getThirdUserId());
        user.setThirdUserName(cmd.getThirdUserName());
        user.setThirdNickName(cmd.getThirdNickName());
        user.setThirdDepartId(cmd.getThirdDepartId());
        user.setThirdDepartName(cmd.getThirdDepartName());
        user.setAuthRoomId(cmd.getAuthRoomId());
        user.setAuthRoomName(cmd.getAuthRoomName());
        user.setAuthStatus(cmd.getAuthStatus());
        user.setSyncStatus(cmd.getSyncStatus());
        user.setSyncMsg(cmd.getSyncMsg());
        user.setRemarks(cmd.getRemarks());
    }

    private long nextId() {
        return IdUtil.getSnowflake(1, 1).nextId();
    }

    private String nextBizId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
