package com.ssj.sys.controller;

import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.sys.teacher.domain.ApplyTeacher;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.bean.weixin.libmy.domain.TbLibManagerAudit;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.conch.push.util.PushConstants;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.Constant;
import com.ssj.service.conch.teacher.service.IApplyTeachService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.library.service.IBookManagerService;
import com.ssj.service.weixin.library.service.LibManagerAuditService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.util.*;

@Controller
@RequestMapping("/sys/audit")
public class TeacherAuditController extends BaseController {

	
	@Autowired
	private IApplyTeachService applyService;
	
	@Autowired
	private IBookManagerService managerService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private TokenManager  tokenManager;

	@Autowired
	private PushTemplateService pushTemplateService;

	@Autowired
	private SconXingeService sconXingeService;

	@Autowired
	private LibManagerAuditService libManagerAuditService;
	
	/**
	 * 老师审核列表列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/TeacherAuditList")
	public String TeacherAuditList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
			throws Exception {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("LIKE_realName", request.getParameter("LIKE_realName")==null?"":request.getParameter("LIKE_realName"));
//		params.put("GTE_type", "1");
		SplitPage sp = new SplitPage();
        sp.setAction(request.getRequestURI().toString());
        sp.setPageNo(pageNo);
        sp.setPageSize(pageSize);
        sp.setParams(params);
	    Page<ApplyTeacher> page= applyService.findByPage(params, initPage(pageNo,pageSize,Direction.DESC, new String[] { "createTime" }));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);

		return "sys/audit/teacherAuditList";
	}

	/**
	 * 审核
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	 @RequestMapping("/teacherAudit")
	 public String teacherAudit(Model model,@RequestParam( defaultValue = "0")String id) throws Exception {

		ApplyTeacher teacher = applyService.getById(id);
		List<String> labelList = Arrays.asList(teacher.getPersonalLabel().split(","));
		model.addAttribute("ws", teacher);
		model.addAttribute("labelList", labelList);

		String[] imgList2 = teacher.getTitleImg().split(",");
		 List<String> titleImgList  = Arrays.asList(imgList2);
		String[] imgList = teacher.getTeacherImg().split(",");
		 List<String>  ImgList = Arrays.asList(imgList);
		model.addAttribute("oneImg", ImgList.get(0));
		model.addAttribute("towImg", ImgList.get(1));
		model.addAttribute("titleImgList", titleImgList);
		return "sys/audit/teacherAudit";
	 }
	
	 /**
	  * 保存
	  * @param lib
	  * @return
	 * @throws Exception 
	  */
	 @RequestMapping(value = "/auditSave", method = RequestMethod.POST)
	 @ResponseBody
	 public Response auditSave(  ApplyTeacher lib) throws Exception{
		 Response response = new Response();
		 Map<String,String> data =new HashMap<>();
		 String contentMessage = "";
		 ApplyTeacher teacher = applyService.getById(lib.getId());
		 //审核通过
		 if ("2".equals(lib.getAuditState())) {
			 /**
			  * 查询 校长为空的，type=7 审核通过的初始记录
			  */
			 TbLibManager manager = managerService.findByOnoTwoOnoTearcher(teacher.getUserId());
			 if (manager == null) {
				 //审核通过新增数据
				 manager = new TbLibManager();
				 manager.setCourseName(teacher.getSubject());
				 manager.setCreateTime(new Date());
				 manager.setName(teacher.getRealName());
				 manager.setSchoolAge(teacher.getSchoolAge());
				 manager.setSex(teacher.getSex());
				 manager.setState(1);
				 manager.setTeacherLever(lib.getTeacherLever());
				 manager.setTeacherType(lib.getTeacherType());
				 manager.setType(7);
				 manager.setTelephone(teacher.getConcatPhone());
				 manager.settPhoto(teacher.getHeadPicUrl());
				 manager.setUserId(teacher.getUserId());
				 manager.setPersonalInfo(lib.getPersonalInfo());
				 manager.setPersonalLabel(teacher.getPersonalLabel());
				 manager.setTeachPoint(lib.getTeachPoint());
				 teacher.setSuccessfulCase(lib.getSuccessfulCase());
			 } else {
				 manager.setTeacherLever(lib.getTeacherLever());
				 manager.setTeacherType(lib.getTeacherType());
			 }
			 userService.generateQrcode(teacher.getUserId());
			 manager=managerService.save(manager);

			 TbLibManager lessonGroupTeacher = managerService.findByUserIdAndType(teacher.getUserId(), Constant.GROUP_TEACHER_TYPE);
			 if (lessonGroupTeacher == null) {
				 lessonGroupTeacher = new TbLibManager();
				 lessonGroupTeacher.setUserId(teacher.getUserId());
				 lessonGroupTeacher.setType(Constant.GROUP_TEACHER_TYPE);
				 lessonGroupTeacher.setCreateTime(new Date());
				 lessonGroupTeacher.setName(teacher.getRealName());
				 lessonGroupTeacher.setTelephone(teacher.getConcatPhone());
				 lessonGroupTeacher.setSex(teacher.getSex());
				 lessonGroupTeacher.setCourseName(teacher.getSubject());
				 lessonGroupTeacher.settPhoto(teacher.getHeadPicUrl());
				 lessonGroupTeacher.setState(1);
				 lessonGroupTeacher.setSchoolAge(teacher.getSchoolAge());
				 lessonGroupTeacher.setPersonalInfo(lib.getPersonalInfo());
				 lessonGroupTeacher.setPersonalLabel(teacher.getPersonalLabel());
				 lessonGroupTeacher.setTeachPoint(lib.getTeachPoint());
				 lessonGroupTeacher.setSuccessfulCase(lib.getSuccessfulCase());
				 lessonGroupTeacher.setTeacherLever("");
				 lessonGroupTeacher= managerService.save(lessonGroupTeacher);
			 }
			 contentMessage = "敬爱的"+teacher.getRealName()+"老师您好，您提交的老师注册申请已审核通过，请及时查看。";
		 }else if("3".equals(lib.getAuditState())){
			 contentMessage = "敬爱的"+teacher.getRealName()+"老师您好，您提交的老师注册申请审核未通过，请及时查看。";
		 }
		 teacher.setAuditState(lib.getAuditState());
		 teacher.setTeacherType(lib.getTeacherType());
		 teacher.setTeacherLever(lib.getTeacherLever());
		 teacher.setPersonalInfo(lib.getPersonalInfo());
		 teacher.setTeachPoint(lib.getTeachPoint());
		 teacher.setSuccessfulCase(lib.getSuccessfulCase());
		 teacher.setAuditTime(new Date());
		 teacher=applyService.save(teacher);

		 /** 公众号推送
		  * 用户姓名
		  * {{keyword1.DATA}}
		  * 审核类型
		  * {{keyword2.DATA}}
		  * 审核状态
		  * {{keyword3.DATA}}
		  * 审核时间
		  * {{keyword4.DATA}}
		  */
		 data.put("first", contentMessage);
		 data.put("keyword1",teacher.getRealName());
		 data.put("keyword2", teacher.getTeacherType());
		 data.put("keyword3", "2".equals(lib.getAuditState()) ? " 审核通过" : "审核未通过");
		 data.put("keyword4", DateHelper.format(teacher.getAuditTime(),"yyyy年MM月dd日"));
		 String template_id="gS0ezxsv4U3E3k3gU7yjWYTeQi95M_8HEI-uvVTci4c";
		 String openId = userService.getById(teacher.getUserId()).getAccount();
		 SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, null, data);
		 pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		 //信鸽推送老师端
		 sconXingeService.asynPushThreadTask(teacher.getUserId(),null,4,contentMessage,PushConstants.PUSH_OTHER);

