package com.palmnest.webapp.controller.lingling;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.core.util.LingLingUtil;
import com.palmnest.application.dto.input.LingLingVisitorMachineInputDto;
import com.palmnest.application.dto.input.lingling.QrcodeInsInputDTO;
import com.palmnest.application.dto.output.lingling.*;
import com.palmnest.model.AppUserOrgnizationRelation;
import com.palmnest.model.User;
import com.palmnest.service.UserManager;
import com.palmnest.service.lingling.manager.LingLingManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Author hxt
 * @Description 令令访客机控制器
 * @Date 2019/3/11 11:02
 **/
@Slf4j
@Controller
@RequestMapping(value = "/lingling/PcPost")
public class LingLingVisitorMachineController {


	@Autowired
	private LingLingManager lingLingManager;
	@Autowired
	private UserManager     userManager;

	/**
	 * 访客机接口参数解析
	 *
	 * @param request
	 * @return
	 */
	private JSONObject handleParam(HttpServletRequest request) {

		try {
			String message = request.getParameter("MESSAGE");

			JSONObject jsonObject   = JSONObject.parseObject(message);
			JSONObject requestParam = jsonObject.getJSONObject("requestParam");

//            log.info("LingLingVisitorMachineController handleParam 令令回调参数处理========>params:{}",message);

			return requestParam;
		} catch (Exception e) {
			log.error("LingLingVisitorMachineController handleParam 令令回调参数处理异常=====>" + e.getMessage());
		}
		return null;
	}

