package com.mortals.xhx.base.login.web;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.service.IAuthTokenService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.utils.WechatTools;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("wechat")
public class WechatLoginController extends BaseJsonBodyController implements InitializingBean {

    @Autowired
    private UserService userService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private IAuthTokenService authTokenService;

    @Value("${wechat.appId:wxdb349cd58dd0600b}")
    private String AppId;
    @Value("${wechat.secret:21eb0f1bdb87c79b9fb6f38db2b1a357}")
    private String AppSecret;

    @RequestMapping("login")
    @UnAuth
    public String getWxInfo(@RequestBody JSONObject obj) {

        JSONObject ret = new JSONObject();

        JSONObject wxJson = JSONObject.parseObject(WechatTools.getOpenid(obj.getString("code"), AppId, AppSecret));
        log.info("微信的返回值{}", wxJson);
        if(StringUtils.isEmpty(wxJson.getString("openid"))){
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, wxJson.getString("errmsg"));
            ret.put("errcode", wxJson.getString("errcode"));
            return ret.toJSONString();
        }else {
            String ip = super.getRequestIP(request);
            UserEntity userEntity = userService.wechatLogin(wxJson.getString("openid"),ip);
            JSONObject data = new JSONObject();
            data.put("userId", userEntity.getId());
            if(userEntity.getStaffId()==null){
                data.put("staffId", -1);
            }else {
                data.put("staffId", userEntity.getStaffId());
            }
            userEntity.setLoginTime(System.currentTimeMillis());
            userEntity.setToken(IdUtil.fastSimpleUUID());
            userEntity.setExpireTime(DateUtils.addCurrDate(7).getTime());
            String token = authTokenService.createToken(userEntity);
            data.put("token", token);
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            return ret.toJSONString();
        }
    }

    @RequestMapping("getPhoneNumber")
    public String getPhoneNumber(@RequestBody JSONObject obj){
        JSONObject ret = new JSONObject();
        String tokenUrl =String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",AppId,AppSecret);
        JSONObject token = JSONObject.parseObject(HttpUtil.createGet(tokenUrl).execute().body());
        log.info("微信的返回值{}", token);
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+token.getString("access_token");
        JSONObject param =new JSONObject();
        param.put("code",obj.getString("code"));
        String body = HttpUtil.createPost(url)
                .contentType("application/json").body(param.toJSONString()).execute().body();
        log.info("微信的返回值{}", body);
        JSONObject jsonObject = JSONObject.parseObject(body);
        if(jsonObject.getIntValue("errcode")==0){
            JSONObject data = new JSONObject();

            String phoneNumber = jsonObject.getJSONObject("phone_info").getString("phoneNumber");
            data.put("phoneNumber", phoneNumber);
            //UserEntity userEntity = this.getContext().getUser().getId();
            if(this.getContext()!=null && this.getContext().getUser()!=null){
                UserEntity userEntity = userService.get(this.getContext().getUser().getId());
                if(userEntity!=null){
                    StaffEntity staffEntity = staffService.selectOne(new StaffQuery().phoneNumber(phoneNumber));
                    if(staffEntity!=null){
                        userEntity.setStaffId(staffEntity.getId());
                        data.put("staffId", staffEntity.getId());
                        data.put("staff",staffEntity);
                    }else {
                        data.put("staffId", -1);
                    }
                    userEntity.setPhone(phoneNumber);
                    userEntity.setUpdateTime(new Date());
                    userEntity.setUpdateUserId(userEntity.getId());
                    userService.update(userEntity);
                }
            }
            ret.put(KEY_RESULT_DATA, data);
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            ret.put(KEY_RESULT_MSG, "用户登录系统成功!");
            return ret.toJSONString();
        }else {
            ret.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            ret.put(KEY_RESULT_MSG, jsonObject.getString("errmsg"));
            ret.put("errcode", jsonObject.getIntValue("errcode"));
            return ret.toJSONString();
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }
}
