package com.platform.yijia.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.platform.yijia.param.request.AppUserInfoRequest;
import com.platform.yijia.pojo.AppUserInfo;
import com.platform.yijia.pojo.CustomerManage;
import com.platform.yijia.service.AppUserInfoService;
import com.platform.yijia.service.PayOrderService;
import com.platform.yijia.service.StationService;
import com.platform.yijia.utils.CodeMsg;
import com.platform.yijia.utils.ResultData;
import com.platform.yijia.utils.weixinapp.AesDecryptUtil;
import com.platform.yijia.utils.weixinapp.WeiXinUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api")
public class AppUserInfoController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(AppUserInfoController.class);
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationService stationService;
//    String appId = "wxe1135cd390b38a54";        //微信小程序appID
//    String appSecret = "0532c7d9ae876c4ad636df0b1e3b9ddb";      //微信小程序密钥

    /*
     * 微信小程序根据code获取用户openId和sessionKey
     * @param code
     * , @RequestParam("stationId") String stationId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSessionKeyAndOpenID")
    public Map<String, Object> getSessionKeyAndOpenID(@RequestParam("code") String code, @RequestParam("stationId") String stationId){
        String appId = "";        //微信小程序appID
        String appSecret = "";      //微信小程序密钥
        if(stationId !=null && stationId !=""){
            Map<String, String> map = stationService.getStationAppIdAndAppSecret(stationId);
            appId = map.get("appId");        //微信小程序appID
            appSecret = map.get("appSecret");      //微信小程序密钥
        }
        //获取session_key 和 openid
        return WeiXinUserUtil.getUserSessionKeyAndOpenID(appId, appSecret, code);
    }

    /*
     * 解密 encryptedData
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/decryptEncryptedData", method = RequestMethod.POST, consumes = "application/json")
    public String decryptEncryptedData(@RequestBody JSONObject jsonObject){
        logger.info("解密获取手机号前台传入参数：" +jsonObject.toString());
        return AesDecryptUtil.decryptEncryptedData(jsonObject.get("encryptedData").toString(), jsonObject.get("sessionKey").toString(), jsonObject.get("iv").toString(), "UTF-8").toString();
    }

    /*
     * 添加用户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAppUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public String addAppUserInfo(@RequestBody AppUserInfoRequest request){
        Gson gson =new Gson();
        ResultData resultData=null;
        try{
            AppUserInfo appUserInfo =new AppUserInfo();
            String openId = "";     //此参数用于查询该用户是否已注册过
            if(request.getUserType()!=null){
                //1-微信公众号
                if(request.getUserType().equals("1") &&StringUtils.isNotBlank(request.getBlogOpenid())){
                    appUserInfo.setUserType(request.getUserType());
                    appUserInfo.setBlogToken(request.getBlogToken());
                    openId = request.getBlogOpenid();
                    appUserInfo.setBlogOpenid(openId);
                 //2-微信小程序
                }else if(request.getUserType().equals("2") &&StringUtils.isNotBlank(request.getMinaOpenid())){
                    appUserInfo.setUserType(request.getUserType());
                    appUserInfo.setMinaToken(request.getMinaToken());
                    openId = request.getMinaOpenid();
                    appUserInfo.setMinaOpenid(openId);
                }
            }
            if(StringUtils.isNotBlank(request.getBlogNickName())){
                appUserInfo.setBlogNickName(request.getBlogNickName());
            }
            if(StringUtils.isNotBlank(request.getMobilePhone())){
                appUserInfo.setMobilePhone(request.getMobilePhone());
            }
            if(StringUtils.isNotBlank(request.getBlogProfilePhoto())){
                appUserInfo.setBlogProfilePhoto(request.getBlogProfilePhoto());
            }

            appUserInfo.setRegisteDate(new Date());
            appUserInfo.setUpdateDate(new Date());

            if(StringUtils.isNotBlank(request.getSexFlag())){
                appUserInfo.setSexFlag(request.getSexFlag());
            }

            Map<String, Object> params = new HashMap<>();
            params.put("openId", openId);                   //注册用户openId
            params.put("userType", request.getUserType());  //用户类型
            //判断该用户是否已存在
            int count = appUserInfoService.isExistAppUser(params);
            if(count > 0){
                resultData = ResultData.error(CodeMsg.USER_EXSIST);
            }else {
                appUserInfoService.AddAppUserInfo(appUserInfo);
                resultData = ResultData.success(CodeMsg.SUCCESS);
            }
        }catch (Exception e){
            resultData = ResultData.error(CodeMsg.INSERT_FAIL);
            e.printStackTrace();
        }
        return gson.toJson(resultData);
    }

}
