package com.sw.mes.yb.spc.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.yb.spc.app.dao.AppPermissionDao;
import com.sw.mes.yb.spc.app.entity.AppPermission;
import com.sw.mes.yb.spc.app.service.AppPermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.sw.mes.core.constant.Constants.TOKEN_PREFIX;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class AppPermissionServiceImpl extends BaseServiceImpl<AppPermission> implements AppPermissionService {
    AppPermissionDao dao;

    @Autowired
    public void setDao(AppPermissionDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    RedisTemplate<String, Object> redisTemplate;


    private static final String SPC_APP_SIX_PERMISSION = "spc_app_six_yb_permission";
    private static final String SPC_APP_UPDATE = "update";
    private static final String SPC_APP_CLOSE = "close";
    private static final String SPC_APP_MODULE = "moduleName";
    public static String USER_ROLES = "user_roles";
    public final static String TOKEN = "token";

    @Override
    public AppPermission findByRoleIdAndPermissionAndModuleNameAndType(Integer roleId, String permission, String moduleName, Integer type) {
        return dao.findByRoleIdAndPermissionAndModuleNameAndType(roleId, permission, moduleName, type);
    }

    @Override
    public Map<String, String> getAppPermissionDto(HttpServletRequest request, String moduleName, Integer type) {
        String token = request.getHeader(TOKEN);
        Map<String, String> map = new HashMap<>(2);
        map.put(SPC_APP_UPDATE, "");
        map.put(SPC_APP_CLOSE, "");
        if (!StringUtils.isBlank(token)) {
            String result = (String) redisTemplate.opsForValue().get(TOKEN_PREFIX + token);
            if (StringUtils.isEmpty(result)) {
                return null;
            }
            JSONObject jsonObject = JSONObject.parseObject(result);
            // 获取角色id
            String roles = (String) jsonObject.get(USER_ROLES);
            String[] roleIds = roles.split(",");
            if (null == roleIds || roleIds.length == 0) {
                return null;
            }
            // 获取spc权限
            String key = SPC_APP_SIX_PERMISSION + type;
            List<AppPermission> appPermissionList = (List<AppPermission>) redisTemplate.opsForValue().get(key);
            if (null == appPermissionList || appPermissionList.size() == 0) {
                appPermissionList = findAll();
                redisTemplate.opsForValue().set(key, appPermissionList, 7 * 24 * 3600, TimeUnit.SECONDS);
            }
            // 遍历角色查找权限
            for (String roleid : roleIds) {
                for (AppPermission appPermission : appPermissionList) {
                    if (null != appPermission.getRoleId() && roleid.equals(appPermission.getRoleId().toString())) {
                        if (null == appPermission.getPermission()) {
                            continue;
                        }
                        // 判断模块名是否存在
                        if (null != appPermission.getModuleName() && moduleName.equalsIgnoreCase(appPermission.getModuleName())) {
                            map.put(SPC_APP_MODULE, appPermission.getModuleName());
                            // 处理权限
                            if (SPC_APP_UPDATE.equals(appPermission.getPermission())) {
                                // 去重权限
                                if (!StringUtils.isBlank(map.get(SPC_APP_UPDATE))) {
                                    // 拿到权限字符串拼接
                                    String permission = map.get(SPC_APP_UPDATE);
                                    map.put(SPC_APP_UPDATE, permission + "," + appPermission.getSeries());
                                } else {
                                    map.put(SPC_APP_UPDATE, appPermission.getSeries());
                                }
                            }
                            // 审批权限
                            if (SPC_APP_CLOSE.equals(appPermission.getPermission())) {
                                if (!StringUtils.isBlank(map.get(SPC_APP_CLOSE))) {
                                    // 拿到权限字符串拼接
                                    String permission = map.get(SPC_APP_CLOSE);
                                    map.put(SPC_APP_CLOSE, permission + "," + appPermission.getSeries());
                                } else {
                                    map.put(SPC_APP_CLOSE, appPermission.getSeries());
                                }
                            }
                        }
                    }
                }
            }
            Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
            while (iterator.hasNext()) {
                // 权限去重
                Map.Entry<String, String> entry = iterator.next();
                Set<String> set = new HashSet<>(Arrays.asList(entry.getValue().split(",")));
                if (SPC_APP_UPDATE.equals(entry.getKey())) {
                    String[] strArray = set.toArray(new String[set.size()]);
                    String join = String.join(",", strArray);
                    map.put(SPC_APP_UPDATE, join);
                }
                if (SPC_APP_CLOSE.equals(entry.getKey())) {
                    String[] strArray = set.toArray(new String[set.size()]);
                    String join = String.join(",", strArray);
                    map.put(SPC_APP_CLOSE, join);
                }
            }
        }
        return map;
    }

    @Override
    public void saveOrUpdate(AppPermission appPermission) {
        super.saveOrUpdate(appPermission);
        if (null != appPermission.getPermission()) {
            // 每次更新，更新缓存
            List<AppPermission> appPermissionList = findAll();
            redisTemplate.opsForValue().set(SPC_APP_SIX_PERMISSION + appPermission.getType(), appPermissionList, 7 * 24 * 3600, TimeUnit.SECONDS);
        }
    }
}
