/*
 *    Copyright (c) 2018-2025, hnqz All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: hnqz
 */
package com.qunzhixinxi.hnqz.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qunzhixinxi.hnqz.admin.api.vo.UserVO;
import com.qunzhixinxi.hnqz.admin.entity.*;
import com.qunzhixinxi.hnqz.admin.mapper.WmUserSignMapper;
import com.qunzhixinxi.hnqz.admin.service.*;
import com.qunzhixinxi.hnqz.common.core.util.R;
import com.qunzhixinxi.hnqz.common.security.util.SecurityUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户签到表
 *
 * @author pigx code generator
 * @date 2020-07-14 20:10:02
 */
@Slf4j
@Service
@AllArgsConstructor
public class WmUserSignServiceImpl extends ServiceImpl<WmUserSignMapper, WmUserSign> implements WmUserSignService {

	private final WmTaskContentService wmTaskContentService;
	private final SysUserService sysUserService;
	private final SysDeptService sysDeptService;
	private final WmTaskTypeService wmTaskTypeService;
	private final WmScorePackageService wmScorePackageService;
	private final WmScorePackageStatusService wmScorePackageStatusService;
	private final WmTaskService wmTaskService;
	private final SysRoleService sysRoleService;
	private final WmTaskRuleService wmTaskRuleService;
	private final SysPublicParamService sysPublicParamService;

