package com.jeesite.modules.sso.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.modules.sys.entity.Role;
import com.jeesite.modules.sys.entity.User;
import com.jeesite.modules.sys.service.RoleService;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.sso.entity.SsoApp;
import com.jeesite.modules.sso.service.SsoAppService;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 应用接入列表Controller
 * @author yinet
 * @version 2022-06-14
 */
@Controller
@RequestMapping(value = "${adminPath}/sso/ssoApp")
public class SsoAppController extends BaseController {

	@Autowired
	private SsoAppService ssoAppService;
	@Autowired
	private RoleService roleService;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public SsoApp get(Long id, boolean isNewRecord) {
		return ssoAppService.get(id+"", isNewRecord);
	}

	/**
	 * 查询列表
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = {"list", ""})
	public String list(SsoApp ssoApp, Model model) {
		// model.addAttribute("ssoApp", ssoApp);

		if (ssoApp.getAccessType().equals("0")) {
			return "modules/sso/ssoAppList";
		} else if (ssoApp.getAccessType().equals("1")) {
			return "modules/sso/messageList";
		} else {
			return "modules/sso/serviceList";
		}
	}


	/**
	 * 查询列表
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = {"list2", ""})
	public String list2(SsoApp ssoApp, Model model) {
		model.addAttribute("SsoApp", ssoApp);
		return "modules/sso/evaluateAppList";
	}


	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<SsoApp> listData(SsoApp ssoApp, HttpServletRequest request, HttpServletResponse response) {
		ssoApp.setPage(new Page<>(request, response));
		Page<SsoApp> page = ssoAppService.findPage(ssoApp);
		List<SsoApp> list = page.getList();
		list=list.stream().sorted(Comparator.comparing(SsoApp::getCreateDate).reversed()).collect(Collectors.toList());
		page.setList(list);
		return page;
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = "listData2")
	@ResponseBody
	public Page<SsoApp> listData2(SsoApp ssoApp, HttpServletRequest request, HttpServletResponse response) {
		ssoApp.setPage(new Page<>(request, response));
		Page<SsoApp> page = ssoAppService.findPage(ssoApp);
		List<SsoApp> list = page.getList();
		list=list.stream().filter(a -> a.getAccessType().equals("0")).collect(Collectors.toList());
		page.setList(list);
		return page;
	}


	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = "form")
	public String form(SsoApp ssoApp, Model model) {
		model.addAttribute("ssoApp", ssoApp);
		//查询权限列表
		List<Role> rolelist = roleService.findList(new Role());
		model.addAttribute("approles", rolelist);
		return "modules/sso/ssoAppForm";
	}

	/**
	 * 保存数据
	 */
	@RequiresPermissions("sso:ssoApp:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated SsoApp ssoApp) {
		ssoAppService.save(ssoApp);
		return renderResult(Global.TRUE, text("保存应用接入列表成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("sso:ssoApp:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(SsoApp ssoApp) {
		ssoAppService.delete(ssoApp);
		return renderResult(Global.TRUE, text("删除应用接入列表成功！"));
	}

	/**
	 * 列表选择对话框
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = "ssoAppSelect")
	public String ssoAppSelect(SsoApp ssoApp, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("ssoApp", ssoApp);
		return "modules/sso/ssoAppSelect";
	}

	//修改状态
	@RequestMapping("/changeStatus")
	public String changeStatus(String flag,String id){
		System.out.println(flag+"===="+id);

		int i=ssoAppService.changeStatus(flag,id);
		if(i!=0){
			return renderResult(Global.TRUE, text("修改成功！"));
		}else {
			return renderResult(Global.TRUE, text("修改失败！"));
		}

	}
	//修改状态
	@RequestMapping("/recommendStatus")
	public String recommendStatus(String flag,String id){
		System.out.println(flag+"===="+id);

		int i=ssoAppService.recommendStatus(flag,id);
		if(i!=0){
			return renderResult(Global.TRUE, text("修改成功！"));
		}else {
			return renderResult(Global.TRUE, text("修改失败！"));
		}

	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("sso:ssoApp:view")
	@RequestMapping(value = "serviceform")
	public String serviceform(SsoApp ssoApp, Model model) {
		if(ssoApp.getId()==null || ssoApp.getId()=="") {
			ssoApp.setAppKey(UUID.randomUUID().toString());
			ssoApp.setAppSecretkey(UUID.randomUUID().toString());
		}
		model.addAttribute("ssoApp", ssoApp);
		return "modules/sso/serviceForm";
	}


	/**
	 * 应用
	 */
	@RequestMapping(value = "ssoApp")
	public List<SsoApp> ssoApp(SsoApp ssoApp) {
		//获取用户权限
		User user = UserUtils.getUser();
		List<Role> roleList = user.getRoleList();

		ssoApp.setAppStatus("0");
		List<SsoApp> list = ssoAppService.findList(ssoApp);
		List<SsoApp> list1=new ArrayList<>();

		if(user.getUserCode().equals("system")){
			return list;
		}
			for (SsoApp app : list) {
				for (Role role : roleList) {
				if(app.getAuthority().contains(role.getRoleCode())){
					list1.add(app);
				}
			}
		}
		list1=list1.stream().distinct().collect(Collectors.toList());
		return list1;
	}


	@RequestMapping("/findAuthority")
	@ResponseBody
	public List<String> findAuthority(String id){
		SsoApp ssoApp=new SsoApp();
		ssoApp.setId(id);
		List<SsoApp> list = ssoAppService.findList(ssoApp);

		List<String> result=new ArrayList<>();

		String[] split = list.get(0).getAuthority().split(",");
		for (String s : split) {
			result.add(s);
		}

		return result;
	}


}
