package com.yeejoin.amos.patrol.business.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.patrol.business.dao.mapper.LatentDangerMapper;
import com.yeejoin.amos.patrol.common.enums.YesOrNoEnum;
import com.yeejoin.amos.patrol.common.remote.RemoteWorkFlowService;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yeejoin.amos.patrol.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.RiskJudgmentTaskMapper;
import com.yeejoin.amos.patrol.business.dao.repository.AppVersionDao;
import com.yeejoin.amos.patrol.business.dao.repository.IMsgSubscribeDao;
import com.yeejoin.amos.patrol.business.param.UserMsgInitParam;
import com.yeejoin.amos.patrol.business.service.intfc.IAppService;
import com.yeejoin.amos.patrol.business.service.intfc.IMsgSubscribeService;
import com.yeejoin.amos.patrol.common.enums.MsgSubscribeTypeEnum;
import com.yeejoin.amos.patrol.dao.entity.AppVersion;
import com.yeejoin.amos.patrol.dao.entity.MsgSubscribe;

import java.util.ArrayList;
import java.util.List;

@Service("iAppService")
public class AppServiceImpl implements IAppService {

	@Autowired
	private IMsgSubscribeDao msgSubscribeDao;
    @Autowired
    private AppVersionDao appVersionDao;
    @Autowired
	private RemoteWorkFlowService remoteWorkFlowService;
    @Autowired	private IMsgSubscribeService msgSubscribeService;

    @Autowired
	private LatentDangerMapper latentDangerMapper;

    @Autowired
    private PlanTaskMapper planTaskMapper;

    @Autowired
    private RiskJudgmentTaskMapper riskJudgmentTaskMapper;


	@Override
	public AppVersion queryAppLastVersion() {
		// TODO Auto-generated method stub
		  return appVersionDao.findLastVersion();
	}


	/**
	 * 新增用户时初始化消息订阅(p_msg_subscribe)表
	 *
	 * @param userDTO
	 */
	 @Override
	public List<MsgSubscribe> saveUserMsgInit(UserMsgInitParam userInitParam) {
		Long count = msgSubscribeDao.countByUserId(userInitParam.getUserId());
		if (count > 0) {	//	已存在用户订阅，直接返回
			return msgSubscribeService.queryMsgSubscribes(userInitParam.getUserId());
		}
		List<MsgSubscribe> msgConfigs = new ArrayList<MsgSubscribe>();
		for (MsgSubscribeTypeEnum type : MsgSubscribeTypeEnum.values()) {
			MsgSubscribe msgSub = new MsgSubscribe();
			msgSub.setOrgCode(userInitParam.getOrgCode());
			msgSub.setUserId(userInitParam.getUserId());
			if (type.equals(MsgSubscribeTypeEnum.PLANBEGIN)
					|| type.equals(MsgSubscribeTypeEnum.PLANWARN)
					|| type.equals(MsgSubscribeTypeEnum.PLANEND)) {
				msgSub.setAttribute1("False");
				msgSub.setAttribute2(10 + "");
			} else if (type.equals(MsgSubscribeTypeEnum.CHECKTYPE)
					|| type.equals(MsgSubscribeTypeEnum.CHECKEMAIL)) {
				msgSub.setAttribute1("error");
			}
			/**else if (type.equals(MsgSubscribeTypeEnum.ROUTE) && !userInitParam.getInit()) {
				// TODO 查询该用户下的路线
				String roleTypeName = userInitParam.getRoleTypeName();
				String orgCode = userInitParam.getOrgCode();

				Specification<Route> spec = new Specification<Route>() {// 构建查询条件

					@Override
					public Predicate toPredicate(Root<Route> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
						List<Predicate> predicate = new ArrayList<>();
						if (!ObjectUtils.isEmpty(roleTypeName)) {
							if (XJConstant.ROLE_NAME_ADMIN.equals(roleTypeName)
									|| XJConstant.ROLE_NAME_SUPERADMIN.equals(roleTypeName)) {
								predicate.add(cb.like(root.get("orgCode").as(String.class), orgCode + "%"));
							} else if (XJConstant.ROLE_NAME_DEPTADMIN.equals(roleTypeName)) {
								String orgCode_ = orgCode;
								if (orgCode.indexOf("-") != -1) {
									orgCode_ = orgCode.substring(0, orgCode.indexOf("-"));
								}
								predicate.add(cb.like(root.get("orgCode").as(String.class), orgCode_ + "%"));
							} else {
								predicate.add(cb.equal(root.get("orgCode").as(String.class), orgCode));
							}
						}
						Predicate[] pre = new Predicate[predicate.size()];
						return query.where(predicate.toArray(pre)).getRestriction();
					}

				};
				List<Route> routeList = iRouteDao.findAll(spec);
				List<Long> routeIdList = new ArrayList<>();
				for (Route route : routeList) {
					routeIdList.add(route.getId());
				}
				String routeIds = StringUtils.join(routeIdList.toArray(), ",");
				msgSub.setAttribute1(routeIds);
			}*/
			msgSub.setMsgType(type.getName());
			msgSubscribeDao.saveAndFlush(msgSub);
			msgConfigs.add(msgSub);

		}
		return msgConfigs;
	}


	@Override
	public List<String> getHaveToDoList(String userId) {
		int taskCount = planTaskMapper.getCurrentPlanTaskCount(userId);
        List<String> havetoDoList = Lists.newArrayList();
        if (taskCount > 0) {
            havetoDoList.add("planPatrol");
        }
		JSONObject respBody = remoteWorkFlowService.pageTask(userId,Integer.parseInt(YesOrNoEnum.YES.getCode()));
		JSONArray taskJsonList = respBody.getJSONArray("data");
		List<JSONObject> taskList = JSONObject.parseArray(taskJsonList.toJSONString(), JSONObject.class);
		List<String> bussinessKeys = new ArrayList<>();
		for (JSONObject json : taskList) {
			bussinessKeys.add(json.getString("businessKey"));
		}
		Integer dangerCount = latentDangerMapper.countByStatus(bussinessKeys);
		if(dangerCount > 0){
			havetoDoList.add("waitHandle");
		}
        return havetoDoList;
	}

}