package com.huimv.receive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.huimv.receive.common.utils.ConstUtil;
import com.huimv.receive.common.utils.Result;
import com.huimv.receive.common.utils.ResultCode;
import com.huimv.receive.entity.AccountGroup;
import com.huimv.receive.entity.Farm;
import com.huimv.receive.entity.GroupMenu;
import com.huimv.receive.entity.Menu;
import com.huimv.receive.mapper.AccountGroupMapper;
import com.huimv.receive.mapper.FarmMapper;
import com.huimv.receive.mapper.GroupMenuMapper;
import com.huimv.receive.mapper.MenuMapper;
import com.huimv.receive.service.IAuthorizeService;
import com.huimv.receive.service.IGroupMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class AuthorizeServiceImpl implements IAuthorizeService {

    @Autowired
    AccountGroupMapper accountGroupMapper;
    @Autowired
    GroupMenuMapper groupMenuMapper;
    @Autowired
    IGroupMenuService groupMenuService;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private FarmMapper farmMapper;
    
    @Override
    @Transactional
    public Result saveAccountGroup(String accountId, String groupIds) {
        /**
         * Step1:先删除原先的账号关联权限组数据；
         * Step2:再添加新的账号关联权限组数据；
         */
        if (accountId == null||"".equals(accountId)){

            accountGroupMapper.removeAccountGroup(groupIds);
            return new Result(10000, "保存账号关联权限组成功", true);
        }else {
            String[] groupIdArray = accountId.split(",");
            accountGroupMapper.removeAccountGroup(accountId);
//        for (int a = 0; a < groupIdArray.length; a++) {
//            accountGroupMapper.removeAccountGroup(accountId,groupIdArray[a]);
//        }
            for (int a = 0; a < groupIdArray.length; a++) {
                AccountGroup accountGroupEntity = new AccountGroup();
                accountGroupEntity.setAccountId(Integer.parseInt(groupIdArray[a]));
                accountGroupEntity.setGroupId(Integer.parseInt(groupIds));
                accountGroupMapper.insert(accountGroupEntity);
//            accountGroupMapper.insert(Integer.parseInt(accountId),Integer.parseInt(groupIdArray[a]));
            }
            return new Result(10000, "保存账号关联权限组成功", true);
        }


    }

    @Override
    @Transactional
    public Result saveGroupMenu(String groupId, String menuIds,String isAll) {
        /**
         * Step1:先删除原先的权限组关联菜单数据；
         * Step2:再添加新的账号权限组关联菜单数据；
         */
        groupMenuMapper.removeGroupMenu(groupId);
        if (StringUtils.isNotBlank(menuIds)){
            String[] menuIdsArray = menuIds.split(",");
            String[] split = isAll.split(",");

            List<GroupMenu> list = new ArrayList();
            for (int a = 0; a < menuIdsArray.length; a++) {
                GroupMenu groupMenu = new GroupMenu();
                groupMenu.setGroupId(Integer.parseInt(groupId));
                groupMenu.setMenuId(Integer.parseInt(menuIdsArray[a]));
                list.add(groupMenu);
            }
            if (StringUtils.isNotBlank(isAll)){
                for (GroupMenu groupMenu : list) {
                    for (String s : split) {
                        if (groupMenu.getMenuId()== Integer.parseInt(s)){
                            groupMenu.setIsAll(1);
                        }
                    }
                }
            }
            groupMenuService.saveBatch(list);
        }


        return new Result(10000, "保存权限组关联菜单成功", true);
    }


    @Override
    public Result getMenuByGroup(Map paramsMap) {
        String groupId  =  (String)paramsMap.get("groupId");
        QueryWrapper<GroupMenu> groupMenuQueryWrapper = new QueryWrapper<>();
        groupMenuQueryWrapper.eq("group_id",groupId);
        groupMenuQueryWrapper.eq("is_all",0);
        List<GroupMenu> groupMenuEntityList = groupMenuMapper.selectList(groupMenuQueryWrapper);
        if (groupMenuEntityList.size() == 0) {
            return new Result(10005, "当前权限组暂未关联任何菜单.", false);
        }
        StringBuilder stringBuffer = new StringBuilder();

        for (GroupMenu groupMenu : groupMenuEntityList) {

            stringBuffer.append(groupMenu.getMenuId());
            stringBuffer.append(",");

        }
        stringBuffer.deleteCharAt(stringBuffer.length()-1);
        return new Result(ResultCode.SUCCESS, stringBuffer.toString());
    }

    @Override
    public Result getMenuByGroupAndFarm(Map<String, String> map) {
        String groupId = (String) map.get("groupId");
        String farmId = (String) map.get("farmId");
        Farm farm = farmMapper.selectById(farmId);
        String farmMenu = farm.getFarmMenu();
        if (StringUtils.isNotBlank(farmMenu)){
            return new Result(ConstUtil.ERR_MYMENU_EMPTY_CODE,"该牧场无任何授权菜单",false);
        }
        List<String> list = Arrays.asList(farmMenu);
        QueryWrapper<GroupMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(groupId),"group_id",groupId);
        queryWrapper.in("menu_id",list);
//        queryWrapper.eq("is_all",0);
        List<GroupMenu> groupMenuEntityList = groupMenuMapper.selectList(queryWrapper);
        if (groupMenuEntityList.size() == 0) {
            return new Result(10005, "当前权限组暂未关联任何菜单.", false);
        }
        StringBuilder stringBuffer = new StringBuilder();

        for (GroupMenu groupMenu : groupMenuEntityList) {

            stringBuffer.append(groupMenu.getMenuId());
            stringBuffer.append(",");

        }
        stringBuffer.deleteCharAt(stringBuffer.length()-1);
        return new Result(ResultCode.SUCCESS, stringBuffer.toString());
    }

    /**
     * @param accountId
     * @return
     */
    @Override
    public Result getGroupByAccount(String accountId) {
        /* 根据账号id读取已关联权限组 */
        QueryWrapper<AccountGroup> accountGroupQueryWrapper = new QueryWrapper<>();
        accountGroupQueryWrapper.eq("account_id",accountId);
        List<AccountGroup> accountGroupEntityList = accountGroupMapper.selectList(accountGroupQueryWrapper);
        if (accountGroupEntityList.size() == 0) {
            return new Result(10006, "当前用户账号暂未关联任何权限组.", false);
        }
        StringBuilder idSb = new StringBuilder();
        for (AccountGroup accountGroupEntity : accountGroupEntityList) {
            if (idSb.length() > 0) {
                idSb.append(",");
            }
            idSb.append(accountGroupEntity.getGroupId());
        }
        return new Result(ResultCode.SUCCESS, idSb.toString());
    }


    @Override
    public Result getAccountByGroup(String groupId) {
        /* 根据账号id读取已关联权限组 */
        QueryWrapper<AccountGroup> accountGroupQueryWrapper = new QueryWrapper<>();
        accountGroupQueryWrapper.eq("group_id",groupId);
        List<AccountGroup> accountGroupEntityList = accountGroupMapper.selectList(accountGroupQueryWrapper);
        if (accountGroupEntityList.size() == 0) {
            return new Result(10006, "当前权限组暂未关联任何用户账号.", false);
        }
        StringBuilder idSb = new StringBuilder();
        for (AccountGroup accountGroupEntity : accountGroupEntityList) {
            if (idSb.length() > 0) {
                idSb.append(",");
            }
            idSb.append(accountGroupEntity.getAccountId());
        }
        return new Result(ResultCode.SUCCESS, idSb.toString());
    }

    @Override
    public List getMyMenuAll(String accountName,String farmId) {
        if ("1".equals(accountName)){
            List<Menu> menus = menuMapper.selectList(new QueryWrapper<Menu>().orderByAsc("sort"));
            return menus;
        }
        Farm farm = farmMapper.selectById(farmId);
        String farmMenu = farm.getFarmMenu();
        String[] farmMenus = farmMenu.split(",");
//        List<String> farmMenus = Arrays.asList(farmMenu);
        return menuMapper.getMyMenu(accountName,farmMenus);
    }

    @Override
    public List<String> getMyButton(Integer userId, Integer farmId) {
        Farm farm = farmMapper.selectById(farmId);
        String farmMenu = farm.getFarmMenu();
        if (userId == 1){
            List<Menu> menus = menuMapper.selectList(null);
            List<String> list = new ArrayList<>();
            for (Menu menu : menus) {
                list.add(menu.getPermission());
            }
            return list;
        }
        String[] menus = farmMenu.split(",");
        return menuMapper.getMyButton(userId,menus);
    }

    @Override
    public List getMyMenuMultilevel(String userId) {
        return null;
    }


}
