package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.*;
import cn.wise.sc.cement.business.mapper.PlanTrainingMapper;
import cn.wise.sc.cement.business.mapper.PlanPeopleMapper;
import cn.wise.sc.cement.business.mapper.SysGroupMapper;
import cn.wise.sc.cement.business.mapper.SysUserMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.PlanTrainingQuery;
import cn.wise.sc.cement.business.model.vo.PlanTrainingVo;
import cn.wise.sc.cement.business.model.vo.UserVo;
import cn.wise.sc.cement.business.service.IPlanTrainingService;
import cn.wise.sc.cement.business.service.IPlanPeopleService;
import cn.wise.sc.cement.business.service.ISysUserMessageService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wlb
 * @since 2020-10-19
 */
@Service
public class PlanTrainingServiceImpl extends ServiceImpl<PlanTrainingMapper, PlanTraining> implements IPlanTrainingService {
	@Resource
	private PlanTrainingMapper planTrainingMapper;

	@Resource
	private SysGroupMapper sysGroupMapper;

	@Resource
	private SysUserMapper sysUserMapper;

	@Autowired
	private ISysUserService userService;

	@Autowired
	private IPlanPeopleService iPlantPeopleService;

	@Autowired
	private IPlanTrainingService iPlanTrainingService;

	@Resource
	private PlanPeopleMapper plantPeopleMapper;

	@Autowired
	private ISysUserMessageService userMessageService;

	@Autowired
	private WeiXinService weiXinService;

	@Override
	public BaseResponse<IPage<PlanTrainingVo>> getPage(PageQuery pageQuery) {
		Map<String, Object> params = new HashMap<>();
		Page<PlanTrainingVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
		IPage<PlanTrainingVo> pages = planTrainingMapper.getPage(page, params);
		return BaseResponse.okData(pages);
	}

	@Override
	public BaseResponse<List<PlanTrainingVo>> getList(Date start, Date end) {
		Map<String, Object> params = new HashMap<>();
		params.put("start", start);
		params.put("end", end);
		List<PlanTrainingVo> list = planTrainingMapper.getList(params);
		return BaseResponse.okData(list);
	}