		 String token = tokenManager.getToken(teacher.getUserId(),"WX");
		 if (token != null && !"".equals(token)) {
			 tokenManager.removeToken(token,"WX");
		 }
		 token = tokenManager.getToken(teacher.getUserId(),"APP");
		 if (token != null && !"".equals(token)) {
			 tokenManager.removeToken(token,"APP");
		 }

		 response.success();
		 return response;
	 }

	@RequestMapping("/orgTeacherAuditList")
	public String orgTeacherAuditList(Model model,
									  @RequestParam(required = false, defaultValue = "10") int pageSize,
									  @RequestParam(required = false, defaultValue = "1") int pageNo) {
		Map<String, Object> params = new HashMap<>(16);
		params.put("LIKE_name", request.getParameter("LIKE_name") == null ? "" : request.getParameter("LIKE_name"));
		params.put("EQ_type", 10);
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<TbLibManagerAudit> page = libManagerAuditService.findByPage(params, initPage(pageNo, pageSize, Direction.DESC, new String[]{"createTime"}));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		return "sys/audit/orgTeacherAuditList";
	}

	/**
	 * 审核
	 * @param model
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/orgTeacherAudit")
	public String orgTeacherAudit(Model model,@RequestParam( defaultValue = "0")String id) {
		TbLibManagerAudit teacher = libManagerAuditService.getById(id);
		model.addAttribute("ws", teacher);
		return "sys/audit/orgTeacherAudit";
	}

	@RequestMapping(value = "/orgAuditSave", method = RequestMethod.POST)
	@ResponseBody
	public Response orgAuditSave(TbLibManagerAudit audit) throws Exception {
		Response response = new Response();
		Map<String, String> data = new HashMap<>(16);
		String contentMessage = "";
		TbLibManagerAudit teacher = libManagerAuditService.getById(audit.getId());
		TbLibManager manager = managerService.getById(teacher.getLibManagerId());
		//有效
		manager.setState(1);
		//审核通过
		if (audit.getStatus()==1) {
			if (manager == null) {
				manager = new TbLibManager();
				//机构老师
				manager.setType(10);
				manager.setCreateTime(new Date());
			}
			manager.setName(teacher.getName());
			manager.setSex(teacher.getSex());
			manager.setTelephone(teacher.getTelephone());
			manager.setCourseName(teacher.getSubject());
			manager.setLon(teacher.getLon());
			manager.setLat(teacher.getLat());
			manager.setAddress(teacher.getAddress());
            manager.setOrgId(teacher.getOrgId());
			manager.setOrgName(teacher.getOrgName());
			manager.setCertification(teacher.getCertification());
			manager.setIdFace(teacher.getIdFace());
			manager.setIdCon(teacher.getIdCon());
			manager=managerService.save(manager);
			teacher.setLibManagerId(manager.getId());
			//尊敬的某某老师您好，您在“私塾家问老师”的资料审核已通过
			contentMessage = "尊敬的" + teacher.getName() + "老师您好，您在“私塾家问老师”的资料审核已通过";
		} else if (audit.getStatus() == 2) {
			contentMessage = "尊敬的" + teacher.getName() + "老师您好，您在“私塾家问老师”的资料审核未通过，请重新完善资料！";
		}
		//审批状态
		teacher.setStatus(audit.getStatus());
		//审批时间
		teacher.setLastUpdateTime(new Date());
		teacher=libManagerAuditService.save(teacher);
		/**
		 * 公众号推送-审核结果通知
		 * {{first.DATA}}
		 * 审核事项：{{keyword1.DATA}}
		 * 审核状态：{{keyword2.DATA}}
		 * 审核时间：{{keyword3.DATA}}
		 * {{remark.DATA}}
		 */
		data.put("first", contentMessage);
		data.put("keyword1", "资料审核");
		data.put("keyword2", 1 == audit.getStatus() ? " 审核通过" : "审核未通过");
		data.put("keyword3", DateHelper.format(teacher.getLastUpdateTime(), "yyyy年MM月dd日 HH时mm分"));
		String template_id = "OPENTM408894858";
		String openId = userService.getById(manager.getUserId()).getAccount();
		SendTemplateShort sendTemplateShort = new SendTemplateShort(openId, template_id, null, data);
		//微信推送
		pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
		/*String token = tokenManager.getToken(manager.getUserId());
		if (token != null && !"".equals(token)) {
			tokenManager.removeToken(token);
		}*/
		response.success();
		return response;
	}
}
