package cn.com.countrygarden.bi.main.controller.experience;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManage;
import cn.com.countrygarden.bi.main.service.experience.TygWxService;
import cn.com.countrygarden.bi.main.service.experience.WcxCustomerService;
import cn.com.countrygarden.bi.main.util.MD5;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/api/wxLogin")
@Slf4j
@Controller
public class TygWxLogin {

    @Autowired
    private WxMpServiceImpl wxService;
    @Autowired
    private WcxCustomerService wcxCustomerService;
    @Autowired
    private TygWxService tygWxService;
    /**
     * 用户页面授权跳转
     * @return
     */
    @GetMapping("/userAuth")
    public String redirect(String url){
        return "redirect:"+wxService.getOAuth2Service().buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
    }
    private static List<String> userOpenIds=new ArrayList<>();

    /**
     * 授权页面回调（可通过code获取用户信息）
     * @param code
     * @param modelMap
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/authLogin")
    @ResponseBody
    public Result authPage(@RequestParam("code") String code,
                           ModelMap modelMap) throws WxErrorException {
        Result result=new Result();
        try {
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxService.getOAuth2Service().getAccessToken(code);
            WxMpUser wxMpUser = wxService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
            String openId = wxMpUser.getOpenId();
            WxMpUser userInfo = wxService.getUserService().userInfo(openId);
            //wxMpUser.get
            //查询当前用户是否有绑定体验官(员工、客户)
            WcxEmployeesManage wcxEmployeesManage = wcxCustomerService.selectByByOpenId(openId,userInfo);
            if (wcxEmployeesManage == null) {
                //通知前端重定向登录
                result.setResultCode(10002);
                result.setResultMsg("用户");
                result.setData(JSONObject.toJSONString(userInfo));
                return result;
            }
            //genAccessToken(phone,openId,"");
            result.setResultCode(200);
            result.setData(wcxEmployeesManage);
        }catch(Exception e){
            result.setResultCode(500);
            result.setData(e.getMessage());
        }
        return result;
    }

    /**
     * 获取用户明细信息
     * @return
     * @throws WxErrorException
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public String getUser() throws WxErrorException {
        WxMpUser userInfo = wxService.getUserService().userInfo("o6PSZ6bq8hMi_WbWoR-xJBtf8XC0");
        log.info("用户数据：{}", JSONUtil.toJsonStr(userInfo));
        return JSONUtil.toJsonStr(userInfo);
    }
    /**
     * 验证手机号码是否存在系统内
     * @return
     */
    @GetMapping("/check/phone")
    @ResponseBody
    public Result checkPhone(String phone){
        return tygWxService.checkPhone(phone);
    }
    /**
     * 发送短信验证码
     * @return
     */
    @GetMapping("/send/message")
    @ResponseBody
    public Result sendMessage(HttpServletRequest req, String phone, HttpServletResponse res){
        return tygWxService.sendMessage(phone,req,res);
    }

    /**
     * 使用短信校验码进行登录
     * @return
     */
    @PostMapping("/code")
    @ResponseBody
    public Result code(HttpServletRequest req,
                      String phone,
                       String code,
                       String userInfo,String sessionId){
        return tygWxService.code(phone,req,code,userInfo,sessionId);
    }
    /**
     * 生成体验官证书编号
     * */
    @PostMapping("/createCode")
    @ResponseBody
    public Result createCode(@RequestParam(value="phone",required = false) String phone){
        return tygWxService.createCode(phone);
    }
}
