package com.yeejoin.precontrol.common.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.precontrol.common.enums.MessageAttributeEnum;
import com.yeejoin.precontrol.common.enums.MessageSubTypeEnum;
import com.yeejoin.precontrol.common.enums.MessageTypeEnum;
import com.yeejoin.precontrol.common.publish.MessageEventPublish;
import netscape.javascript.JSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.KnowledgeShareDto;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskTechDocument;
import com.yeejoin.precontrol.common.entity.UserRegistration;
import com.yeejoin.precontrol.common.enums.StatusEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.WeChatMsgTemplateTypeEum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.feign.KnowledgeBaseFeign;
import com.yeejoin.precontrol.common.mapper.TaskMapper;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.ITaskKnowledgeShareService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.service.ITaskTechDocumentService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;

import javax.ws.rs.HEAD;

@Service
public class TaskKnowledgeShareServiceImpl extends ServiceImpl<TaskMapper, Task> implements ITaskKnowledgeShareService {

	@Autowired
	IPersonService iPersonService;

	@Autowired
	IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	ITaskPersonService iTaskPersonService;

	@Autowired
	ITaskTechDocumentService iTaskTechDocumentService;

	@Autowired
	ITaskService iTaskService;

	@Autowired
	IProjectService iProjectService;

	@Value("${knowledge.category.id}")
	Long categoryId;

	@Autowired
	KnowledgeBaseFeign knowledgeBaseFeign;

	@Autowired
	MessageEventPublish messageEventPublish;
	
	@Autowired
	IStatisticsService statisticsService;
	
	@Autowired
	SmallProService smallProService;
	
	@Value("${smallProgram.name}")
	String smallPrograName;

	@Override
	@Transactional
	public KnowledgeShareDto saveOne(KnowledgeShareDto knowledgeShareDto) {
		Task task = new Task();
		BeanUtils.copyProperties(knowledgeShareDto, task);
		task.setType(TaskTypeEnum.KNOWLEDGE_SHARE.getValue());
		task.setStatus(StatusEnum.UNFINISHED.getValue());
		task.setTaskNo(DateUtils.getTimeStamp());
		Project project = iProjectService.getById(knowledgeShareDto.getProjectId());
		task.setProjectName(project.getName());
		this.save(task);
		knowledgeShareDto.setTaskId(task.getId());
		List<Long> studyPersonIds = knowledgeShareDto.getStudyPersonIds();
		List<TaskPerson> taskPersonList = new ArrayList<TaskPerson>();
		for (int i = 0; i < studyPersonIds.size(); i++) {
			Long studyPersonId = studyPersonIds.get(i);
			TaskPerson taskPerson = new TaskPerson();
			taskPerson.setPersonId(studyPersonId);
			Person person = iPersonService.getById(studyPersonId);
			if (person != null) {
				taskPerson.setPersonName(person.getName());
			} else {
				if (!StringUtil.isEmpty(knowledgeShareDto.getStudyPersonNames())) {
					taskPerson.setPersonName(knowledgeShareDto.getStudyPersonNames().get(i));
				}
			}
			taskPerson.setTaskId(task.getId());
			PersonAscription personAscription = iPersonAscriptionService.getOne(
					new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, studyPersonId));
			if (personAscription != null) {
				taskPerson.setCompanyId(personAscription.getCompanyId());
			} else {
				taskPerson.setCompanyId(knowledgeShareDto.getCompanyId());
			}
			taskPerson.setType(TaskPersonTypeEnum.STUDY.getValue());
			taskPerson.setReadStatus(StatusEnum.UNFINISHED.getValue());
			taskPersonList.add(taskPerson);
		}
		// 添加发起人
		TaskPerson createPerson = new TaskPerson();
		createPerson.setPersonId(knowledgeShareDto.getCreatePersonId());
		Person person = iPersonService.getById(knowledgeShareDto.getCreatePersonId());
		createPerson.setTaskId(task.getId());
		createPerson.setType(TaskPersonTypeEnum.CREATEPERSON.getValue());
		createPerson.setReadStatus(StatusEnum.SUCCESS.getValue());
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		createPerson.setPersonName(person != null ? person.getName() : null);
		createPerson.setCompanyId(personAscription != null ? personAscription.getCompanyId() : null);
		taskPersonList.add(createPerson);
		iTaskPersonService.saveBatch(taskPersonList);

