package com.palmnest.webapp.controller.wechat;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.AppConstants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.BeanUtils;
import com.palmnest.application.core.util.HttpKit;
import com.palmnest.application.core.util.LocationUtil;
import com.palmnest.model.ScopeEntity;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.estateserve.SmsAuthCode;
import com.palmnest.model.estateserve.WxUser;
import com.palmnest.model.virtfood.VirtFood;
import com.palmnest.model.virtfood.VirtFoodConfig;
import com.palmnest.model.virtfood.VirtFoodOutConfig;
import com.palmnest.model.virtfood.VirtFoodPerson;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.ScWxuserManager;
import com.palmnest.service.estateserve.SmsAuthCodeManager;
import com.palmnest.service.virtfood.VirtFoodConfigManager;
import com.palmnest.service.virtfood.VirtFoodManager;
import com.palmnest.service.virtfood.VirtFoodOutConfigManager;
import com.palmnest.service.virtfood.VirtFoodPersonManager;
import com.palmnest.webapp.controller.utils.AESUtil;
import com.palmnest.webapp.controller.utils.SignTools;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "/wechat/virtfood")
public class WxVirtFoodController {


	@Autowired
	private VirtFoodManager          virtFoodManager;
	@Autowired
	private VirtFoodConfigManager    virtFoodConfigManager;
	@Autowired
	private VirtFoodPersonManager    virtFoodPersonManager;
	@Autowired
	private UserManager              userManager;
	@Autowired
	private OrganizationManager      organizationManager;
	@Autowired
	private ScWxuserManager          scWxuserManager;
	@Autowired
	private SmsAuthCodeManager       smsAuthCodeManager;
	@Autowired
	private AppUserManager           appUserManager;
	@Autowired
	private VirtFoodOutConfigManager virtFoodOutConfigManager;

	// 小程序登陸
	private static String Code2SessionUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";

