package com.ff.weijinxiao.controller;


import cn.hutool.core.date.DateUtil;
import com.ff.weijinxiao.domain.AccountBook;
import com.ff.weijinxiao.domain.CUser;
import com.ff.weijinxiao.domain.UserInfo;
import com.ff.weijinxiao.jwt.JwtHelper;
import com.ff.weijinxiao.service.AccountBookService;
import com.ff.weijinxiao.service.CUserService;
import com.ff.weijinxiao.service.UserInfoService;
import com.ff.weijinxiao.util.JsonTool;
import com.ff.weijinxiao.util.RandomUtil;
import com.ff.weijinxiao.util.ResultTool;
import com.ff.weijinxiao.util.WXUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * 微信用户接口
 */
@RestController
@RequestMapping("api/cuser")
@Api(value = "微信用户controller", tags = {"微信用户接口"})
public class CUserController {

    private final static Logger logger = LoggerFactory.getLogger(CUserController.class);

    @Resource
    private CUserService cUserService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private AccountBookService accountBookService;

    public static String appid = "wx3d48d376faa3e9fb";
    public static String appsecret = "97193e51eb0b8474f5259bc5be874e30";

    @PostMapping("/update")
    @ApiOperation(value = "更新微信用户信息", notes = "更新微信用户信息")
    public Map<String, Object> updateCUser(@RequestBody CUser cUser, HttpServletRequest request) {
        try {
            cUserService.saveCUser(cUser);
            return ResultTool.genSuccessResult("修改成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "修改失败:" + e.getMessage());
        }
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建微信用户信息", notes = "创建微信用户信息")
    public Map<String, Object> saveCUser(@RequestBody CUser cUser, HttpServletRequest request) {
        try {
            cUserService.saveCUser(cUser);
            return ResultTool.genSuccessResult("创建成功");
        } catch (Exception e) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_2, "创建失败:" + e.getMessage());
        }
    }


