package com.fkzy.warn.service.impl;

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 com.fkzy.warn.mapper.PermissionMapper;
import com.fkzy.warn.model.Permission;
import com.fkzy.warn.service.PermissionService;
import com.fkzy.warn.service.PermissionUserService;
import com.fkzy.warn.common.constants.EntityConstants;
import com.fkzy.warn.common.request.RequestParameter;
import com.fkzy.warn.common.response.ApiResponse;
import com.fkzy.warn.model.PermissionUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * @author zhangjing
 * @date 2023/10/16 18:17
 * @description
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements
    PermissionService {

    @Autowired
    PermissionUserService permissionUserService;


    @Override
    public ApiResponse saveModel(Permission entity, String ticket) {
        save(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse updateModel(Permission entity,String ticket) {
        this.updateById(entity);
        return new ApiResponse();
    }

    @Override
    public ApiResponse deleteModel(List<String> ids) {
        Permission entity = new Permission();
        entity.setIsDel(EntityConstants.DEL);
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.in("id", ids);
        update(entity, wrapper);
        return new ApiResponse();
    }

    @Override
    public Page<Permission> queryPage(RequestParameter parameter) {
        Permission entity = parameter.getParameter().toJavaObject(Permission.class);
        Page<Permission> page = new Page<Permission>(parameter.getCurrent(), parameter.getSize());
        page.setSearchCount(true);
        page.setOptimizeCountSql(true);
        QueryWrapper<Permission> eWrapper = new QueryWrapper<Permission>(entity);
        Page<Permission> result = this.page(page, eWrapper);
        eWrapper.eq("is_del", EntityConstants.NORMAL)
            .orderByDesc("create_time");
        return result;
    }

    @Override
    public ApiResponse bindPerson(Integer permissionId, List<Integer> ids) {
        ApiResponse response = new ApiResponse();
        QueryWrapper<PermissionUser> wrapper = new QueryWrapper();
        wrapper.eq("permission_id",permissionId);
        permissionUserService.remove(wrapper);
        List<PermissionUser> list = new ArrayList<>();
        for (Integer id : ids) {
            PermissionUser p = new PermissionUser();
            p.setUserId(id);
            p.setPermissionId(permissionId);
            list.add(p);
        }
        permissionUserService.saveBatch(list);
        return response;
    }
}