	/**
	 * 客户机用户登录
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/loginWin")
	@ResponseBody
	public LingLingResultDto loginWin(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);

		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("loginWin", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String account  = requestParam.getString("account");
		String password = requestParam.getString("password");

		if (StringUtils.isAnyBlank(account, password)) {
			return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_10001, "loginWin", LingLingUtil.PARAM_EMPTY_ERROR);
		}

		log.info("LingLingVisitorMachineController loginWin =====>account:{},password:{}", account, password);

		try {
			User user = userManager.getUser(account, password);
			if (Objects.isNull(user)) {
				return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_20002, "loginWin", LingLingUtil.ACCOUNT_PASSWORD_ERROR);
			}

			// 获取该账户对应项目的访客机设置信息
			List<AppUserOrgnizationRelation> list       = userManager.getUserOrgByUserId(user.getId());
			LoginWinVO                       loginWinVO = lingLingManager.getVisitorMachineByOrgId(list.get(0).getOrgId());
			// 如果项目还未配置访客机初始信息,则不可以登录;
			if (Objects.isNull(loginWinVO)) {
				log.info("loginWin error=======>{}", LingLingUtil.UN_INITIALIZE_MACHINE);
				return LingLingResultUtil.createErrorDto("loginWin", LingLingUtil.UN_INITIALIZE_MACHINE);
			}
			loginWinVO.setUserId(user.getId());

			List resultList = new ArrayList();
			resultList.add(loginWinVO);
			return LingLingResultUtil.createSuccesDto("loginWin", resultList);
		} catch (Exception e) {
			log.error("loginWin error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("loginWin", LingLingUtil.SERVER_ERROR);
		}

	}


	/**
	 * 查询访客信息(使用访客手机号或身份证号去查询)
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/selectVisitor")
	@ResponseBody
	public LingLingResultDto selectVisitor(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("selectVisitor", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String telephone  = requestParam.getString("telephone");
		String idenNumber = requestParam.getString("idenNumber");

		if (StringUtils.isAllBlank(telephone, idenNumber)) {
			return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_10001, "selectVisitor", LingLingUtil.PARAM_EMPTY_ERROR);
		}
		log.info("LingLingVisitorMachineController selectVisitor =====>telephone:{},idenNumber:{}", telephone, idenNumber);

		try {
			SelectVisitorVO visitorVO  = lingLingManager.getVisitorInfo(telephone, idenNumber);
			List            resultList = new ArrayList();
			resultList.add(visitorVO);
			return LingLingResultUtil.createSuccesDto("selectVisitor", resultList);
		} catch (Exception e) {
			log.error("selectVisitor error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("selectVisitor", LingLingUtil.SERVER_ERROR);
		}
	}


	/**
	 * 提交生成二维码
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/qrcodeIns")
	@ResponseBody
	public LingLingResultDto qrcodeIns(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("qrcodeIns", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		try {
			QrcodeInsInputDTO inputDTO = JSONObject.parseObject(requestParam.toJSONString(), QrcodeInsInputDTO.class);
			QrcodeInsVo       vo       = lingLingManager.createVisitorMachineQrCode(inputDTO,1);

			if (Objects.isNull(vo)) {
				return LingLingResultUtil.createErrorDto("qrcodeIns", "生成二维码异常");
			}
			return LingLingResultUtil.createSuccesDto("qrcodeIns", vo);
		} catch (Exception e) {
			log.error("qrcodeIns error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("qrcodeIns", LingLingUtil.SERVER_ERROR);
		}
	}

	/**
	 * 上传照片(身份证头像/抓拍头像)
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/uploadPhoto")
	@ResponseBody
	public LingLingResultDto uploadPhoto(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("uploadPhoto", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String photo     = requestParam.getString("photoData");// 照片base64字符串
		String photoName = requestParam.getString("photoName");// 照片名称
		String photoType = requestParam.getString("photoType");// 照片类型

		try {
			lingLingManager.uploadPhoto(photo, photoName, photoType);
			return LingLingResultUtil.createSuccesDto("uploadPhoto", LingLingUtil.UPLOADPHOTO_SUCCESS);
		} catch (Exception e) {
			log.error("uploadPhoto error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("uploadPhoto", LingLingUtil.SERVER_ERROR);
		}
	}

	/**
	 * 获取拜访目的
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getVisitorAuto")
	@ResponseBody
	public LingLingResultDto getVisitorAuto(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("getVisitorAuto", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String                           userId = requestParam.getString("userId");
		List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(Long.valueOf(userId));
		if (CollectionUtils.isEmpty(list)) {
			return LingLingResultUtil.createErrorDto("getVisitorAuto", null);
		}

		Integer                        orgId          = list.get(0).getOrgId();
		LingLingVisitorMachineInputDto visitorMachine = lingLingManager.getVisitorMachine(orgId);

		if (Objects.isNull(visitorMachine)) {
			return LingLingResultUtil.createErrorDto("getVisitorAuto", null);
		}

		List     resultList  = new ArrayList();
		String visitReasonStr = visitorMachine.getVisitReasonStr();
		if(StringUtils.isNotEmpty(visitReasonStr)){

			String[] visitReason = visitReasonStr.split(";");
			for (String str : visitReason) {
				Map<String, String> map = new HashMap<>();
				map.put("name", str);
				resultList.add(map);
			}
		}


		return LingLingResultUtil.createSuccesDto("getVisitorAuto", resultList);
	}


	/**
	 * 获取公司列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getCompany")
	@ResponseBody
	public LingLingResultDto getCompany(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("getCompany", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String                           userId = requestParam.getString("userId");
		List<AppUserOrgnizationRelation> list   = userManager.getUserOrgByUserId(Long.valueOf(userId));
		if (CollectionUtils.isEmpty(list)) {
			return LingLingResultUtil.createErrorDto("getCompany", null);
		}

		Integer            orgId       = list.get(0).getOrgId();
		List<GetCompanyVO> companyList = lingLingManager.getCompanyList(orgId);
		return LingLingResultUtil.createSuccesDto("getCompany", companyList);
	}


	/**
	 * 发送短信
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/sendQRCode")
	@ResponseBody
	public LingLingResultDto sendQRCode(HttpServletRequest request) {

		JSONObject requestParam = handleParam(request);
		if (Objects.isNull(requestParam)) {
			return LingLingResultUtil.createErrorDto("sendQRCode", LingLingUtil.PARAM_ANALYSIS_ERROR);
		}

		String telephone = requestParam.getString("telephone");// 访客手机号
		String codeId    = requestParam.getString("codeId");// 二维码ID
		String qrcodeKey = requestParam.getString("qrcodeKey");// 二维码数据

		if (StringUtils.isAnyBlank(telephone, codeId)) {
			return LingLingResultUtil.createErrorDto(LingLingUtil.STATUS_CODE_10001, "sendQRCode", LingLingUtil.PARAM_EMPTY_ERROR);
		}

		try {
			lingLingManager.sendQRCode(telephone, codeId,1,null);
			return LingLingResultUtil.createSuccesDto("sendQRCode", "sendQRCode success");
		} catch (Exception e) {
			log.error("sendQRCode error=======>", e.getMessage());
			return LingLingResultUtil.createErrorDto("sendQRCode", LingLingUtil.SERVER_ERROR);
		}

	}
}