	@Override
	public R saveWmUserSign(WmUserSign wmUserSign) {
		if (StringUtils.isEmpty(wmUserSign.getPackageId())) {
			return R.failed("关联积分包异常");
		}
		if (StringUtils.isEmpty(wmUserSign.getSignEntId())) {
			return R.failed("打卡地址异常，请退出后重试");
		}

		if (StringUtils.isEmpty(wmUserSign.getSignEntName())) {
			return R.failed("打卡地址异常，请退出后重试");
		}
		if (StringUtils.isEmpty(wmUserSign.getSignEntType())) {
			wmUserSign.setSignEntType("1");
		}
		WmScorePackage tWmScorePackage = wmScorePackageService.getById(wmUserSign.getPackageId());
		if (StringUtils.isEmpty(tWmScorePackage.getId())) {
			log.warn("获取不到积分包：{}", wmUserSign.getPackageId());
			return R.failed("获取不到积分包");
		}
		if(StringUtils.isEmpty(tWmScorePackage.getRuleId())){
			log.warn("积分包未配置积分规则：{}", wmUserSign.getPackageId());
			return R.failed("积分包未配置积分规则");
		}
		//TODO 测试通过后删除
		UserVO sysU = sysUserService.selectUserVoById(SecurityUtils.getUser().getId());
		if (!sysU.getUserId().toString().equals(wmUserSign.getSignUserid())) {
			log.warn("客户拜访任务，登录人不符：{}", wmUserSign.getSignUserid());
			return R.failed("客户拜访任务，登录人不符");
		}

		if("1".equals(tWmScorePackage.getPackageType1())){
			Boolean fullFlag = wmTaskService.checkUserTaskSubScore(sysU.getUserId() + "");
			if(fullFlag){
				String value = sysPublicParamService.getSysPublicParamKeyToValue("USER_TASK_SUB_SCORE");
				String info = StringUtils.isEmpty(value)?"每日最多提交3万积分":"每日最多提交"+Integer.parseInt(value)+"积分";
				log.warn("系统当前限制积分上限：【{}】，提示：【{}】", value, info);
				return R.failed(1,info);
			}
		}

		WmUserSign singQuery = new WmUserSign();
		singQuery.setSignUserid(wmUserSign.getSignUserid());
		singQuery.setSignEntName(wmUserSign.getSignEntName());
//		singQuery.setSignDate(LocalDateTime.now().minus(4, ChronoUnit.HOURS));
		int total = this.count(Wrappers.query(singQuery).lambda()
		.gt(WmUserSign::getSignDate,LocalDateTime.now().minus(4, ChronoUnit.HOURS)));

		if(total != 0){
			log.warn("打卡间隔过短：{} {}", wmUserSign.getSignUserid(),wmUserSign.getSignEntName());
			return R.failed("客户拜访任务，登录人不符");
		}

		/**
		 * 积分包领取明细
		 */
		WmScorePackageStatus query = new WmScorePackageStatus();
		query.setUserId(sysU.getUserId() + "");
		query.setStatus("2");
		query.setTaskAddFlag("1");
		query.setPackageId(tWmScorePackage.getId());
		List<WmScorePackageStatus> statusList = wmScorePackageStatusService.list(Wrappers.lambdaQuery(query));
		if (CollectionUtils.isEmpty(statusList)) {
			log.warn("获取积分包异常，任务保存失败9001：{}", tWmScorePackage.getId());
			return R.failed("获取积分包异常，任务保存失败");
		}
		if (statusList.size() != 1) {
			log.warn("获取积分包异常，任务保存失败9002：{}", tWmScorePackage.getId());
			return R.failed("获取积分包异常，任务保存失败");
		}
		WmScorePackageStatus scorePackageStatus = statusList.get(0);

		boolean saveSign = this.save(wmUserSign);

		if (saveSign) {

			WmTask wmTask = new WmTask();
			wmTask.setTaskFrom("1");
			wmTask.setTaskUserId(sysU.getUserId() + "");    //任务提交人
			if ("1".equals(wmUserSign.getSignEntType())) {
				wmTask.setTaskTypeId("5");                           //任务类型
			} else {
				wmTask.setTaskTypeId("6");                           //任务类型
			}
			wmTask.setSubmitStatus("0");
			LocalDateTime localDateTime = LocalDateTime.now();
			wmTask.setUpdateTime(localDateTime);
			wmTask.setLookintoDate(localDateTime);       //调研时间
			wmTask.setCreateTime(localDateTime);
			wmTask.setTaskStatus("2"); //直接提交
			wmTask.setDrugEntId(sysU.getDrugEntId());

			wmTask.setDeptId(sysU.getDeptId() + "");

			WmTaskType wmTaskType = new WmTaskType();

			if ("1".equals(wmUserSign.getSignEntType())) {
				WmTaskType wmTaskType1 = wmTaskTypeService.getById(5);
				wmTaskType.setTaskTypeName(wmTaskType1.getTaskTypeName());
			} else {
				WmTaskType wmTaskType1 = wmTaskTypeService.getById(6);
				wmTaskType.setTaskTypeName(wmTaskType1.getTaskTypeName());
			}

			wmTaskType.setRuleId(tWmScorePackage.getRuleId());
			int score = wmTaskTypeService.getWmTaskTypeByEnt(wmTaskType);
			if (score < 0) {
				return R.failed("获取任务积分失败");
			}
			wmTask.setScore(score);

			wmTask.setScorePackageId(tWmScorePackage.getId());
			wmTask.setTaskRuleId(tWmScorePackage.getTaskRuleId());

			WmTaskContent wmTaskContent = new WmTaskContent();
			wmTaskContent.setTemp1(wmUserSign.getLatitude());
			wmTaskContent.setTemp2(wmUserSign.getLongitude());
			wmTaskContent.setTemp3(wmUserSign.getId() + "");
			wmTaskContentService.save(wmTaskContent);

			wmTask.setTaskContentId(wmTaskContent.getId() + "");
			//保存任务
			wmTaskService.save(wmTask);

			/**
			 * 判断任务完成度
			 */
			WmScorePackage updatePke = wmScorePackageService.getById(tWmScorePackage.getId());
			if (null != updatePke) {
				/**
				 * 查询出 审核通过和审核中的任务
				 */
				WmTask taskQuery = new WmTask();
				taskQuery.setScorePackageId(tWmScorePackage.getId());
				QueryWrapper<WmTask> taskQueryWrapper = Wrappers.query(taskQuery);
				taskQueryWrapper.lambda()
						.ne(WmTask::getTaskStatus, "4")
						.eq(WmTask::getRealFlag, "0");
//						.ne(WmTask::getRealFlag, "1");
				List<WmTask> wmTaskList = wmTaskService.list(taskQueryWrapper);
				/**
				 * 判断定量还是定额 1- 定额   2-定量
				 * 20210120 目前 1-定额  1包1人  2-定量   1包多人
				 */

				if ("1".equals(updatePke.getPackageType1())) {

					int totalCount = 0;
					for (WmTask wmtask : wmTaskList) {
						totalCount += wmtask.getScore();
					}

					if (totalCount >= updatePke.getScore()) {
						updatePke.setTaskAddFlag("0");
						scorePackageStatus.setTaskAddFlag("0");
						wmScorePackageStatusService.updateById(scorePackageStatus);
					}
					wmTask.setType("1");

				} else if ("2".equals(updatePke.getPackageType1())) {

					List<WmTask> userTaskList = wmTaskList.stream().filter(item ->
							item.getTaskUserId().equals(sysU.getUserId() + "")).collect(Collectors.toList());

					if (userTaskList.size() >= scorePackageStatus.getTaskNum()) {
						scorePackageStatus.setTaskAddFlag("0");
						wmScorePackageStatusService.updateById(scorePackageStatus);

						/**
						 * 改变大包状态
						 */
						WmScorePackageStatus queryAll = new WmScorePackageStatus();
						queryAll.setPackageId(tWmScorePackage.getId());
						queryAll.setStatus("2");
						queryAll.setTaskAddFlag("0");
						List<WmScorePackageStatus> statusAll = wmScorePackageStatusService.
								list(Wrappers.query(queryAll));
						if(new BigDecimal(updatePke.getUserNum())
								.compareTo(new BigDecimal(statusAll.size())) <= 0){
							updatePke.setTaskAddFlag("0");
						}
					}

//					if (wmTaskList.size() >= updatePke.getTaskNum()) {
//						updatePke.setTaskAddFlag("0");
//					}
					wmTask.setType("2");
				}
				updatePke.setIsConduct("1");
				wmScorePackageService.updateById(updatePke);
				return R.ok(wmTask);
			}
		}

		return R.failed("签到保存失败");
	}


}
