package com.mortals.xhx.base.system.resource.web;


import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.IBaseEnum;
import com.mortals.framework.common.Rest;
import com.mortals.framework.common.code.UserType;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.resource.model.ResourceEntity;
import com.mortals.xhx.base.system.resource.service.ResourceService;
import com.mortals.xhx.common.code.AuthType;
import com.mortals.xhx.common.code.SourceType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 资源信息
 *
 * @author: zxfei
 * @date: 2022/5/7 15:27
 */
@Slf4j
@RestController
@RequestMapping("resource")
public class ResourceController extends BaseCRUDJsonBodyMappingController<ResourceService,ResourceEntity,Long> {

	public ResourceController(){
		super.setModuleDesc("资源信息");
	}

	@Override
	protected void init(Map<String, Object> model, Context context) {
		Map<String, Object> statsus = new HashMap<String, Object>();
		statsus.put("authType", AuthType.getEnumMap());
		statsus.put("sourceType", SourceType.getEnumMap());
		if (getCurUser().isAdmin()) {
			statsus.put("userType",  IBaseEnum.getEnumMap(UserType.class));
		} else {
			statsus.put("userType", UserType.findByValue(getCurUser().getUserType()));
		}
		model.put(KEY_RESULT_DICT, statsus);
	}

	/**
	 * 获取所有资源
	 *
	 * @return
	 */
	@PostMapping("allResources")
	public String allResources(int userType) {
		JSONObject ret = new JSONObject();
		ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
		ret.put(KEY_RESULT_MSG, "所有的customer以及user");
		ret.put(KEY_RESULT_DATA, service.findAll(userType));
		return ret.toJSONString();
	}

	/**
	 * 资源路径刷新
	 */
	@GetMapping(value = "refreshUrl")
	@UnAuth
	public Rest<String> refreshUrl(@RequestParam(name = "packageName", defaultValue = "com.mortals.xhx") String packageName) {
		log.info("刷新资源路径，packageName", packageName);
		String busiDesc = this.getModuleDesc() + "资源路径刷新";
		Rest<String> rest = Rest.ok(busiDesc + " 【成功】");
		try {
			this.service.refreshResourceUrl(packageName, getContext());
			recordSysLog(request, busiDesc + " 【成功】");
		} catch (Exception e) {
			log.error(busiDesc, e);
			rest = Rest.fail(super.convertException(e));
		}
		return rest;
	}
	
}