package com.github.wxiaoqi.security.admin.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.admin.entity.AppUserAlipay;
import com.github.wxiaoqi.security.admin.entity.AppUserDetail;
import com.github.wxiaoqi.security.admin.entity.AppUserLogin;
import com.github.wxiaoqi.security.admin.mapper.AppUserAlipayMapper;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.auth.client.jwt.UserAuthUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.upyuns.platform.rs.universal.feign.ThirdFeign;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

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

/**
 * 支付宝账号表
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-03 16:36:44
 */
@Service
@Slf4j
public class AppUserAlipayBiz extends BaseBiz<AppUserAlipayMapper, AppUserAlipay>{

    @Autowired
    private UserAuthUtil userAuthUtil;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    AppUserLoginBiz appUserLoginBiz;

    @Autowired
    AppUserDetailBiz appUserDetailBiz;

    @Autowired
    ThirdFeign thirdFeign;

    //添加支付宝账号
    public  void  addAlipay(Integer userId,String txAlipay){
        AppUserAlipay appUserAlipay=new AppUserAlipay();
        appUserAlipay.setTxAlipay(txAlipay);
        appUserAlipay.setUserId(userId);
        appUserAlipay.setIsDel(0);
        AppUserAlipay appUserAlipay1=selectOne(appUserAlipay);
        if (appUserAlipay1==null){
            appUserAlipay.setIsDefault(1);
            insertSelective(appUserAlipay);
        }else {
            appUserAlipay1.setIsDefault(1);
            updateSelectiveById(appUserAlipay1);
        }
    }
   //获取支付宝列表
    public List<AppUserAlipay> getListByUserId(Integer userId){
        Example example=new Example(AppUserAlipay.class);
        example.createCriteria().andEqualTo("userId",userId).andEqualTo("isDel",0);
        example.setOrderByClause("is_default desc");
        return  selectByExample(example);
    }


    //获取支付宝用户信息
    public List<AppUserAlipay> getByUserId(HttpServletRequest request){
        Example example=new Example(AppUserAlipay.class);
        Integer userId = null;
        try {
            String username = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getId();
            if (StringUtils.isNotBlank(username)) {
                userId = Integer.parseInt(username);
                example.createCriteria().andEqualTo("userId", userId).andEqualTo("isDel",0);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        example.setOrderByClause("is_default desc");
        AppUserAlipay appUserAlipay = mapper.selectOneByExample(example);
        List<AppUserAlipay> appUserAlipays = new ArrayList<>();
        //支付宝
        if(appUserAlipay != null) {
            appUserAlipay.setType(1);
            appUserAlipays.add(appUserAlipay);
        }
        //微信
        AppUserLogin appUserLogin = appUserLoginBiz.getUserById(userId);
        if(appUserLogin != null && StringUtils.isNotBlank(appUserLogin.getWxOpenid())) {
            AppUserDetail appUserDetail = appUserDetailBiz.getUserByUserid(userId);
            AppUserAlipay wxAppUser = new AppUserAlipay();
            wxAppUser.setType(0);
            wxAppUser.setUserId(userId);
            wxAppUser.setNickname(StringUtils.isEmpty(appUserDetail.getWxNickname())?appUserDetail.getNickname():appUserDetail.getWxNickname());
            wxAppUser.setTxAlipay(appUserLogin.getWxOpenid());
            appUserAlipays.add(wxAppUser);
        }
        return appUserAlipays;
    }

    public void  save(AppUserAlipay appUserAlipay) {
        Example example=new Example(AppUserAlipay.class);
        example.createCriteria().andEqualTo("userId", appUserAlipay.getUserId()).andEqualTo("isDel",0);
        example.setOrderByClause("is_default desc");
        AppUserAlipay oldValue = mapper.selectOneByExample(example);
        if (oldValue != null) {
            BeanUtil.copyProperties(appUserAlipay, oldValue, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            updateByIdRe(oldValue);
        } else {
            insertSelectiveRe(appUserAlipay);
        }

    }

    /**
     * 支付宝授权获取用户信息
     * @param code
     * @return
     */
    public ObjectRestResponse getUserInfo(String code, HttpServletRequest request) {
        String username = null;
        AppUserAlipay appUserAlipay = new AppUserAlipay();
        try {
            username = userAuthUtil.getInfoFromToken(userAuthConfig.getToken(request)).getId();
            if (StringUtils.isBlank(username)) {
                return ObjectRestResponse.createFailedResult(ResultCode.RSTOKEN_EXPIRED_CODE, ResultCode.getMsg(ResultCode.RSTOKEN_EXPIRED_CODE));
            } else {
                appUserAlipay.setUserId(Integer.parseInt(username));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (StringUtils.isBlank(code)) {
            return ObjectRestResponse.paramIsEmpty();
        }
        String result = thirdFeign.getAliPayUserInfo(code).getData();
        if (StringUtils.isNotBlank(result)) {
            log.info("【支付宝】用户授权获取用户token， {}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (jsonObject.getJSONObject("error_response") == null && jsonObject.getJSONObject("alipay_user_info_share_response") != null) {
                JSONObject responseObject = jsonObject.getJSONObject("alipay_user_info_share_response");
                String account = responseObject.getString("user_id");
                if (account != null) {
                    appUserAlipay.setTxAlipay(account);
                    appUserAlipay.setCrtTime(new Date().getTime());
                    appUserAlipay.setIsDel(0);
                }
                String nickname = responseObject.getString("nick_name");
                if (nickname != null) {
                    appUserAlipay.setNickname(nickname);
                }
                log.info("用户支付宝信息： {}", appUserAlipay.toString());
                save(appUserAlipay);
                return ObjectRestResponse.succ(appUserAlipay.getNickname());
            } else {
                return ObjectRestResponse.createFailedResult(Integer.parseInt(jsonObject.getJSONObject("error_response").getString("code")), jsonObject.getJSONObject("error_response").getString("sub_msg"));
            }
        }
        return ObjectRestResponse.createDefaultFail();
    }

}