package com.ycwl.basic.service.pc.impl;

import com.ycwl.basic.exception.BaseException;
import com.ycwl.basic.model.pc.scenic.entity.ScenicAccountEntity;
import com.ycwl.basic.model.pc.scenic.req.ScenicAccountReqQuery;
import com.ycwl.basic.service.pc.ScenicAccountService;
import com.ycwl.basic.utils.SnowFlakeUtil;
import org.springframework.stereotype.Service;
import com.ycwl.basic.mapper.ScenicAccountMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service
public class ScenicAccountServiceImpl implements ScenicAccountService {
    @Autowired
    private ScenicAccountMapper mapper;

    @Override
    public int addScenicAccount(ScenicAccountEntity entity) {
        if (entity.getId() == null) {
            entity.setId(SnowFlakeUtil.getLongId());
        }
        int result = mapper.add(entity);
        if (entity.getScenicId() != null && !entity.getScenicId().isEmpty()) {
            entity.getScenicId().forEach(scenicId -> {
                mapper.addAccountScenicRelation(entity.getId(), scenicId, entity.getIsSuper());
            });
        }
        return result;
    }

    @Override
    public int deleteScenicAccount(Long id) {
        return mapper.deleteById(id);
    }

    @Override
    public int updateScenicAccount(ScenicAccountEntity entity) {
        if (entity.getId() == null) {
            throw new BaseException("参数错误");
        }
        int update = mapper.update(entity);
        mapper.deleteRelationById(entity.getId());
        entity.getScenicId().forEach(scenicId -> {
            mapper.addAccountScenicRelation(entity.getId(), scenicId, entity.getIsSuper());
        });
        return update;
    }

    @Override
    public ScenicAccountEntity getScenicAccountById(Long id) {
        ScenicAccountEntity account = mapper.findAccountById(String.valueOf(id));
        List<Long> scenicList = mapper.getAccountRelations(id);
        account.setScenicId(scenicList);
        return account;
    }

    @Override
    public ScenicAccountEntity getSuperAccountByScenicId(Long scenicId) {
        return mapper.getSuperAccountOfScenic(scenicId);
    }

    // 新增分页查询实现
    @Override
    public List<ScenicAccountEntity> pageQuery(ScenicAccountReqQuery req) {
        return mapper.pageQuery(req);
    }

    @Override
    public int updateStatus(Long id) {
        return mapper.updateStatus(id);
    }

    @Override
    public int updateActiveStatus(Long id) {
        return mapper.updateActiveStatus(id);
    }

    @Override
    public ScenicAccountEntity getScenicAccountByAccount(String account) {
        ScenicAccountEntity accountEntity = mapper.getByAccount(account);
        if (accountEntity == null) {
            throw new BaseException("账号异常");
        }
        List<Long> scenicList = mapper.getAccountRelations(accountEntity.getId());
        accountEntity.setScenicId(scenicList);
        return accountEntity;
    }
}