package org.springblade.business.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.utils.DateUtils;
import org.springblade.business.entity.UserOpinion;
import org.springblade.business.entity.UserOpinionFile;
import org.springblade.business.service.IUserOpinionCommentsService;
import org.springblade.business.service.IUserOpinionFileService;
import org.springblade.business.service.IUserOpinionFlowService;
import org.springblade.business.vo.BusinessUserOpinionVO;
import org.springblade.business.vo.UserOpinionFlowVO;
import org.springblade.business.vo.UserOpinionVO;
import org.springblade.business.mapper.UserOpinionMapper;
import org.springblade.business.service.IUserOpinionService;
import org.springblade.common.utils.CommonUtil;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.system.user.entity.User;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户意见表 服务实现类
 *
 * @author BladeX
 * @since 2022-05-25
 */
@Service
@AllArgsConstructor
public class UserOpinionServiceImpl extends BaseServiceImpl<UserOpinionMapper, UserOpinion> implements IUserOpinionService {

	private final IUserOpinionFileService userOpinionFileService;

	private final IUserOpinionCommentsService userOpinionCommentsService;

	private final IUserOpinionFlowService userOpinionFlowService;

	private final IUserClient userClient;

	@Override
	public IPage<BusinessUserOpinionVO> queryBusinessUserOpinionListAll(Query query) {
		return this.queryBusinessUserOpinionList(null, query);
	}

