package com.winsun.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.winsun.bean.School;
import com.winsun.mapper.HhrUserMapper;
import com.winsun.mapper.SchoolMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.enums.SqlLike;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.winsun.auth.core.annotion.Permission;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.shiro.ShiroUser;

import com.winsun.bean.activity.HhrActivity;
import com.winsun.mapper.activity.ActivityMapper;
import com.winsun.utils.PicturesUtil;

/**
 * @Author: dongyp
 * @Date: 2020/4/9
 */
@RestController
@RequestMapping("/activity")
public class ActivityController extends BaseController {

	@Autowired
	private ActivityMapper activityMapper;
	private static String PATH_TYPE = "activity";

	@Autowired
	private HhrUserMapper hhrUserMapper;

	@Autowired
	private SchoolMapper schoolMapper;

	@Permission(menuname = "查询活动信息", value = "list", method = RequestMethod.POST)
	public ResponseData<Page<HhrActivity>> list(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "status", required = false) String status,
			@RequestParam(name = "createTimeStart", required = false) String createTimeStart,
			@RequestParam(name = "createTimeEnd", required = false) String createTimeEnd,
			@RequestParam(name = "pageNo", required = false) int pageIndex,
			@RequestParam(name = "pageSize", required = false) int pageSize) {
		Wrapper<HhrActivity> wrapper = new EntityWrapper<HhrActivity>();
		wrapper.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapper.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapper.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapper.eq("del_flag", 0);
		wrapper.eq(StringUtils.isNotBlank(status), "status", status);
		
		Page<HhrActivity> page = new Page<>(pageIndex, pageSize);
		List<HhrActivity> list = activityMapper.selectPage(page, wrapper);
		page.setRecords(list);
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "新增活动", value = "addActivity", method = RequestMethod.POST)
	public ResponseData<String> addActivity(@RequestParam("title") String title, @RequestParam("desc") String desc,
			@RequestParam("integral") String integral, @RequestParam("activityType") String activityType, 
			@RequestParam("subclass") String subclass,@RequestParam("imageUrl") String imageUrl,
			@RequestParam("sort") String sort, @RequestParam("range") String range){
		
		ShiroUser user = getShiroUser();

		// 添加活动权限
		boolean hasDataPermission = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "县分管理员（订单）", "系统管理员", "超级管理员"));
		if (!hasDataPermission) {
			return ResponseData.error("无数据权限！");
		}

		// 获取当前用户所属县分
		List<Map<String, Object>> maps = hhrUserMapper.selectHehuorenSchool(user.getId() + "");
		String subName = "";
		String subSchool = "";
		if (maps != null && maps.size() != 0) {
			subName = maps.get(0).get("sub_name") != null ? maps.get(0).get("sub_name").toString() : "";
			subSchool = maps.get(0).get("school_name") != null ? maps.get(0).get("school_name").toString() : "";
		}

		HhrActivity activity = new HhrActivity();
		activity.setTitle(title);
		activity.setDesc(desc);
		activity.setIntegral(Integer.parseInt(integral));
		activity.setActivityType(activityType);
		activity.setSubclass(subclass);
		activity.setSort(Integer.parseInt(sort));
		activity.setRange(range);
		activity.setIsSubName(0);
		activity.setImageUrl(imageUrl);
		activity.setCreator(user.getName());
		activity.setCreateTime(new Date());
		activity.setUpdateTime(new Date());
		activity.setSubName(subName);
		activity.setSubSchool(subSchool);

		boolean isSubManager = user.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "县份管理员（订单）"));
		if (isSubManager && "团队活动".equals(activity.getActivityType())) {
			return ResponseData.error("无权限创建团队活动");
		}
		if (isSubManager && "个人活动".equals(activity.getActivityType())) {
			activity.setIsSubName(1);
			activity.setStatus("0");
			activity.setRange(subName);
		}else{
			activity.setIsSubName(0);
			activity.setStatus("1");
			if ("团队活动".equals(activity.getActivityType())) {
				activity.setRange("全市");
			}
		}

		int num = activityMapper.insert(activity);
		if (num > 0) {
			return ResponseData.success("添加完毕！");
		}

		return ResponseData.error("添加失败");
	}
	
	@Permission(menuname = "修改活动", value = "updateActivity", method = RequestMethod.POST)
	public ResponseData<String> addActivity(@RequestParam("id") String id, 
			@RequestParam("title") String title, @RequestParam("desc") String desc,
			@RequestParam("integral") String integral, @RequestParam("activityType") String activityType, 
			@RequestParam("subclass") String subclass,@RequestParam("imageUrl") String imageUrl,
			@RequestParam("sort") String sort, @RequestParam("range") String range){

		HhrActivity activity = new HhrActivity();
		activity.setId(id);
		activity.setTitle(title);
		activity.setDesc(desc);
		activity.setIntegral(Integer.parseInt(integral));
		activity.setActivityType(activityType);
		activity.setSubclass(subclass);
		activity.setSort(Integer.parseInt(sort));
		activity.setImageUrl(imageUrl);
		activity.setUpdateTime(new Date());
		int num = activityMapper.updateById(activity);
		
		if (num > 0) {
			return ResponseData.success("修改完毕！");
		}

		return ResponseData.error("修改失败");
	}
	
	@Permission(menuname = "删除活动", value = "deleteActivity", method = RequestMethod.POST)
	public ResponseData<String> deleteActivity(@RequestParam("id") String id){

		HhrActivity activity = new HhrActivity();
		activity.setId(id);
		activity.setDelFlag(1);
		int num = activityMapper.updateById(activity);
		
		if (num > 0) {
			return ResponseData.success("删除完毕！");
		}

		return ResponseData.error("删除失败");
	}

	/**
	 * 审核活动
	 * @param activityId
	 * @param status
	 * @return
	 */
	@Permission(menuname = "审核活动", value = "auditActivity", method = RequestMethod.POST)
	public ResponseData<String> auditActivity(@RequestParam("activityId") String activityId,@RequestParam("status") String status) {

		ShiroUser shiroUser = getShiroUser();
		boolean b = shiroUser.getRoleNames().stream().anyMatch(data -> StringUtils.equalsAny(data, "系统管理员", "超级管理员"));
		if (!b) {
			return ResponseData.error("无权审核");
		}

		if (!"1".equals(status) && !"2".equals(status)) {
			return ResponseData.error("审核状态错误");
		}

		HhrActivity hhrActivity = new HhrActivity();
		hhrActivity.setId(activityId);
		hhrActivity.setStatus(status);
		Integer integer = activityMapper.updateById(hhrActivity);

		if (integer > 0) {
			return ResponseData.success("", "审核成功！");
		}

		return ResponseData.error("审核失败！");
	}
	
	/**
     * 查询活动列表
     *
     * @param pageNo      查询页码 默认首页
     * @param pageSize    查询每页数量 默认10
     * @param activityType 查询条件-活动类型
     * @param subclass   查询条件-活动小类
     * @return
     */
	@Permission(menuname = "获取活动列表", value = "getActivityList", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getActivityList(Integer pageNo, Integer pageSize, String activityType,  String subclass, String status) {
		try{
			Wrapper<HhrActivity> wrapper = new EntityWrapper<HhrActivity>();
			wrapper.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
			wrapper.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
			wrapper.eq(StringUtils.isNotBlank(status), "status", status);
			wrapper.eq("del_flag", 0);

			Page<HhrActivity> page = new Page<>(pageNo == null ? 1 : pageNo, pageSize == null ? 10 : pageSize);
			List<HhrActivity> list = activityMapper.selectPage(page, wrapper);
			page.setRecords(list);
			resultMap.put("activityList", list);

			return ResponseData.success(resultMap, "查询成功");
		}catch(Exception e){
			e.printStackTrace();
			return ResponseData.error("查询失败！");
		}
    }

	/**
	 * 移动端获取活动列表
	 * @return
	 */
	@Permission(menuname = "获取活动列表", value = "mobileGetActivityList", method = RequestMethod.POST)
	public ResponseData<Map<String, Object>> mobileGetActivityList(Integer pageNo,
		   Integer pageSize, String activityType, String subclass,
		   String status) {

		ShiroUser shiroUser = getShiroUser();

		String s = schoolMapper.selectSchoolIdByUserId(shiroUser.getId() + "");

		if (StringUtils.isBlank(s)) {
			return ResponseData.error("请先设置所在学校");
		}

		if (shiroUser == null || shiroUser.getId() == null) {
			return ResponseData.error("查询列表失败！");
		}

		School school = schoolMapper.selectById(s);
		if (school == null) {
				return ResponseData.error("学校信息有误");
		}

		try {

			Page<HhrActivity> page = new Page<>(pageNo == null ? 1 : pageNo, pageSize == null ? 10 : pageSize);
			List<Map<String, Object>> maps = activityMapper.mobileSelectActivityList(page, school.getSubName(), subclass, activityType);
			resultMap.put("activityList", maps);
			return ResponseData.success(resultMap, "查询成功！");

		}catch (Exception e) {
			e.printStackTrace();
			return ResponseData.error("查询失败！");
		}
	}
    
	/**
     * 获取活动信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getActivityInfo", method = RequestMethod.POST)
    public ResponseData<Map<String, Object>> getActivityInfo(String id) {
		HhrActivity activity = activityMapper.selectById(id);
		Map<String, Object> activityMap = JSON.parseObject(JSON.toJSONString(activity), Map.class);

        return ResponseData.success(activityMap, "查询成功");
    }
    
    @Permission(menuname = "上传图片",value = "uploadImg", method = RequestMethod.POST)
    public ResponseData<String> uploadImg(@RequestParam("picture") String picture) {
        ShiroUser user = getShiroUser();
        Integer userId=user.getId();
        String path = PicturesUtil.uploadPictures(picture, userId.toString(),PATH_TYPE);

        if(StringUtils.isNoneBlank(path)){
            return ResponseData.success(path, "上传成功");
        }
        return ResponseData.error("上传图片失败！");
    }
    
}