	@Override
	public BaseResponse<List<PlanTrainingVo>> getById(Integer id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id);
		List<PlanTrainingVo> list = planTrainingMapper.getById(params);
		return BaseResponse.okData(list);
	}

	@Override
	@Transactional
	public BaseResponse<PlanTraining> create(PlanTrainingQuery query) {
		LoginUser loginUser = userService.getLoginUser();
		if (loginUser == null){
			return BaseResponse.errorMsg("请登录账号");
		}
		PlanTraining cama = new PlanTraining();
		BeanUtils.copyProperties(query, cama);
		cama.setPlanObject("");
		boolean save = this.save(cama);
		if (save) {
			Integer planId = cama.getId();
			//todo 培训关联表对象  ==>plant + 基本用户信息
			List<PlanPeople> batchAdd = new ArrayList<>();
			if (query.getUserIds()!=null) {
				//拆分用户id
				String userIds = query.getUserIds();
				String[] split = userIds.split("、");
				//为每个用户id创建关联表信息s
				for (String userId : split) {
					Integer id = Integer.parseInt(userId);
					UserVo user = sysUserMapper.getById(id);
					PlanPeople planPeople = new PlanPeople();
					planPeople.setPlanId(planId);
					planPeople.setUserId(user.getId());
					planPeople.setName(user.getName());
					planPeople.setAccount(user.getUsername());
					planPeople.setGroupId(user.getGroupId());

					batchAdd.add(planPeople);
					cama.setPlanObject(cama.getPlanObject() + user.getName() + "、");
				}
			}

			if (query.getGroupIds()!=null) {
				//传的GroupIds
				String groupIds = query.getGroupIds();
				String[] split1 = groupIds.split("、");
				List<PlanPeople> batchAdd1 = new ArrayList<>();
				for (String groupId : split1) {
					int gpId = Integer.parseInt(groupId);
					QueryWrapper<SysUser> qw = new QueryWrapper<>();
					qw.eq("group_id", gpId);
					List<SysUser> sysUsers = sysUserMapper.selectList(qw);
					for (SysUser user : sysUsers) {
						PlanPeople planPeople = new PlanPeople();
						planPeople.setPlanId(planId);
						planPeople.setUserId(user.getId());
						planPeople.setName(user.getName());
						planPeople.setAccount(user.getUsername());
						planPeople.setGroupId(user.getGroupId());

						batchAdd.add(planPeople);
//						cama.setPlanObject(cama.getPlanObject() + user.getName() + "、");
					}
					cama.setPlanObject(cama.getPlanObject() + sysGroupMapper.selectById(groupId).getName() + "、");
				}
			}
			iPlantPeopleService.saveBatch(batchAdd);
			String substring = cama.getPlanObject().substring(0, cama.getPlanObject().length() - 1);
			cama.setPlanObject(substring);
			iPlanTrainingService.updateById(cama);
		}

		List<Integer> planPeopleIdList = plantPeopleMapper.getPlanPeopleId(cama.getId());
		if (planPeopleIdList == null){
			return BaseResponse.errorMsg("培训计划信息错误");
		}
		String userIds="";
		for (Integer planId : planPeopleIdList){
			SysUser byId = userService.getById(planId);
			if (byId == null){
				return BaseResponse.errorMsg("培训计划信息错误");
			}
			BaseResponse wrapper = userMessageService.sendMessage(planId, "您有一条新的的培训信息", cama.getId(), SysUserMessage.MessageType.ENTRUST);
			if (wrapper.getCode() != 200){
				return wrapper;
			}
			if (StringUtils.isNotBlank(byId.getWxId())){
				userIds = userIds.equals("")?byId.getWxId():userIds+"|"+byId.getWxId();
			}
		}
		String content="您好！您有一项新的培训计划，请按时前往指定地点进行培训";
		weiXinService.sendTextMessage(userIds,content);

		return BaseResponse.okData(cama);
	}

	@Override
	public BaseResponse<PlanTraining> update(PlanTrainingQuery planTrainingQuery) {
		PlanTraining update = new PlanTraining();
		BeanUtils.copyProperties(planTrainingQuery, update);
		update.setId(planTrainingQuery.getId());

		QueryWrapper<PlanPeople> qw = new QueryWrapper<>();
		qw.eq("plan_id", update.getId());

		update.setPlanObject("");
		boolean remove = iPlantPeopleService.remove(qw);
		if (remove) {
			Integer planId = update.getId();
			List<PlanPeople> batchAdd = new ArrayList<>();
			//todo 培训关联表对象  ==>plant + 基本用户信息
			//拆分用户id
			String userIds = planTrainingQuery.getUserIds();
			String[] split = userIds.split("、");
			if (planTrainingQuery.getUserIds()!=null) {
				//为每个用户id创建关联表信息s
				for (String userId : split) {
					Integer id = Integer.parseInt(userId);
					UserVo user = sysUserMapper.getById(id);
					PlanPeople planPeople = new PlanPeople();
					planPeople.setPlanId(planId);
					planPeople.setUserId(user.getId());
					planPeople.setName(user.getName());
					planPeople.setAccount(user.getUsername());
					planPeople.setGroupId(user.getGroupId());

					batchAdd.add(planPeople);
					update.setPlanObject(update.getPlanObject() + user.getName() + "、");
				}
			}

			if (planTrainingQuery.getGroupIds()!=null) {
				//传的GroupIds
				String groupIds = planTrainingQuery.getGroupIds();
				String[] split1 = groupIds.split("、");
				List<PlanPeople> batchAdd1 = new ArrayList<>();
				for (String groupId : split1) {
					int gpId = Integer.parseInt(groupId);
					QueryWrapper<SysUser> qw1 = new QueryWrapper<>();
					qw1.eq("group_id", gpId);
					List<SysUser> sysUsers = sysUserMapper.selectList(qw1);
					for (SysUser user : sysUsers) {
						PlanPeople planPeople = new PlanPeople();
						planPeople.setPlanId(planId);
						planPeople.setUserId(user.getId());
						planPeople.setName(user.getName());
						planPeople.setAccount(user.getUsername());
						planPeople.setGroupId(user.getGroupId());

						batchAdd.add(planPeople);
//						update.setPlanObject(update.getPlanObject() + user.getName() + "、");
					}
					update.setPlanObject(update.getPlanObject() + sysGroupMapper.selectById(split1).getName() + "、");
				}
			}
			iPlantPeopleService.saveBatch(batchAdd);
			String substring = update.getPlanObject().substring(0, update.getPlanObject().length() - 1);
			update.setPlanObject(substring);
			iPlanTrainingService.updateById(update);
		}

		return BaseResponse.okData(update);
	}

	/**
	 * 判断培训计划是否开始，如果开始，提醒培训人员 每天早上6点
	 * @return
	 */
	@Override
	@Scheduled(cron = "0 0 6 * * *")
