package com.yizhi.application.calendar;

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

import com.baomidou.mybatisplus.plugins.Page;
import com.yizhi.application.point.constant.PointEventEnum;
import com.yizhi.calendar.application.feign.StudentCalendarClient;
import com.yizhi.calendar.application.vo.CalendarRecordVO;
import com.yizhi.calendar.application.vo.CalendarSignViewVO;
import com.yizhi.calendar.application.vo.HeadVO;
import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.point.application.feign.PointListenerClients;
import com.yizhi.point.application.feign.PointRedisFeignClients;
import com.yizhi.point.application.vo.PointParamVO;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(tags = "学员端-签到打卡接口")
@RestController
@RequestMapping("/api/calendar")
public class StudentCalendarController {

	private static final Logger logger = LoggerFactory.getLogger(StudentCalendarController.class);

	@Autowired
	private StudentCalendarClient studentCalendarClient;

    @Autowired
    private PointRedisFeignClients pointRedisFeignClients;

	@Autowired
	private PointListenerClients pointListenerClients;

	@ApiOperation(value = "新增签到")
	@GetMapping(value = "/addPoint")
	public Response<Object> addPoint(@RequestParam("code") String code,@RequestParam("sourceId") Long sourceId) {
		return Response.ok(pointListenerClients.addPoint(code,sourceId));
	}
    
    /*@Autowired
    private AmqpTemplate amqpTemplate;*/
    
	@ApiOperation(value = "签到打卡")
	@GetMapping(value = "/sign")
	public Response<Map<String, Object>> sign() {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		String accountName = res.getAccountName();
		Long companyId = res.getCompanyId();
		Long orgId = res.getOrgId();
		try {
			Map<String, Object> map = studentCalendarClient.sign(accountId, siteId);
			Integer point = (Integer) map.get("point");
			Long signId = (Long) map.get("signId");
			if (point!=null) {
                try {
                    PointParamVO pointParamVO = new PointParamVO();
                    pointParamVO.setEventName(PointEventEnum.POINTSIGN.getKey());    //事件名称
                    pointParamVO.setActivityType("签到打卡成功积分发放");                //事件类型
                    pointParamVO.setActivitySource("打卡");                            //学习活动来源
                    pointParamVO.setActivityName("签到打卡");                //学习活动名称
                    pointParamVO.setReleaseCondition("指定积分发放");                    //发放条件
                    pointParamVO.setReleaseRules("签到打卡成功");                    //发放规则
                    pointParamVO.setCreatePointTime(new Date());                            //积分创建时间
                    pointParamVO.setSourceId(signId);                        //积分来源ID，（业务ID主键）
                    pointParamVO.setOperatingPoint(point);                //积分数量，  正数 加积分，  负数减积分
                    pointParamVO.setAccountId(accountId);        //学员ID
                    pointParamVO.setAccountName(accountName);    //学员名称
                    pointParamVO.setCompanyId(companyId);        //企业ID
                    pointParamVO.setSiteId(siteId);                //站点ID
                    pointParamVO.setOrgId(orgId);                //组织ID
                    String sitePointId = null;
                    if (null != point && 0 != point) {
                        sitePointId = pointRedisFeignClients.addPointRedis(pointParamVO);    //调用积分接口添加积分
                    }
                    if (null != sitePointId) {
                        //amqpTemplate.convertAndSend(MQqueuesEnum.SIGN.getKey(), sitePointId);    //发送积分获取消息
                    }
                } catch (Exception e) {
                    logger.error("签到打卡积分发放失败：", e);
                }
			}
			return Response.ok(map);
		} catch (Exception e) {
			logger.error(accountId + "签到打卡业务处理失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}

	@ApiOperation(value = "用户每日签到详情", response = CalendarSignViewVO.class)
	@GetMapping(value = "/isSign")
	public Response<CalendarSignViewVO> isSign() {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		try {
			CalendarSignViewVO sign = studentCalendarClient.isSign(accountId, siteId);
			return Response.ok(sign);
		} catch (Exception e) {
			logger.error(accountId + "每日签到详情查询失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}

	@ApiOperation(value = "签到打卡头部数据", response = HeadVO.class)
	@GetMapping("/head")
	public Response<HeadVO> headData() {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		try {
			HeadVO vo = studentCalendarClient.getHeadData(accountId, siteId);
			return Response.ok(vo);
		} catch (Exception e) {
			logger.error(accountId + "用户签到头部数据查询失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}

	@ApiOperation(value = "用户签到明细", response = CalendarRecordVO.class)
	@GetMapping(value = "/detail")
	public Response<Object> detail(
			@ApiParam(name = "type", value = "1为本周，2为上周，3为本月，4为上月，5为全部", required = true) @RequestParam(name = "type", required = true, defaultValue = "1") Integer type,
			@ApiParam(name = "pageNo", value = "跳转页数,默认第一页", required = false) @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@ApiParam(name = "pageSize", value = "每页条数,默认20条", required = false) @RequestParam(name = "pageSize", defaultValue = "20") Integer pageSize) {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		try {
			Page<CalendarRecordVO> page = studentCalendarClient.getSignDetail(accountId, siteId, type, pageNo, pageSize);
			Map<String, Integer> pageMap = new HashMap<String, Integer>();
			pageMap.put("pageNo", pageNo);
			pageMap.put("pageSize", pageSize);
			pageMap.put("pageTotal", page.getTotal());
			return Response.ok(page.getRecords(), pageMap);
		} catch (Exception e) {
			logger.error(accountId + "用户签到明细查询失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}

	@ApiOperation(value = "用户签到日历",response = CalendarRecordVO.class)
	@GetMapping(value = "/month")
	public Response<CalendarRecordVO> selectByMonth(
			@ApiParam(name = "month", value = "所选月份", required = true) @RequestParam(name = "month", required = true) String month) {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		try {
			List<CalendarRecordVO> list = studentCalendarClient.getSignByMonth(accountId, siteId, month);
			return Response.ok(list);
		} catch (Exception e) {
			logger.error(accountId + "用户签到日历查询失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}
	
	@ApiOperation(value = "用户签到状态",notes = "0未签到 1已签到")
	@GetMapping(value = "/getSignState")
	public Response<Integer> getSignState() {
		RequestContext res = ContextHolder.get();
		Long accountId = res.getAccountId();
		Long siteId = res.getSiteId();
		try {
			Integer state = studentCalendarClient.getSignState(accountId, siteId);
			return Response.ok(state);
		} catch (Exception e) {
			logger.error(accountId + "用户签到状态查询失败！！！" + e);
			return Response.fail(ReturnCode.BIZ_FAIL.getCode(),ReturnCode.BIZ_FAIL.getMsg());
		}
	}
}
