package com.izouma.wenlvju.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.kevinsawicki.http.HttpRequest;
import com.izouma.wenlvju.ApplicationTests;
import com.izouma.wenlvju.config.DateConfig;
import com.izouma.wenlvju.domain.Rate;
import com.izouma.wenlvju.domain.User;
import com.izouma.wenlvju.exception.BusinessException;
import com.izouma.wenlvju.repo.RateRepo;
import com.izouma.wenlvju.repo.UserRepo;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TestToken extends ApplicationTests {

    @Autowired
    private UserRepo userRepo;

    @Autowired
    private RateRepo rateRepo;

    @Test
    public void testToken() {
        String appId = "189610";
        String appKey = "3e8d47d8-e6de-4b75-aa07-02b0d6c83678";
        long expiryDate = System.currentTimeMillis() + 1000 * 60 * 10;//10分钟有效时间
        String tokenKey = appId + appKey + expiryDate;

        System.out.println(tokenKey);
        System.out.println(DigestUtils.md5Hex(tokenKey).toLowerCase());
    }

    @Test
    public void testSms() {
        Map<String, Object> map = new HashMap<>();
        map.put("appId", "189610");
        map.put("expiryDate", "1619768481254");
        map.put("tokenKey", "93d2fee65ef4dc7f81757c5fad05f557");
        map.put("operationType", "ADD");
        Map<String, Object> data = new HashMap<>();
        data.put("phone", "13365135976");
        data.put("message", "测试介绍信息");
        map.put("data", data);
        String body = JSONObject.toJSONString(map);
        System.out.println(body);
        HttpRequest.post("http://sms.njlyw.cn/ApiSmsSer/NjuSms/SubmitMultipleMessage")
                .contentType("application/json;charset=UTF-8")
                .send(body)
                .receive(System.out);
//        System.out.println(send.code());
    }

    @Test
    public void testToMap() {
        String str = "{\"Success\":true,\"Code\":\"200\",\"Message\":\"1条成功0条失败\"}";
//        System.out.println(str);
        Map formMap = JSON.parseObject(str, Map.class);
//        System.out.println(formMap);
        Object success = formMap.get("Code");
        String ok = "";
        if (success instanceof String) {
            ok = (String) success;
        }
        if (!"200".equals(ok)) {
            System.out.println("发送失败");
        } else {
            System.out.println("发送成功");
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DateConfig.DEFAULT_DATE_TIME_FORMAT);
        System.out.println(formatter.format(LocalDateTime.now()));

    }

    @Test
    public void testBody() {
        Rate rate = rateRepo.findById(429L).orElseThrow(new BusinessException("无记录"));
        List<Long> ids = new ArrayList<>(rate.getExpertMemberUserId());
        ids.add(rate.getExpertUserId());
        Map<Long, User> userMap = userRepo.findAllById(ids)
                .stream()
                .collect(Collectors.toMap(User::getId, user -> user));
        String message = "已分配新评审计划：\n" +
                "审核单位：%s\n" +
                "单位地址：%s\n" +
                "单位负责人：%s\n" +
                "电话：%s\n" +
                "审核时间区间：%s\n" +
                "专家组长 ： %s-%s\n" +
                "专家组员： %s\n" +
                "线上评审地址： http://wlj.izouma.com/h5/login";
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(DateConfig.DEFAULT_DATE_FORMAT);

        User user = userMap.get(rate.getExpertUserId());
        StringBuilder sb = new StringBuilder();
        rate.getExpertMemberUserId().forEach(id -> {
            User user1 = userMap.get(id);
            sb.append(user1.getNickname()).append("-").append(user1.getPhone()).append("、");
            System.out.println(sb);
        });
        String str = sb.substring(0, sb.length() - 1);
        String date = dtf.format(rate.getReviewStartTime()) + "至" + dtf.format(rate.getReviewEndTime());
        String body = String.format(message, rate.getName(), rate.getDetailAddress(), rate.getOwner(), rate.getOwnerPhone(), date, user
                .getNickname(), user.getPhone(), str);

        System.out.println(body);
    }
}
