package com.iformall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.IdWorker;
import com.iformall.domain.po.MallRolePermission;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.MallRolePermissionMapper;
import com.iformall.service.MallRolePermissionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MallRolePermissionServiceImpl implements MallRolePermissionService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MallRolePermissionMapper mallUserRolePermissionMapper;


    @Override
    public PageInfo<MallRolePermission> listAsPage(MallRolePermission record, Integer pageIndex, Integer pageSize) {
        return PageHelper.startPage(pageIndex, pageSize).doSelectPageInfo(() -> mallUserRolePermissionMapper.findList(record));
    }

    @Override
    public List<MallRolePermission> getList(MallRolePermission record) {
        return mallUserRolePermissionMapper.findList(record);
    }

    @Override
    public MallRolePermission getById(Long id) {
        return mallUserRolePermissionMapper.selectById(id);
    }

    @Override
    public void saveOrUpdate(MallRolePermission record) {
        if (record.getId() == null) {
            //record.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            final IdWorker idWorker = IdWorker.get();
            record.setId(idWorker.nextId());
            mallUserRolePermissionMapper.insert(record);
        } else {
            mallUserRolePermissionMapper.updateById(record);
        }
    }

    @Override
    public void deleteById(Long id) {
        mallUserRolePermissionMapper.deleteById(id);
    }


    @Override
    public void savePermissions(String tenantId, Long roleId, Long[] perId) {
        final IdWorker idWorker = IdWorker.get();
        // 删除old
        mallUserRolePermissionMapper.deleteByRoleId(roleId);
        // 添加新的
        List<MallRolePermission> mallRolePermissionList = new ArrayList<>();
        for (Long pId : perId) {
            MallRolePermission permission = new MallRolePermission();
            permission.setId(idWorker.nextId());
            permission.setPermissionId(pId);
            permission.setTenantId(tenantId);
            permission.setRoleId(roleId);
            mallRolePermissionList.add(permission);
        }
        int count = mallUserRolePermissionMapper.insertBatch(mallRolePermissionList);
        if(count != mallRolePermissionList.size()) {
            throw new MallinkException(ErrorCode.DB_FAIL);
        }
    }

    public void deleteByRoleId(Long roleId) {
        mallUserRolePermissionMapper.deleteByRoleId(roleId);
    }


}
