package cn.wise.sc.cement.business.controller;

import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.service.impl.WeiXinService;
import cn.wise.sc.cement.business.util.weixin.Global;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "微信接口")
@RestController
@RequestMapping("/tcdri/weixin")
public class WeiXinController {

    private static final Logger log = LoggerFactory.getLogger("WeiXinController");

    @Autowired
    private WeiXinService weiXinService;

    @ApiOperation(value = "获取登录token-小程序端")
    @GetMapping("/getToken")
    public BaseResponse getToken(String code) {

        log.debug("============================================");
        log.debug("code: {}", code);
        log.debug("=============================================");
        try {
            //测试服务器
            return weiXinService.getTestToken(code);
            //正式服务器
//            return weiXinService.getToken(code, "APP");
        } catch (Exception e) {
            log.debug("获取登录token{}", e);
        }
        return BaseResponse.errorMsg("失败!");
    }

    @ApiOperation(value = "获取登录token-管理端")
    @GetMapping("/getPCToken")
    public BaseResponse getPCToken(String code) {
        try {
            //测试服务器
//            return weiXinService.getTestToken(code);
            //正式服务器
            return weiXinService.getToken(code, "PC");
        } catch (Exception e) {
            log.debug("获取登录token{}", e);
        }
        return BaseResponse.errorMsg("失败!");
    }

    @ApiOperation(value = "当前登录用户")
    @GetMapping("/getLoginUser")
    public BaseResponse getLoginUser() {
        try {
            return weiXinService.getLoginUser();
        } catch (Exception e) {
            log.debug("当前登录用户{}", e);
        }
        return BaseResponse.errorMsg("失败!");
    }

    @GetMapping("/jsapiTicket")
    @ApiOperation("获取jsapi_ticket")
    public BaseResponse<Map> getAccessToken() {
        String accessToken = weiXinService.getJsapiTicket();
        Map<String, String> rts = new HashMap<>(5);
        rts.put("jsapi_ticket", accessToken);
        rts.put("timestamp", (new Date()).getTime() / 1000 + "");
        rts.put("noncestr", "Wm3WZYTPz0wzccnW");
        rts.put("app_id", "ww348f91b2573c1867");
        rts.put("jsApiList","['scanQRCode']");
        return BaseResponse.okData(rts);
    }

    @GetMapping("/signature")
    @ApiOperation("获取accessToken")
    public BaseResponse<String> signature(String param) {
        MessageDigest md;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(param.getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return BaseResponse.okData(StrUtil.swapCase(tmpStr));
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }


    @Value("${weixin.systemUrl}")
    private String systemUrl;

    @ApiOperation(value = "发送消息")
    @GetMapping("/sendTextMessage")
    public BaseResponse sendTextMessage() {
        try {
            //发送企业微信消息内容
            String content="你好！"+"竹天卫"+"向您申请了一条委托，请前往\n" +
                    systemUrl+"进行评审。";
            System.out.println("**************************content**********************");
            System.out.println(content);
            weiXinService.sendTextMessage("ZhuTianWei", content);


//            weiXinService.sendTextMessage("1","hello");
            return BaseResponse.okData("成功");
        } catch (Exception e) {
            log.debug("发送消息{}", e);
        }
        return BaseResponse.errorMsg("失败!");
    }

}
