package com.winsun.controller;

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.auth.core.util.IOUtils;
import com.winsun.bean.School;
import com.winsun.bean.SysUser;
import com.winsun.bean.activity.HhrActivity;
import com.winsun.bean.activity.HhrActivityRecord;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.mapper.OrderViewMapper;
import com.winsun.mapper.PartnerMapper;
import com.winsun.mapper.SchoolMapper;
import com.winsun.mapper.SysUserMapper;
import com.winsun.mapper.activity.ActivityMapper;
import com.winsun.mapper.activity.ActivityRecordMapper;
import com.winsun.utils.ExcelDealUtils;
import com.winsun.utils.MapUtil;
import com.winsun.utils.PicturesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 活动参与记录 controller
 * @Author: dongyp
 * @Date: 2020/4/14 
 */
@Slf4j
@RestController
@RequestMapping("/activityRecord")
public class ActivityRecordController extends BaseController {

	private static ActivityRecordMapper activityRecordMapper;
	private static ActivityMapper activityMapper;
	private static SysUserMapper sysUserMapper;
	private static SchoolMapper schoolMapper;
	
	@Autowired
	private PartnerMapper partnerMapper;
	@Autowired
	private OrderViewMapper orderViewMapper;

	@Autowired
	public ActivityRecordController(ActivityRecordMapper activityRecordMapper,ActivityMapper activityMapper,SysUserMapper sysUserMapper,SchoolMapper schoolMapper) {
		ActivityRecordController.activityRecordMapper = activityRecordMapper;
		ActivityRecordController.activityMapper = activityMapper;
		ActivityRecordController.sysUserMapper = sysUserMapper;
		ActivityRecordController.schoolMapper = schoolMapper;
	}
	