	/**
	 * 项目列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getOpenId")
	@ResponseBody
	public AppResultDto getOpenId(HttpServletRequest request) {
		String appid   = request.getParameter("appid");
		String secret  = "dfc4fb00d014ed693f20c9a693717a44";//request.getParameter("secret");
		String js_code = request.getParameter("js_code");
//		 String longitude = request.getParameter("longitude");
//	    String latitude = request.getParameter("latitude");
		try {

			String     get_url = Code2SessionUrl.replace("APPID", appid).replace("SECRET", secret).replace("JSCODE", js_code);
			String     jsonStr = HttpKit.get(get_url);
			JSONObject json    = JSONObject.parseObject(jsonStr);
//			if(json.getString("errcode").equals("0")){
//				String openid = json.getString("openid");
//				return AppResultUtil.createSuccesDto(openid);
//	        }else {
//	        	return AppResultUtil.createSuccesDto("400", json.getString("errcode"));
//	        }
			log.error(jsonStr);
			if (json.get("openid") != null) {
				String         openid = json.getString("openid");
				VirtFoodPerson person = virtFoodPersonManager.getByopenid(openid);
				if (person == null) {
					return AppResultUtil.createSuccesDto(json);
				} else {
					if (person.getVirt_id() == null) {
						AppUser user = appUserManager.getAppUsersByPhoneAndOrg(person.getMobile(), Integer.parseInt(person.getOrg_id().toString()));
						if (user != null && user.getVirtualArchId() != null) {
							virtFoodPersonManager.remove(person.getId());
							return AppResultUtil.createSuccesDto(json);
						}
					}


					VirtFoodOutConfig oc     = virtFoodOutConfigManager.get(1L);
					JSONObject        object = new JSONObject();
					VirtFood          vf     = virtFoodManager.get(person.getFood_id());
					VirtFoodConfig    vfc    = virtFoodConfigManager.getByFoodId(vf.getId());
					object.put("spid", vf.getCard_no());
					object.put("mobile", person.getMobile());
					object.put("sign", "");
					object.put("virtFoodConfig", vfc);
					object.put("openid", openid);
					String mobileAES = AESUtil.encode2base64(person.getMobile(), oc.getParam1(), true);
					String str = "charset=UTF-8&mobile=" + mobileAES + "&sign_type=SHA-256&spid=" + vf.getCard_no() +

							"&version=1.0&key=" + oc.getEncodekey();

					String     sign     = SignTools.getFoodSign(str);
					JSONObject signjson = new JSONObject();
					signjson.put("spid", vf.getCard_no());
					signjson.put("mobile", mobileAES);
					signjson.put("version", "1.0");
					signjson.put("charset", "UTF-8");
					signjson.put("sign_type", "SHA-256");
					signjson.put("sign", sign);
					object.put("signObject", signjson);

					//小程序商城跳转参数
					String scstr = "charset=UTF-8&sign_type=SHA-256&spid=" + vf.getCard_no() +

							"&version=1.0&key=" + oc.getEncodekey();

					String     scsign     = SignTools.getFoodSign(scstr);
					JSONObject scsignjson = new JSONObject();
					scsignjson.put("spid", vf.getCard_no());

					scsignjson.put("version", "1.0");
					scsignjson.put("charset", "UTF-8");
					scsignjson.put("sign_type", "SHA-256");
					scsignjson.put("sign", scsign);
					object.put("signObjectShop", scsignjson);
					object.put("islogin", 1);
					return AppResultUtil.createSuccesDto(object);
				}
			}
			json.put("islogin", 0);
			return AppResultUtil.createSuccesDto(json);

		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createSuccesDto("400", e.getMessage());
		}
	}

	/**
	 * 用户登录接口
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/login")
	@ResponseBody
	public AppResultDto login(HttpServletRequest request) {

		String orgId  = request.getParameter("orgId");
		String openId = request.getParameter("openId");
		String mobile = request.getParameter("mobile");
//        String longitude = request.getParameter("longitude");
//        String latitude = request.getParameter("latitude");
		String mobileCode = request.getParameter("mobileCode");
		log.info("登录 :WxVirtFoodController login orgId--:{},openId--:{},mobile--:{},mobileCode--:{}",
				orgId, openId, mobile, mobileCode);

		if (StringUtils.isBlank(mobileCode)) {
			return AppResultUtil.createErrorDto(AppConstants.REST_PASSWORD_ERROR, "请输入验证码");
		}
		if (!"9999".equalsIgnoreCase(mobileCode)) {//9999不验证
			SmsAuthCode smsAuthCode = smsAuthCodeManager.getSmsAuthCode(mobile, mobileCode, "1", 15);
			if (smsAuthCode == null) {
				return AppResultUtil.createErrorDto(AppConstants.AUTH_CODE_ERROR, "验证码不正确");
			}
		}
		VirtFoodOutConfig oc = virtFoodOutConfigManager.get(1L);
		try {
			JSONObject          object = new JSONObject();
			WxUser              wxUser = scWxuserManager.getScWxuserByOpenId(openId);
			AppUser             user   = appUserManager.getAppUsersByPhoneAndOrg(mobile, Integer.parseInt(orgId));
			Map<String, Object> params = new HashMap<>();
			if (user != null && user.getVirtualArchId() != null) {
				//檢查企業是否開通飯卡
				params.put("virtId", user.getVirtualArchId());
				List<VirtFood> vfs = virtFoodManager.findAll(params);
				if (vfs != null && vfs.size() > 0) {
					VirtFoodConfig vfc = virtFoodConfigManager.getByFoodId(vfs.get(0).getId());
					object.put("spid", vfs.get(0).getCard_no());
					object.put("mobile", mobile);
					object.put("sign", "");
					object.put("virtFoodConfig", vfc);

					VirtFoodPerson person = virtFoodPersonManager.getByopenid(openId);
					if (person == null) {
						VirtFoodPerson addperson = new VirtFoodPerson();
						addperson.setCreated_at(new Date());
						addperson.setFood_id(vfs.get(0).getId());
						addperson.setOpenid(openId);
						addperson.setMobile(mobile);
						addperson.setOrg_id(Long.parseLong(orgId));
						addperson.setVirt_id(Long.parseLong(user.getVirtualArchId().toString()));
						virtFoodPersonManager.saveModel(addperson);
					}

					//小程序跳转参数
					String spid      = vfs.get(0).getCard_no();
					String timestamp = Long.toString(System.currentTimeMillis() / 1000);
					String nonce_str = UUID.randomUUID().toString();
					String mobileAES = AESUtil.encode2base64(mobile, oc.getParam1(), true);
					String str = "charset=UTF-8&mobile=" + mobileAES + "&sign_type=SHA-256&spid=" + spid +

							"&version=1.0&key=" + oc.getEncodekey();
					String     sign     = SignTools.getFoodSign(str);
					JSONObject signjson = new JSONObject();
					signjson.put("spid", spid);
					signjson.put("mobile", mobileAES);
					signjson.put("version", "1.0");
					signjson.put("charset", "UTF-8");
					signjson.put("sign_type", "SHA-256");
					signjson.put("sign", sign);
					object.put("signObject", signjson);

					//小程序商城跳转参数
					String scstr = "charset=UTF-8&sign_type=SHA-256&spid=" + spid +
							"&version=1.0&key=" + oc.getEncodekey();

					String     scsign     = SignTools.getFoodSign(scstr);
					JSONObject scsignjson = new JSONObject();
					scsignjson.put("spid", spid);
//	   		        scsignjson.put("longitude", longitude);
//	   		        scsignjson.put("latitude", latitude);
					scsignjson.put("version", "1.0");
					scsignjson.put("charset", "UTF-8");
					scsignjson.put("sign_type", "SHA-256");
					scsignjson.put("sign", scsign);
					object.put("signObjectShop", scsignjson);

					return AppResultUtil.createSuccesDto(object);
				}

			}
			params.clear();

			//附屬查
			String foodid = virtFoodManager.getFoodIdByOrgId(orgId);
			String spid   = "";
			if (StringUtils.isEmpty(foodid)) {
				params.put("orgId", orgId);
				List<VirtFood> vfs = virtFoodManager.findAll(params);
				spid = vfs.get(0).getCard_no();
				foodid = vfs.get(0).getId().toString();
			} else {
				VirtFood virtfood = virtFoodManager.get(Long.parseLong(foodid));
				spid = virtfood.getCard_no();
			}

			VirtFoodConfig vfc = virtFoodConfigManager.getByFoodId(Long.parseLong(foodid));

			object.put("spid", spid);
			object.put("mobile", mobile);
			object.put("sign", "");
			object.put("virtFoodConfig", vfc);
			VirtFoodPerson person = virtFoodPersonManager.getByopenid(openId);
			if (person == null) {
				VirtFoodPerson addperson = new VirtFoodPerson();
				addperson.setCreated_at(new Date());
				addperson.setFood_id(Long.parseLong(foodid));
				addperson.setOpenid(openId);
				addperson.setMobile(mobile);
				addperson.setOrg_id(Long.parseLong(orgId));
				virtFoodPersonManager.saveModel(addperson);
			}
			//小程序跳转参数

//			String timestamp=Long.toString(System.currentTimeMillis() / 1000);
//			String nonce_str = UUID.randomUUID().toString();
			String mobileAES = AESUtil.encode2base64(mobile, oc.getParam1(), true);
			String str = "charset=UTF-8&mobile=" + mobileAES + "&sign_type=SHA-256&spid=" + spid +

					"&version=1.0&key=" + oc.getEncodekey();

			String     sign     = SignTools.getFoodSign(str);
			JSONObject signjson = new JSONObject();
			signjson.put("spid", spid);
			signjson.put("mobile", mobileAES);
			signjson.put("version", "1.0");
			signjson.put("charset", "UTF-8");
			signjson.put("sign_type", "SHA-256");
			signjson.put("sign", sign);
			object.put("signObject", signjson);

			//小程序商城跳转参数
			String scstr = "charset=UTF-8&sign_type=SHA-256&spid=" + spid +

					"&version=1.0&key=" + oc.getEncodekey();

			String     scsign     = SignTools.getFoodSign(scstr);
			JSONObject scsignjson = new JSONObject();
			scsignjson.put("spid", spid);
			scsignjson.put("version", "1.0");
			scsignjson.put("charset", "UTF-8");
			scsignjson.put("sign_type", "SHA-256");
			scsignjson.put("sign", scsign);
			object.put("signObjectShop", scsignjson);

			return AppResultUtil.createSuccesDto(object);
		} catch (Exception e) {
			// TODO: handle exception
			return AppResultUtil.createErrorDto("400", e.getMessage());
		}
		//查找tb_user,关联tb_wxUser


	}

	/**
	 * 项目列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getprojects")
	@ResponseBody
	public AppResultDto getList(HttpServletRequest request) {

		try {

			Page page = virtFoodManager.getProjects(9999, 1, request.getParameter("projectName"));
			//WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			String[] pys = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "M", "L", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"};

			List<Map<String, Object>> resLs = new ArrayList<>();
			for (String i : pys) {
				Map<String, Object> resMap = new HashMap<>();
				resMap.put("key", i);
				List<Object> datals = new ArrayList<>();

				for (Object obj : page.getItems()) {

					String imap = BeanUtils.getProperty(obj, "name");//JSONObject.parseObject(obj.toString(),new TypeReference<Map<String, String>>(){});
					String ipy  = getPinYinHeadChar(imap);
					if (ipy.substring(0, 1).toUpperCase().equals(i)) {
						datals.add(obj);
					}
				}

				resMap.put("data", datals);
				resLs.add(resMap);
			}

			return AppResultUtil.createSuccesDto(resLs);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createSuccesDto("400", "查询记录失败");
		}
	}

	/**
	 * 项目列表-附近
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getnearbyprojects")
	@ResponseBody
	public AppResultDto getnearbyprojects(HttpServletRequest request) {

		try {
			int pageSize = 20;
			int pageNo   = 1;
			if (StringUtils.isNotEmpty(request.getParameter("pageSize"))) {
				pageSize = Integer.parseInt(request.getParameter("pageSize"));
			}
			double longitude = Double.parseDouble(request.getParameter("longitude"));
			double latitude  = Double.parseDouble(request.getParameter("latitude"));
			double scope     = 1;
			if (StringUtils.isNotEmpty(request.getParameter("scope"))) {
				scope = Double.parseDouble(request.getParameter("scope"));
			}
			ScopeEntity scopeEntity = LocationUtil.findNeighPosition(longitude, latitude, scope);
			Page        page        = virtFoodManager.getProjectsOfLate(scopeEntity, pageSize, pageNo);


			return AppResultUtil.createSuccesDto(page);
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createSuccesDto("400", e.getMessage());
		}
	}

	/**
	 * 得到中文首字母
	 *
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {

		String convert = "";
		for (int j = 0; j < str.length(); j++) {
			char     word        = str.charAt(j);
			String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
			if (pinyinArray != null) {
				convert += pinyinArray[0].charAt(0);
			} else {
				convert += word;
			}
		}
		return convert;
	}

	/**
	 * 项目列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/recappstatus")
	@ResponseBody
	public AppResultDto recappstatus(HttpServletRequest request) {

		try {

			String     instr       = SignTools.readInputStream(request.getInputStream(), Charset.forName("utf-8"));
			JSONObject jasonObject = JSONObject.parseObject(instr);
			Map        map         = (Map) jasonObject;
			String     spid        = map.get("spid").toString();
			String     status      = map.get("status").toString();
			String     errmsg      = map.get("errmsg") == null ? "" : map.get("errmsg").toString();
			String     version     = map.get("version") == null ? "" : map.get("version").toString();
			String     timestamp   = map.get("timestamp") == null ? "" : map.get("timestamp").toString();
			String     charset     = map.get("charset") == null ? "" : map.get("charset").toString();
			String     nonce_str   = map.get("nonce_str") == null ? "" : map.get("nonce_str").toString();
			String     sign        = map.get("sign") == null ? "" : map.get("sign").toString();

			//WebPageResultDto dto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", page.getItems());
			VirtFood food = virtFoodManager.getBySpid(spid);
			if (status.equals("1")) {
				food.setApproval_status(Byte.valueOf("2"));
				food.setUpdated_at(new Date());
			} else {
				food.setApproval_status(Byte.valueOf("3"));
				food.setApproval_remarks(errmsg);
			}
			virtFoodManager.updateModel(food);
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			e.printStackTrace();
			return AppResultUtil.createSuccesDto("400", e.getMessage());
		}
	}

	/**
	 * 报修详情
	 * @param request
	 * @return
	 */
//	@RequestMapping(value="/getDetail")
//	@ResponseBody
//	public AppResultDto getDetail(HttpServletRequest request) {
//		String id = request.getParameter("id");
//		if(!StringUtil.isNotEmpty(id)){
//			return AppResultUtil.createErrorDto("400", "ID为空！");
//		}
//		try {
//			RepairService repairService=repairServiceManager.get(Long.parseLong(id));
//			RepairServiceDto dto = new RepairServiceDto();
//			BeanUtils.copyProperties(dto,repairService);
//			Long orgId = repairService.getOrg_id();
//			TbOrganization org = organizationManager.getOrganizationById(Integer.parseInt(orgId.toString()));
//			if(org != null) {
//				dto.setOrgTel(org.getTelephone());
//			}
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//			dto.setCreated_at_str(sdf.format(dto.getCreated_at()));
//			dto.setUpdated_at_str(sdf.format(dto.getUpdated_at()));
//			if(dto.getUpdated_by() != null && dto.getUpdated_by()!=0) {
//				User user = userManager.get(repairService.getUpdated_by());
//				if(user != null) {
//					dto.setUpdated_by_name(user.getFullName());
//				}
//			}
//			WebPageResultDto webPageResultDto = new WebPageResultDto(AppConstants.SUCCESS_CODE, "成功", dto);
//			return AppResultUtil.createSuccesDto(webPageResultDto);
//		} catch (Exception e) {
//			e.printStackTrace();
//			return AppResultUtil.createErrorDto("400", "获取详情失败！");
//		}
//
//	}


}