	@Override
	public IPage<BusinessUserOpinionVO> queryBusinessUserOpinionList(String currentUserId, Query query) {
		//获取分配给当前用户的工单
		List<BusinessUserOpinionVO> businessUserOpinionVOS = this.baseMapper.queryManageUserOpinionList(currentUserId);
		if(businessUserOpinionVOS != null && businessUserOpinionVOS.size() > 0){
			//先分组
			List<List<BusinessUserOpinionVO>> resultList = CommonUtil.getBatchSize(businessUserOpinionVOS, query.getSize());
			//获取具体页数下的数据
			List<BusinessUserOpinionVO> finalResult = resultList.get(query.getCurrent() - 1);

			//获取得到的工单所关联的所有附件
			List<Long> userOpinionKeys = finalResult.stream().map(BusinessUserOpinionVO::getUserOpinionId).distinct().collect(Collectors.toList());
			List<UserOpinionFile> allFile = this.userOpinionFileService.selectUserOpinionFileByUserOpinionKeys(userOpinionKeys);

			//设置附件信息
			finalResult.forEach(vo -> {
				List<String> imageUrls = new ArrayList<>();
				if(allFile != null && allFile.size() > 0){
					//处理附件信息
					Iterator<UserOpinionFile> iterator = allFile.iterator();
					while (iterator.hasNext()){
						UserOpinionFile nextFile = iterator.next();
						if(nextFile.getUserOpinionId().equals(vo.getUserOpinionId())){
							imageUrls.add(nextFile.getFileUrl());
							iterator.remove();
						}
					}
				}
				//设置附件信息
				vo.setImageUrl(imageUrls);

				//获取当前工单最新状态
				List<UserOpinionFlowVO> newFlow = this.userOpinionFlowService.queryCurrentUserOpinionFlowByUserOpinionId(String.valueOf(vo.getUserOpinionId()), vo.getNewNumber());
				if(newFlow != null && newFlow.size() > 0){
					//获取退后阶段
					UserOpinionFlowVO flow = newFlow.get(3);
					//设置最后的处理结果
					vo.setNewIsCurrent(flow.getCurrentBol());
					if(!vo.getNewIsCurrent()){
						//如果有权限则获取当前正在进行的操作环节
						for(UserOpinionFlowVO flowVo : newFlow){
							//依次找到正在执行的环节
							if(new Integer("2").equals(flowVo.getSort())){
								//设置当前用户操作权限（如果当前用户的流程次数和主表次数一致，认为可以操作）
								if(StringUtils.isNotEmpty(currentUserId)){
									vo.setOperation(vo.getNumber().equals(vo.getNewNumber()));
								} else {
									Long userId = AuthUtil.getUser().getUserId();
									vo.setOperation(StringUtils.isNotEmpty(String.valueOf(userId)) && flowVo.getManageUser().equals(userId));
								}
							}

							if(new Integer("1").equals(flowVo.getIsCurrent())){
								vo.setCurrentLinkId(flowVo.getId());
								vo.setCurrentLink(flowVo.getSort());
								break;
							}
						}
					}
				}

				//获取当前时间以判断距离结束时间还剩多少分钟
				try{
					if(vo.getCurrentLinkId() == null || vo.getCurrentLink() == null || vo.getCurrentLinkId() == -1 || vo.getCurrentLink() == -1){
						//说明已处理
						vo.setTimeRemaining("已处理");
					} else {
						//未处理
						Date manageDate = DateUtil.parseDate(vo.getManageTime()), nowDate = new Date();
						long between = manageDate.getTime() - nowDate.getTime();
						if(between > 0){
							long day = between / (24 * 60 * 60 * 1000);
							long hour = (between - (day * 24 * 60 * 60 * 1000)) / ( 60 * 60 * 1000);
							long minute = (between - (day * 24 * 60 * 60 * 1000) - hour * 60 * 60 * 1000) / ( 60 * 1000);

							vo.setTimeRemaining(day + "天" + hour + "小时" + minute + "分");
						} else {
							vo.setTimeRemaining("已超时");
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}

			});

			//设置分页信息及结果数据
			IPage<BusinessUserOpinionVO> page = Condition.getPage(query);
			page.setTotal(businessUserOpinionVOS.size());
			page.setRecords(finalResult);

			return page;
		}

		return null;
	}

	/**
	 * 获取当前用户提交的工单信息
	 * @param user 用户
	 * @return 结果集
	 */
	@Override
	public List<UserOpinionVO> queryCurrentUserOpinionList(BladeUser user) {
		List<UserOpinion> result = this.baseMapper.queryCurrentUserOpinionList(user.getUserId());

		if(result != null && result.size() != 0){
			List<UserOpinionVO> resultVo = JSONArray.parseArray(JSONObject.toJSONString(result), UserOpinionVO.class);
			resultVo.forEach(vo -> {
				//获取当前工单最新情况
				List<UserOpinionFlowVO> flowList = this.userOpinionFlowService.queryCurrentUserOpinionFlowByUserOpinionId(String.valueOf(vo.getId()), vo.getNumber());
				String newFlow = "";
				if(flowList != null && flowList.size() != 0){
					Integer isCurrent = flowList.get(flowList.size() - 1).getIsCurrent();
					newFlow = new Integer("2").equals(isCurrent) ? "已解决" : "正在处理";
				}
				String title = vo.getProblemType();
				if(vo.getCreateTime() != null){
					//如果有创建时间则拼接创建时间
					title = DateUtils.formatDate(vo.getCreateTime(), "yyyy-MM-dd") + " " + vo.getProblemType();
					if(StringUtils.isNotEmpty(newFlow)){
						title = title + "（" + newFlow + "）";
					}
				}
				vo.setTitle(title);
			});
			return resultVo;
		}

		return null;
	}

	@Override
	public IPage<UserOpinionVO> selectUserOpinionPage(IPage<UserOpinionVO> page, UserOpinionVO userOpinion, BladeUser users) {
		//当前页面数据
		long current = (page.getCurrent() - 1L) * page.getSize();
		//获取当前用户的提交记录
		List<UserOpinion> currentUserResult = this.baseMapper.queryCurrentUserOpinionList(users.getUserId());
		//获取非当前用户提交记录
		List<UserOpinion> notCurrentUserResult = this.baseMapper.selectUserOpinionPage(current, page.getSize(), userOpinion, String.valueOf(users.getUserId()));

		if(currentUserResult != null && notCurrentUserResult != null){
			//将当前用户提交的记录排在前面
			currentUserResult.addAll(notCurrentUserResult);
		}

		if(currentUserResult != null && currentUserResult.size() != 0){
			//有数据，查询相关信息
			List<UserOpinionVO> resultVo = JSONArray.parseArray(JSONObject.toJSONString(currentUserResult), UserOpinionVO.class);
			resultVo.forEach(vo -> {
				//查询相关附件
				List<UserOpinionFile> files = this.userOpinionFileService.selectUserOpinionFileByUserOpinionKey(vo.getId());
				if(files != null && files.size() != 0){
					vo.setReturnFiles(files.stream().map(UserOpinionFile::getFileUrl).distinct().collect(Collectors.toList()));
				}
				//统计评论数和点赞数
				Map<String,Integer> resultMap = this.userOpinionCommentsService.selectCommentsAndGoodCountByUserOpinionKey(vo.getId());
				vo.setCommentsNumber(resultMap.get("comments"));
				//获取处理结果
				Integer isSolve = this.userOpinionFlowService.selectIsSolveByUserOpinionKey(vo.getId());
				if(isSolve == 2){
					vo.setIsSolve(1);
				}
				try{
					if(StringUtils.isNotEmpty(String.valueOf(vo.getCreateUser())) && !"null".equals(String.valueOf(vo.getCreateUser()))){
						//获取用户信息
						User user = this.userClient.userInfoById(vo.getCreateUser()).getData();
						if(user != null){
							vo.setAvatar(user.getAvatar());
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			});
			return page.setRecords(resultVo);
		}
		return null;
	}

}