	@Permission(menuname = "查询活动参与信息", value = "list", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> list(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "status", required = false) String status,
			@RequestParam(name = "creator", required = false) String creator,
			@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> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		wrapperRecord.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperRecord.eq(StringUtils.isNotBlank(status), "status", status);
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					
					newList.add(map);
				}
			}
		}
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageSize) {
			dataList = newList;
		}else {
			dataList = newList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(dataList);
		page.setTotal(newList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "审核活动参与记录", value = "auditActivityRecord", method = RequestMethod.POST)
	public ResponseData<String> auditActivityRecord(@RequestParam("id") String id, 
			@RequestParam("status") String status, @RequestParam("integral") Integer integral,
			@RequestParam("remark") String remark){

		HhrActivityRecord activityRecord = new HhrActivityRecord();
		activityRecord.setId(id);
		activityRecord.setStatus(status);
		if ("3".equals(status)) {
			activityRecord.setRecordIntegral(0);
		}else{
			activityRecord.setRecordIntegral(integral);
		}
		activityRecord.setRemark(remark);
		activityRecord.setUpdateTime(new Date());
		int num = activityRecordMapper.updateById(activityRecord);
		if (num > 0) {
			return ResponseData.success("审核完毕！");
		}
		return ResponseData.error("审核失败");
	}

	@Permission(menuname = "审核活动参与记录", value = "auditActivityRecords", method = RequestMethod.POST)
	public ResponseData<String> auditActivityRecords(@RequestParam(value = "id",required = false) String id,
													 @RequestParam("ids") String ids,
													 @RequestParam("status") String status, @RequestParam("integral") Integer integral,
													 @RequestParam("remark") String remark){
		if(integral==null){
			return ResponseData.error("所得积分不得为空！");
		}
		List<String> list1 = new ArrayList<>();
		List<Integer> list = new ArrayList<>();
		Wrapper<HhrActivityRecord> wrapper = new EntityWrapper<>();
		if(id != null && StringUtils.isNotBlank(id)){
			wrapper.eq("id",id);
		}else {
			list1 = Arrays.asList(ids.split(",")); //[a, b, c]
			for (String s : list1) {
				list.add(Integer.valueOf(s));
			}
			wrapper.in("id",list);
		}

		HhrActivityRecord activityRecord = new HhrActivityRecord();
		activityRecord.setStatus(status);
		if ("3".equals(status)) {
			activityRecord.setRecordIntegral(0);
		}else{
			activityRecord.setRecordIntegral(integral);
		}
		activityRecord.setRemark(remark);
		activityRecord.setUpdateTime(new Date());
		int num = activityRecordMapper.update(activityRecord,wrapper);
		if (num > 0) {
			return ResponseData.success("审核完毕！");
		}
		return ResponseData.error("审核失败");
	}


	@Permission(menuname = "查询积分记录信息", value = "getIntegralList", method = RequestMethod.POST)
	public ResponseData<Page<Map<String, Object>>> getIntegralList(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "account", required = false) String account,
			@RequestParam(name = "name", required = false) String name,
			@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> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Wrapper<SysUser> wrapperUser = new EntityWrapper<SysUser>();
		wrapperUser.like(StringUtils.isNotBlank(name), "name", name, SqlLike.DEFAULT);
		wrapperUser.eq(StringUtils.isNotBlank(account), "account", account);
		List<SysUser> userList = sysUserMapper.selectList(wrapperUser);
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);
		
		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		for(SysUser sysUser : userList) {
			String userId = sysUser.getId();
			if(null != refMap.get(userId)) {
				for(School school : schoolList) {
					if(refMap.get(userId).toString().equals(school.getId())) {
						sysUser.setSubstName(school.getSubName());
						sysUser.setSchoolName(school.getSubName());
					}
				}
			}
		}
		
		
		Page<Map<String, Object>> page = new Page<>(pageIndex, pageSize);
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			Map<String, Object> map = new HashMap<String, Object>();
			int num = 0;
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					num++;
					break;
				}
			}
			
			for(SysUser sysUser : userList) {
				if(sysUser.getId().equals(activityRecord.getCreateId())) {
					map.put("account", sysUser.getAccount());
					map.put("name", sysUser.getName());
					map.put("substName", sysUser.getSubstName());
					map.put("schoolName", sysUser.getSchoolName());
					num++;
					break;
				}
			}
			
			if(num == 2) {
				newList.add(map);
			}
		}
		
		List<Map<String, Object>> dataList = new ArrayList<Map<String,Object>>();
		if(newList.size() < pageSize) {
			dataList = newList;
		}else {
			dataList = newList.subList((pageIndex-1)*pageSize, pageIndex*pageSize);
		}
		
		page.setRecords(dataList);
		page.setTotal(newList.size());
		return ResponseData.success(page, "查询完毕！");
	}
	
	@Permission(menuname = "导出活动积分记录", value = "exportIntegralRecord", method = RequestMethod.POST)
    public void exportIntegralRecord(@RequestParam("title") String title,
			@RequestParam("activityType") String activityType, @RequestParam("subclass") String subclass,
			@RequestParam(name = "status", required = false) String status,
			@RequestParam(name = "creator", required = false) String creator,
			@RequestParam(name = "createTimeStart", required = false) String createTimeStart,
			@RequestParam(name = "createTimeEnd", required = false) String createTimeEnd
    		) throws IOException {

        Wrapper<HhrActivity> wrapperActivity = new EntityWrapper<HhrActivity>();
		wrapperActivity.like(StringUtils.isNotBlank(title), "title", title, SqlLike.DEFAULT);
		wrapperActivity.eq(StringUtils.isNotBlank(activityType), "activity_type", activityType);
		wrapperActivity.eq(StringUtils.isNotBlank(subclass), "subclass", subclass);
		wrapperActivity.eq("del_flag", 0);
		List<HhrActivity> listActivity = activityMapper.selectList(wrapperActivity);
		
		Wrapper<HhrActivityRecord> wrapperRecord = new EntityWrapper<HhrActivityRecord>();
		wrapperRecord.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperRecord.eq(StringUtils.isNotBlank(status), "status", status);
		List<HhrActivityRecord> listRecord = activityRecordMapper.selectList(wrapperRecord);
		
		Wrapper<SysUser> wrapperUser = new EntityWrapper<SysUser>();
		wrapperUser.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperUser.eq(StringUtils.isNotBlank(status), "status", status);
		List<SysUser> userList = sysUserMapper.selectList(wrapperUser);
		
		Wrapper<School> wrapperSchool = new EntityWrapper<School>();
		wrapperSchool.like(StringUtils.isNotBlank(creator), "creator", creator, SqlLike.DEFAULT);
		wrapperSchool.eq(StringUtils.isNotBlank(status), "status", status);
		List<School> schoolList = schoolMapper.selectList(wrapperSchool);
		
		Map<String, Object> refMap = MapUtil.listToMap(schoolMapper.getSchoolRef(), "user_id", "school_id");
		
		for(SysUser sysUser : userList) {
			String userId = sysUser.getId();
			if(null != refMap.get(userId)) {
				for(School school : schoolList) {
					if(refMap.get(userId).toString().equals(school.getId())) {
						sysUser.setSubstName(school.getSubName());
						sysUser.setSchoolName(school.getSubName());
					}
				}
			}
		}
		
		List<Map<String, Object>> newList = new ArrayList<Map<String,Object>>();
		for(HhrActivityRecord activityRecord : listRecord) {
			String activityId = activityRecord.getActivityId();
			Map<String, Object> map = new HashMap<String, Object>();
			int num = 0;
			
			for(HhrActivity activity : listActivity) {
				if(activityId.equals(activity.getId())) {
					
					map.put("title", activity.getTitle());
					map.put("desc", activity.getDesc());
					map.put("integral", activity.getIntegral());
					map.put("activityType", activity.getActivityType());
					map.put("subclass", activity.getSubclass());
					map.put("id", activityRecord.getId());
					map.put("status", activityRecord.getStatus());
					map.put("remark", activityRecord.getRemark());
					map.put("recordIntegral", activityRecord.getRecordIntegral());
					map.put("creator", activityRecord.getCreator());
					map.put("message", activityRecord.getMessage());
					map.put("createTime", activityRecord.getCreateTime());
					num++;
				}
			}

			for(SysUser sysUser : userList) {
				if(sysUser.getId().equals(activityRecord.getCreateId())) {
					map.put("account", sysUser.getAccount());
					map.put("name", sysUser.getName());
					map.put("substName", sysUser.getSubstName());
					map.put("schoolName", sysUser.getSchoolName());
					num++;
				}
			}
			
			if(num == 2) {
				newList.add(map);
			}
		}
		

        ServletOutputStream os = null;
        XSSFWorkbook workbook = ExcelDealUtils.getWorkBook(ExcelDealUtils.activityExcel("积分清单"), newList);
        try {

            HttpServletResponse response = getHttpServletResponse();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("文件出错！" + e.getMessage(), e);
        } finally {
            IOUtils.closeQuite(workbook, os);
        }
    }
	 
	 /**
     * 保存活动参与记录（微信端）
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "addActivityRecord", method = RequestMethod.POST)
    public ResponseData<String> getActivityInfo(String activityId,String message,String imageUrl) {
    	ShiroUser user = ShiroKit.getUser();
    	String filePath = "";
		if(StringUtils.isNotBlank(imageUrl)){
			filePath  = PicturesUtil.uploadPictures(imageUrl, activityId,"activity");
		}
		HhrActivityRecord activityRecord = new HhrActivityRecord();
		activityRecord.setActivityId(activityId);
		activityRecord.setStatus("1");
		activityRecord.setMessage(message);
		activityRecord.setImageUrl(filePath);
		activityRecord.setCreateId(Integer.toString(user.getId()));
		activityRecord.setCreator(user.getName());
		activityRecord.setCreateTime(new Date());
		
		int num = activityRecordMapper.insert(activityRecord);
		if(num > 0) {
			return ResponseData.success("提交成功！");
		}

		return ResponseData.error("提交失败！");
    }
	
}