    @PostMapping("/delete")
    @ApiOperation(value = "删除微信用户信息", notes = "删除微信用户信息")
    public Map<String, Object> deleteCUser(@ApiParam(required = true, value = "微信用户id") @RequestBody String jsonId) {
        Integer id = JsonTool.parseJsonIdStr(jsonId);
        if (id < 0) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "id参数错误");
        }
        CUser cUser = cUserService.findById(id);
        if (null == cUser) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "微信用户不存在");
        }
        cUserService.deleteById(id);
        return ResultTool.genSuccessResult("删除成功");
    }

    @GetMapping("/findbyid")
    @ApiOperation(value = "根据id查询微信用户信息", notes = "根据id查询微信用户信息")
    public Map<String, Object> findById(@ApiParam(required = true, value = "微信用户id") @RequestParam String id,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        try {
            CUser cUser = cUserService.findById(Integer.valueOf(id));
            if (null != cUser) {
                result.put("data", cUser);
                result.put("message", "查询成功");
                result.put("code", ResultTool.SuccessCode);
            } else {
                result.put("message", "查询失败，没有结果");
                result.put("code", ResultTool.ErrorCode_1);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("message", "查询失败" + e.getMessage());
            result.put("code", ResultTool.ErrorCode_2);
        }

        return result;
    }


    @GetMapping("/list")
    @ApiOperation(value = "查询微信用户列表", notes = "查询微信用户列表")
    public Map<String, Object> findList(@ApiParam(required = false, value = "微信用户名字") @RequestParam(required = false) String phone,
                                        HttpServletRequest request) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        List<CUser> list = cUserService.findList(param);
        if (null != list && list.size() > 0) {
            result.put("data", list);
            result.put("total", list.size());
            result.put("message", "查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    @GetMapping("/listpage")
    @ApiOperation(value = "查询微信用户分页列表", notes = "查询微信用户分页列表")
    public Map<String, Object> findListPage(@ApiParam(required = false, value = "微信用户名字") @RequestParam(required = false) String phone,
                                            @ApiParam(required = false, value = "页码 1开始") @RequestParam(required = false) Integer pageNo,
                                            @ApiParam(required = false, value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> param = new HashMap<>();
        if (null == pageNo) {
            pageNo = 1;
        } else if (pageNo < 1) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }
        param.put("GT_id", 0);
        param.put("EQ_isDelete", 0);
        if (null != phone && phone.length() > 0) {
            param.put("LIKE_phone", phone);
        }
        Page<CUser> list = cUserService.findPage(pageNo, pageSize, param);
        if (null != list && list.getTotalElements() > 0) {
            result.put("data", list);
            result.put("message", "分页查询成功");
            result.put("code", 10000);
        } else {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "没有查询到数据");
        }

        return result;
    }

    /**
     * code转openid
     *
     * @param code
     * @return
     */
    @GetMapping(value = "/wxapi/getopenid")
    @ApiOperation(value = "根据code换取openid", notes = "根据code换取openid")
    public Map<String, Object> getOpenid(@ApiParam(required = true, value = "code") @RequestParam String code) {
        logger.info("根据code换取openid :" + code);
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> data = getSessionKey(code);
        logger.info(data.toString());
        if (data != null && data.containsKey("openid")) {
            String openId = data.get("openid").toString();
            if (StringUtils.isBlank(openId)) {
                return ResultTool.genFailResult(ResultTool.ErrorCode_1, "code换openId失败");
            }
            CUser cUser = cUserService.findByOpenId(openId);
            if (null == cUser) {
                cUser = new CUser();
                cUser.setOpenId(openId);
                cUserService.saveCUser(cUser);
            }
            String token = JwtHelper.generateToken(openId);
            UserInfo userInfo = cUser.getUserInfo();
            if (null == userInfo) {
                //未绑定用户或者注册
                result.put("registed", false);
            } else {
                result.put("registed", true);
                Date validityTime = userInfo.getValidityTime();
                if (null == validityTime) {
                    validityTime = DateUtil.date();
                    validityTime = addDate(validityTime, 30);
                    userInfo.setValidityTime(validityTime);
                    userInfoService.saveUserInfo(userInfo);
                }
            }
            result.put("userinfo", userInfo);
            result.put("token", token);
            result.put("code", 10000);
            result.put("message", "code换取openId成功");
        } else {
            result.put("code", 10001);
            result.put("registed", false);
            result.put("message", "code换取openId失败");
        }
        return result;
    }

    public Date addDate(Date date, long day) {
        long time = date.getTime(); // 得到指定日期的毫秒数
        day = day * 24 * 60 * 60 * 1000; // 要加上的天数转换成毫秒数
        time += day; // 相加得到新的毫秒数
        return DateUtil.date(time); // 将毫秒数转换成日期
    }

    public static Map<String, Object> getSessionKey(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret
                + "&js_code=" + code + "&grant_type=authorization_code";
        return WXUtil.parseJSON2Map(WXUtil.sendGet(url, null));
    }

    @PostMapping("/wxapi/updatecuser")
    @ApiOperation(value = "更新cuser信息", notes = "更新cuser信息")
    public Map<String, Object> createNewCUser(@Valid @RequestBody CUser cUser,
                                              HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        logger.info("updatecuser");
        String token = request.getHeader("token");
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "token无效");
        }
        cUser.setOpenId(openId);
        cUserService.saveCUser(cUser);

        result.put("code", 10000);
        result.put("message", "更新C端用户成功");
        result.put("cuser", cUser);
        return result;
    }

    @PostMapping("/wxapi/binduserinfo")
    @ApiOperation(value = "绑定已有用户", notes = "绑定已有用户")
    public Map<String, Object> bindUserInfo(@ApiParam(required = true, value = "phone") @RequestParam(required = true) String phone,
                                            @ApiParam(required = false, value = "昵称") @RequestParam(required = false) String nickName,
                                            @ApiParam(required = false, value = "头像") @RequestParam(required = false) String avatarUrl,
                                            HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        logger.info("updatecuser");
        String token = request.getHeader("token");
        String openId = JwtHelper.parseToken(token);
        if (StringUtils.isBlank(openId)) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "token无效");
        }
        CUser cUser = cUserService.findByOpenId(openId);
        if (null == cUser) {
            return ResultTool.genFailResult(ResultTool.ErrorCode_1, "token无效");
        }
        if (StringUtils.isNotBlank(avatarUrl)) {
            cUser.setAvatarUrl(avatarUrl);
        }
        if (StringUtils.isNotBlank(nickName)) {
            cUser.setNickName(nickName);
        }
        UserInfo userInfo = userInfoService.findByPhone(phone);
        if (null == userInfo) {
            //return ResultTool.genFailResult(ResultTool.ErrorCode_2, "手机号码无效");
            userInfo = new UserInfo();
            userInfo.setUid(RandomUtil.genUId());
            userInfo.setPhone(phone);
            if (StringUtils.isNotBlank(nickName)) {
                userInfo.setWechatName(nickName);
            }
            if (StringUtils.isNotBlank(avatarUrl)) {
                userInfo.setWechatIcon(avatarUrl);
            }
            userInfo.setWechatOpenid(openId);
            userInfo = userInfoService.saveUserInfo(userInfo);
        } else {
            userInfo.setWechatOpenid(openId);
            if (StringUtils.isNotBlank(nickName)) {
                userInfo.setWechatName(nickName);
            }
            if (StringUtils.isNotBlank(avatarUrl)) {
                userInfo.setWechatIcon(avatarUrl);
            }
            userInfoService.saveUserInfo(userInfo);
        }
        cUser.setUserInfo(userInfo);
        cUserService.saveCUser(cUser);
        //创建默认账本
        if (null == userInfo.getAccountBookId()) {
            AccountBook accountBook = new AccountBook();
            accountBook.setName("我的账本");
            accountBook.setUid(userInfo.getUid());
            List<UserInfo> userInfos = new ArrayList<>();
            userInfos.add(userInfo);
            accountBook.setUserInfos(userInfos);
            accountBookService.saveAccountBook(accountBook);
            userInfo.setAccountBookId(accountBook.getId());
            userInfoService.saveUserInfo(userInfo);
        }

        result.put("userInfo", userInfo);
        result.put("code", 10000);
        result.put("message", "C端用户绑定成功");
        return result;
    }

    @GetMapping("/wxcheckcuser")
    @ApiOperation(value = "根据openId查看会否已注册", notes = "根据openId查看会否已注册")
    public Map<String, Object> checkCUser(@ApiParam(required = true, value = "openId") @RequestParam String openId) {
        Map<String, Object> result = new HashMap<>();

        CUser cUser = cUserService.findByOpenId(openId);
        if (null != cUser) {
            result.put("code", 10000);
            result.put("isRegisted", true);
            result.put("data", cUser);
            result.put("message", "此用户已注册过");
        } else {
            result.put("code", 10001);
            result.put("isRegisted", false);
            result.put("message", "此用户未注册过");
        }
        return result;
    }


    @PostMapping("/wxupdatecuser")
    @ApiOperation(value = "更新C帐号", notes = "更新C帐号")
    public Map<String, Object> updateCUser(@ApiParam(required = true, value = "openId") @RequestParam String openId,
                                           @ApiParam(required = false, value = "昵称") @RequestParam(required = false) String nickName,
                                           @ApiParam(required = false, value = "城市") @RequestParam(required = false) String city,
                                           @ApiParam(required = false, value = "省") @RequestParam(required = false) String province,
                                           @ApiParam(required = false, value = "性别") @RequestParam(required = false) String gender,
                                           @ApiParam(required = false, value = "头像url") @RequestParam(required = false) String avatarUrl) {
        Map<String, Object> result = new HashMap<>();
        logger.info("wxcreatecuser");

        CUser cUser = cUserService.findByOpenId(openId);


        if (null != nickName && nickName.length() > 0) {
            cUser.setNickName(nickName);
        }
        if (null != city && city.length() > 0) {
            cUser.setCity(city);
        }
        if (null != province && province.length() > 0) {
            cUser.setProvince(province);
        }
        if (null != gender && gender.length() > 0) {
            cUser.setGender(gender);
        }
        if (null != avatarUrl && avatarUrl.length() > 0) {
            cUser.setAvatarUrl(avatarUrl);
        }

        cUserService.saveCUser(cUser);

        result.put("code", 10000);
        result.put("message", "创建C端用户成功");
        result.put("cuser", cUser);
        return result;
    }


}
