package com.qiankun.controller.rainbowplan;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qiankun.annotation.Auth;
import com.qiankun.config.WxMaConfiguration;
import com.qiankun.utils.JwtTokenUtil;
import com.qiankun.vo.PublishWish;
import com.qiankun.vo.RegisterInfo;
import com.qiankun.vo.UserInfo;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/wx/rainbowplan/{appid}")
public class RainbowPlanController {
    private final Logger logger = LoggerFactory.getLogger(RainbowPlanController.class);
    private static Map<String, UserInfo> userInfoMap = Maps.newConcurrentMap();
    private static Map<String, List<PublishWish>> wishMap = Maps.newConcurrentMap();
    @Autowired
    private JwtTokenUtil tokenUtil;

    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/validateExpired",method = RequestMethod.GET)
    public Map<String,Object> validateToken(@PathVariable String appid,@RequestHeader("token") String token){
        Map<String,Object> result = Maps.newConcurrentMap();
        result.put("result",tokenUtil.isTokenExpired(token));
        return result;
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public Map<String,String> login(@PathVariable String appid, @RequestParam String code){
        if (StringUtils.isBlank(code)) {
            return null;
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            Map<String,String> result = Maps.newConcurrentMap();
            //TODO 判断openid是否在数据库中存在
            if (userInfoMap.containsKey(session.getOpenid())){
                //生成sKey
                String sKey = tokenUtil.generateToken(session.getOpenid());
//                result.put("session",session);
                result.put("sKey",sKey);
            }else {
                result.put("sKey","");

            }
            result.put("openid",session.getOpenid());

            return result;
        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return null;
        }
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public String register(@PathVariable String appid,@RequestBody RegisterInfo info){
        if (Strings.isNullOrEmpty(info.getOpenid())){
            throw new IllegalArgumentException("请求参数错误");
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(UUID.randomUUID().toString());
        userInfo.setPhone(info.getPhone());
        userInfo.setName(info.getName());
        userInfo.setGender(info.getGender());
        userInfoMap.put(info.getOpenid(),userInfo);
        return tokenUtil.generateToken(info.getOpenid());
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/userInfo",method = RequestMethod.GET)
    public UserInfo getUserInfo(@PathVariable String appid, @RequestHeader String sKey) throws Exception {
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        if (!userInfoMap.containsKey(openid)) {
            throw new Exception("请求的用户不存在");
        }

        return userInfoMap.get(openid);
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/userInfo",method = RequestMethod.POST)
    public String updateUserInfo(@PathVariable String appid,@RequestBody UserInfo info,@RequestHeader String sKey){
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        UserInfo userInfo = findUserInfo(openid);
        userInfo.setName(info.getName());
        userInfo.setNickName(info.getNickName());
        userInfo.setPhone(info.getPhone());
        userInfo.setGender(info.getGender());
        userInfo.setBirthday(info.getBirthday());
        userInfo.setBedNum(info.getBedNum());
        userInfo.setReceiveName(info.getReceiveName());
        userInfo.setConnectTel(info.getConnectTel());
        userInfo.setReceiveAddress(info.getReceiveAddress());
        userInfo.setAvatar(info.getAvatar());


        return "OK";
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/userInfoWithAvatar",method = RequestMethod.POST)
    public String updateUserInfoWithAvatar(@PathVariable String appid, UserInfo info, @RequestHeader String sKey) throws IOException {
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        UserInfo userInfo = findUserInfo(openid);
        if (!info.getFile().isEmpty()){
//            BASE64Encoder encoder = new BASE64Encoder();
//            String imageData = encoder.encode(info.getFile().getBytes());


            String originalFileName = info.getFile().getOriginalFilename();
            String path = "/Users/liuyang/uploadImage";
            File destFile = new File(path,originalFileName);
            FileUtils.writeByteArrayToFile(destFile,info.getFile().getBytes());
            userInfo.setName(info.getName());
            userInfo.setNickName(info.getNickName());
            userInfo.setPhone(info.getPhone());
            userInfo.setGender(info.getGender());
            userInfo.setBirthday(info.getBirthday());
            userInfo.setBedNum(info.getBedNum());
            userInfo.setReceiveName(info.getReceiveName());
            userInfo.setConnectTel(info.getConnectTel());
            userInfo.setReceiveAddress(info.getReceiveAddress());
            userInfo.setAvatar(info.getAvatar());
            userInfo.setAvatar(originalFileName);
        }
        return "OK";
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/publishWish",method = RequestMethod.POST)
    public String publishWish(@PathVariable String appid, PublishWish publishWish,@RequestHeader String sKey) throws IOException {
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        if (!publishWish.getFile().isEmpty()){
//            BASE64Encoder encoder = new BASE64Encoder();
//            String imageData = encoder.encode(info.getFile().getBytes());


            String originalFileName = publishWish.getFile().getOriginalFilename();
            String path = "/Users/liuyang/uploadImage";
            File destFile = new File(path,originalFileName);
            FileUtils.writeByteArrayToFile(destFile,publishWish.getFile().getBytes());
            List<PublishWish> wishList = Lists.newArrayList();
            if (wishMap.containsKey(openid)){
                wishList = wishMap.get(openid);
            }
            PublishWish wish = new PublishWish();
            wish.setTitle(publishWish.getTitle());
            wish.setWish(publishWish.getWish());
            wish.setWishImage(originalFileName);
            wishList.add(wish);
            wishMap.put(openid,wishList);
        }
        return "OK";
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/wish/list",method = RequestMethod.GET)
    public List<PublishWish> wishList(@PathVariable String appid,@RequestHeader String sKey){
        if (Strings.isNullOrEmpty(sKey)){
            throw new IllegalArgumentException("请求参数错误");
        }
        String openid = tokenUtil.getUsernameFromToken(sKey);
        return wishMap.get(openid);
    }

    private UserInfo findUserInfo(String openid){
        return userInfoMap.get(openid);
    }
    @Auth(verifyLogin = false,verifyURL = false)
    @RequestMapping(value = "/loadResource",method = RequestMethod.GET)
    public ResponseEntity<byte[]> loadResource(@RequestParam String imageName) throws IOException {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        File file = new File("/Users/liuyang/uploadImage",imageName);
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    }
}