		TaskTechDocument taskTechDocument = new TaskTechDocument();
		taskTechDocument.setTaskId(task.getId());
		taskTechDocument.setTechDocumentId(knowledgeShareDto.getDocumentId());
		taskTechDocument.setTechDocumentName(knowledgeShareDto.getDocumentName());
		taskTechDocument.setIndustryType(knowledgeShareDto.getIndustryType());
		iTaskTechDocumentService.save(taskTechDocument);
		
		//更新推送
		String orgCode= person.getOrgCode();
		statisticsService.initWs(orgCode, Constant.WS_COMPOSITESUM);
		
		
		// 微信服务通知
		List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>()
				.in(Person::getId, studyPersonIds).isNotNull(Person::getOpenId));
		List<String> openIds = persons.stream().map(Person::getOpenId).collect(Collectors.toList());
		List<String> messages = new ArrayList<>();
		messages.add(smallPrograName);
		messages.add("知识推送");  
		messages.add("您有待办理的知识推送管控任务流程");
		messages.add(DateUtils.getDateNowString());
		smallProService.sendWeChatUpcomingMessage(openIds, WeChatMsgTemplateTypeEum.TODO.getValue(),
				messages);
		return knowledgeShareDto;
	}

	@Override
	public boolean updateOneById(KnowledgeShareDto knowledgeShareDto) {
		return true;
	}

	@Override
	public KnowledgeShareDto queryById(Long personId, Long taskId) {
		KnowledgeShareDto knowledgeShareDto = new KnowledgeShareDto();
		Task task = iTaskService.getById(taskId);
		BeanUtils.copyProperties(task, knowledgeShareDto);
		List<TaskPerson> personList = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getType, TaskPersonTypeEnum.STUDY.getValue()));
		knowledgeShareDto.setStudyPersonList(personList);
		TaskTechDocument taskTechDocument = iTaskTechDocumentService
				.getOne(new LambdaQueryWrapper<TaskTechDocument>().eq(TaskTechDocument::getTaskId, taskId));
		knowledgeShareDto.setDocumentId(taskTechDocument.getTechDocumentId());
		knowledgeShareDto.setDocumentName(taskTechDocument.getTechDocumentName());

		// 查询该知识推送是否已读
		TaskPerson taskPerson = iTaskPersonService.getOne(new LambdaQueryWrapper<TaskPerson>()
				.eq(TaskPerson::getTaskId, taskId).eq(TaskPerson::getPersonId, personId));
		knowledgeShareDto.setReadStatus(taskPerson != null ? taskPerson.getReadStatus() : null);
		return knowledgeShareDto;
	}

	@Override
	public void knowledgeNotice(KnowledgeShareDto knowledgeShareDto) {
		List<Long> personIds = knowledgeShareDto.getStudyPersonIds();
		// 获取taskPersonId
		QueryWrapper<TaskPerson> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(TaskPerson::getTaskId, knowledgeShareDto.getTaskId()).in(TaskPerson::getPersonId,
				personIds);
		List<TaskPerson> taskPersonList = iTaskPersonService.list(queryWrapper);
		if (!CollectionUtils.isEmpty(personIds)) {
			JSONArray array = new JSONArray();
			personIds.forEach(id -> {
				TaskPerson taskPerson = taskPersonList.stream().filter(t -> t.getPersonId().equals(id)).findFirst()
						.orElse(null);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put(MessageAttributeEnum.PERSON_ID.getName(), id);
				jsonObject.put(MessageAttributeEnum.CONTENT.getName(), MessageSubTypeEnum.KNOWLEDGE_PUSH_MSG.getTip());
				jsonObject.put(MessageAttributeEnum.MSG_TYPE.getName(), MessageTypeEnum.KNOWLEDGE_PUSH.getType());
				jsonObject.put(MessageAttributeEnum.MSG_SUB_TYPE.getName(),
						MessageSubTypeEnum.KNOWLEDGE_PUSH_MSG.getType());
				jsonObject.put(MessageAttributeEnum.TASK_ID.getName(), knowledgeShareDto.getTaskId());
				if (taskPerson != null) {
					jsonObject.put(MessageAttributeEnum.PARAM.getName(), taskPerson.getId());
				}

				array.add(jsonObject);
			});

			JSONObject data = new JSONObject();
			data.put("param", array);

			messageEventPublish.publish(data);
		}
	}

	@Override
	public Long saveOneByPostName(UserRegistration registration, String postNameKey,String postName, Long createPersonId) {
		// Person person = iPersonService.getById(personId);
		FeignClientResult<AgencyUserModel> userModel = Privilege.agencyUserClient
				.queryByUserId(String.valueOf(registration.getUserId()));
		Long personId = null;
		if (userModel.getResult() != null) {
			personId = userModel.getResult().getSequenceNbr();
		} else {
			throw new BaseException("账号不存在,userId: " + registration.getUserId());
		}
		KnowledgeShareDto knowledgeShareDto = new KnowledgeShareDto();
		knowledgeShareDto.setCreatePersonId(createPersonId);
		knowledgeShareDto.setProjectId(registration.getProjectId());
		knowledgeShareDto.setCompanyId(registration.getCompanyId());
		Long[] studyIds = { personId };
		knowledgeShareDto.setStudyPersonIds(Arrays.asList(studyIds));
		String[] studyName = { registration.getRealName() };
		knowledgeShareDto.setStudyPersonNames(Arrays.asList(studyName));
		ResponseModel<Object> response = knowledgeBaseFeign.getDocListByCategoryId(false, categoryId, 0, 99,
				postNameKey);
		System.out.println("------------categoryId: "+categoryId+" ,-----------postNameKey: "+postNameKey);
		System.out.println("------------"+JSONObject.toJSONString(response));
		if (response.getResult() != null) {
			Object o = response.getResult();
			Map<String, Object> page =null;
			try {	
				page = (Map<String, Object>) o;
			}
			catch (Exception e) {
				e.printStackTrace();
				throw new BaseException("获取对应工种知识错误");
			}
		
			if (page == null) {
				throw new BaseException("获取对应工种知识错误");
			}
			Object obj = page.get("records");
			if (obj == null) {
				throw new BaseException("获取对应工种知识错误");
			}
			List<Map<String, Object>> list = (List<Map<String, Object>>) obj;
			if (StringUtil.isNotEmpty(list)) {
				Map<String, Object> map = list.get(0);
				if (map != null) {
					Object objNbr = map.get("sequenceNbr");
					knowledgeShareDto.setDocumentId(objNbr != null ? Long.valueOf(objNbr.toString()) : null);
					knowledgeShareDto.setDocumentName(String.valueOf(map.get("docTitle")));
					knowledgeShareDto.setName(String.valueOf(map.get("docTitle")));
					if (map.get("code") != null && !map.get("code").equals("null")) {
						knowledgeShareDto.setCode(String.valueOf(map.get("code")));
					}
					if (map.get("number") != null && !map.get("number").equals("null")) {
						knowledgeShareDto.setNumber(String.valueOf(map.get("number")));
					}
				} else {
					throw new BaseException("没有对应工种知识,请在知识库加入"+postName+"知识");
				}

			} else {
				throw new BaseException("没有对应工种知识,请在知识库加入"+postName+"知识");
			}
		} else {
			throw new BaseException("没有对应工种知识,请在知识库加入"+postName+"知识");
		}
		knowledgeShareDto.setIndustryType(postNameKey);
		knowledgeShareDto = this.saveOne(knowledgeShareDto);
		
		knowledgeNotice(knowledgeShareDto);
		return knowledgeShareDto.getTaskId();
	}

}
