<template>
  <view class="content">
    <button
      type="default"
      open-type="getPhoneNumber"
      @getphonenumber="decryptPhoneNumber"
      v-if="false"
      @click="login"
    >
      微信授权一键登录
    </button>

    <button @click="httpTest" style="margin-top: 10rps">
      h5 axios http请求
    </button>

    <button @click="wxHttpTest" style="margin-top: 10rps">
      miniprogram http请求
    </button>

    <button @click="chooseImage" style="margin-top: 10rps">上传图片</button>
  </view>
</template>

<script>
import httpClient from "../../common/httpClient.js";
// import {common,	user} from '../../proto/bundle.js';
// //const protobuf = require("protobufjs/minimal");
// const axios = require('axios');

// let loginMessage = user.login_req.create({
// 	phone: '1234567890',
// 	type: 1,
// 	verifyInfo: '123456a',
// })
// //proto对象转buffer
// let buffer = user.login_req.encode(loginMessage).finish()
// console.log(buffer);
// let requestMessage = common.MsgWebsocket.create({
// 	version: 1,
// 	app: 1,
// 	server: 2,
// 	servant: 1005,
// 	data: buffer,
// })
// let requestBuffer = common.MsgWebsocket.encode(requestMessage).finish()
// console.log(requestBuffer);

// let typeStr = Object.prototype.toString.call(requestBuffer.buffer)
// console.log(typeStr);
export default {
  data() {
    return {};
  },
  methods: {
    //选择图片
    chooseImage() {
      let that = this;

      uni.chooseImage({
        count: 1,
        success(res) {
          console.log(res);
          let file = res.tempFiles[0];
          console.log(file);
          that.wxUploadImage(file);
        },
      });
    },
    //上传图片
    wxUploadImage(file) {
      httpClient
        .uploadFile(file.path, "image/jpeg")
        .then((result) => {
          console.log(result);
        })
        .catch((err) => {
          console.warn(err);
        });
    },
    login() {},
    decryptPhoneNumber(e) {
      console.log(e.detail.errMsg);
      console.log(e.detail.iv);
      console.log(e.detail.encryptedData);
    },
    wxHttpTest() {
      //try{
      httpClient
        .post({
          server: 2,
          servant: 1005,
          data: {
            // phone:Buffer.from('3246541321'),
            phone: "3246541321",
            type: 1,
            //verifyInfo:Buffer.from('asdasd')
            verifyInfo: "asdasd",
            data: {},
          },
        })
        .then(
          (res) => {
            console.log(res);
            /* res的结构
					  {
						  code:0,错误码 number类型
						  msg:"",错误消息 string类型
						  data:对应loginRsp的js对象
					  }
					 */
            if (res.code === 0) {
              //成功
            } else {
              //失败
            }
          },
          (err) => {
            //出现异常
            console.log(err);
          }
        );
    },
    wxHttpTest1() {
      let typeStr = Object.prototype.toString.call(requestBuffer.buffer);
      console.log(typeStr);
      let requestArrayBuf = new Uint8Array([...requestBuffer]).buffer;
      uni
        .request({
          //url:'https://test.api1.radio1964.com:80/Ohplay/Web/HttpToTcp'
          url: "http://60.205.190.38:80/Ohplay/Web/HttpToTcp",
          header: {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/x-protobuf",
            Token:
              "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyaWQiOjY1MDYzMywibmFtZSI6IjE4MTI2NDQ3MDE1IiwiZXhwIjoxNjIyODg0NTA1fQ.f7jIm0856-VnynA99MBoA2Dl1pePxI0HT_ECsUp5QHA",
          },
          method: "POST",
          timeout: 15000,
          dataType: "protobuf",
          responseType: "arraybuffer",
          data: requestArrayBuf,
        })
        .then(
          (res) => {
            console.log(res);
            for (let response of res) {
              if (
                response !== null &&
                response !== undefined &&
                response.statusCode === 200
              ) {
                try {
                  let enc = new TextDecoder("utf-8");
                  let res = JSON.parse(
                    enc.decode(new Uint8Array(response.data))
                  ); //转化成json对象
                  console.log(res);
                } catch (e) {
                  //let resBuf = protobuf.util.newBuffer(response.data)
                  let resBuf = Buffer.from(response.data);
                  //console.log(resBuf.toString());
                  let resMessage = common.MsgWebsocket.decode(resBuf);
                  console.log(resMessage);
                  let loginRspBuf = resMessage.data;
                  console.log(loginRspBuf);
                  let loginRspMessage = user.login_rsp.decode(loginRspBuf);
                  console.log(loginRspMessage);
                  let obj = user.login_rsp.toObject(loginRspMessage, {
                    longs: String,
                    enums: String,
                  });
                  console.log(obj);
                  console.log(
                    `errorMessage = ${Buffer.from(
                      loginRspMessage.errInfo.errorMessage
                    ).toString()}`
                  );
                  //console.log(Buffer.from(loginRspMessage.errInfo.errorMessage).toString());
                }
              }
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
    httpTest() {
      //测试http请求
      // let blob = new Blob([requestBuffer], {
      // 	type: 'buffer'
      // });
      // 将请求数据encode成二进制，encode是proto.js提供的方法
      function transformRequest(data) {
        return common.MsgWebsocket.encode(requestMessage).finish();
      }
      axios
        .create({
          timeout: 15000,
          method: "post",
          headers: {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/octet-stream",
            //'Token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VyaWQiOjY1MDYzMywibmFtZSI6IjE4MTI2NDQ3MDE1IiwiZXhwIjoxNjIyODg0NTA1fQ.f7jIm0856-VnynA99MBoA2Dl1pePxI0HT_ECsUp5QHA'
          },
          responseType: "arraybuffer",
        })
        .post("http://60.205.190.38:80/Ohplay/Web/HttpToTcp", requestMessage, {
          transformRequest: transformRequest,
        })
        .then(
          (response) => {
            console.log(response);
            if (response.status === 200 /* && response.data.byteLength>0*/) {
              try {
                let enc = new TextDecoder("utf-8");
                let res = JSON.parse(enc.decode(new Uint8Array(response.data))); //转化成json对象
                console.log(res);
              } catch (e) {
                //let resBuf = protobuf.util.newBuffer(response.data)
                let resBuf = Buffer.from(response.data);
                console.log(resBuf.toString());
                let resMessage = common.MsgWebsocket.decode(resBuf);
                let loginRspBuf = resMessage.data;
                let loginRspMessage = user.login_rsp.decode(loginRspBuf);
                let obj = user.login_rsp.toObject(loginRspMessage, {
                  longs: String,
                  enums: String,
                });
                console.log(obj);
                console.log(
                  `errorMessage = ${Buffer.from(
                    loginRspMessage.errInfo.errorMessage
                  ).toString()}`
                );
              }
            }
          },
          (err) => {
            console.log(err);
          }
        );
    },
  },
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 20rpx;
}
</style>