//	@Scheduled(cron = "0 * * * * ?")
	public BaseResponse<String> checkplanDate() {
		QueryWrapper<PlanTraining> qw = new QueryWrapper<>();
		qw.eq("remind",1);
		List<PlanTraining> planTrainings = planTrainingMapper.selectList(qw);
		if (planTrainings == null){
			return BaseResponse.errorMsg("目前暂无需要提醒的培训计划");
		}

		String userIds="";
		for (PlanTraining planTraining2 : planTrainings){
			LocalDate remindTime = planTraining2.getRemindTime();
			LocalDate nowDate = LocalDate.now();

			if (remindTime != null && nowDate.equals(remindTime)){
			List<Integer> planPeopleId = plantPeopleMapper.getPlanPeopleId(planTraining2.getId());
			for (Integer checkId : planPeopleId){
				SysUser byId = userService.getById(checkId);
				if (byId == null ){
					return BaseResponse.errorMsg("用户没有该培训计划，信息错误");
				}
				if (StringUtils.isNoneBlank(byId.getWxId())){
					userIds=userIds.equals("")?byId.getWxId():userIds+"|"+byId.getWxId();
				}
			}
				String content="您好！您有一项新的培训计划，记得按时参加";
//				System.out.println("**************************content**********************");
//				System.out.println(content);
//				System.out.println(userIds);
				weiXinService.sendTextMessage(userIds,content);
			}
		}
		return BaseResponse.okMsg("成功");
	}

//	@Override
//	@Transactional
//	public BaseResponse<String> status(Integer status, Integer id) {
//		if(status == null || id == null){
//			return BaseResponse.errorMsg("参数错误!");
//		}
//		PlanTraining planTraining = planTrainingMapper.selectById(id);
//		if(planTraining == null){
//			return BaseResponse.errorMsg("数据错误!");
//		}
//		planTraining.setStatus(status);
//		planTrainingMapper.updateById(planTraining);
//		String result = "";
//		if(planTraining.getStatus() == 1){
//			result = "未通过";
//		}else{
//			result = "通过";
//		}
//		return BaseResponse.okData(result);
//	}

	@Override
	public BaseResponse delete(Integer id) {
		PlanTraining nsa = planTrainingMapper.selectById(id);
		if (nsa == null) {
			return BaseResponse.errorMsg("为找到指定信息");
		}
		planTrainingMapper.deleteById(id);
		return BaseResponse.okData("删除成功");
	}

	@Override
	public void exportList(String filename,HttpServletResponse response) {
		Map<String, Object> params = new HashMap<>();
//		params.put("objective", objective);
		List<Map<String, Object>> list = planTrainingMapper.exportList(params);

		if (!CollectionUtils.isEmpty(list)) {
			Map<String, Object> map = list.get(0);
			String[] headers = new String[9];
			headers[0] = "序号";
			headers[1] = "培训对象";
			headers[2] = "培训目的";
			headers[3] = "培训内容";
			headers[4] = "培训时间";
			headers[5] = "培训方式";
			headers[6] = "培训人";
			headers[7] = "考核人";
			headers[8] = "实施情况";

			List<Object[]> datas = new ArrayList<>(list.size());
			for (Map<String, Object> m : list) {
				Object[] objects = new Object[headers.length];
				for (int j = 0; j < headers.length; j++) {
					String obj = m.get(headers[j]) == null ? "" : m.get(headers[j]).toString();
					if (j == 0 && obj != null) {
						obj = obj.split("\\.")[0];
					}

					objects[j] = obj;
					if (StringUtils.isEmpty(obj)){
						objects[j]= "———";
					}
				}

				datas.add(objects);
			}
			ExcelUtil.excelExport(
					filename == null || filename.trim().length() <= 0 ? "培训计划" : filename, headers,
					datas, response);
		}
	}
	/**
	 * 培训计划上传附件
	 *
	 * @param query
	 * @return
	 */
//	@Transactional
//	@Override
//	public BaseResponse<PlanTraining> uploadPlanTrainListPT(PlanTrainingFJ query) {
//		LoginUser loginUser = userService.getLoginUser();
//		if (loginUser == null) {
//			return BaseResponse.errorMsg("请登录账号");
//		}
//		if (query == null || query.getId() == null) {
//			return BaseResponse.errorMsg("参数错误");
//		}
//		PlanTraining planTraining = planTrainingMapper.selectById(query.getId());
//		if (planTraining == null) {
//			return BaseResponse.errorMsg("数据错误");
//		}
//		planTraining.setEnclosureUrl(query.getEnclosureUrl())
//				.setExtName(query.getExtName())
//				.setAlias(query.getAlias());
//		planTrainingMapper.updateById(planTraining);
//		return BaseResponse.okData(planTraining);
//	}

}
