package com.xjrsoft.xjrsoftboot;

import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Db;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.xjrsoft.common.constant.GlobalConstant;
import com.xjrsoft.common.exception.MyException;
import com.xjrsoft.common.utils.DatasourceUtil;
import com.xjrsoft.module.evaluate.vo.EvaluateExecuterVo;

import lombok.Data;
import org.junit.jupiter.api.Test;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static java.util.Calendar.DAY_OF_MONTH;

public class StrTest {
    @Test
    public void formatTest() {
        String f = "《{}》等待{}审批。";

        System.out.println(StrUtil.format(f, "sdfsdf", "bbbbbb"));
    }
    @Test
    public void list2StrTest() {
//        List<String> list = new ArrayList();
//        String joined = String.join(",", list);

        String t = "kjk,klj,lkk,lkjd";
        String[] ta = new String[2];
//        ta = t.split(",");
        System.err.println(ta[0]);


    }




    @Test
    public void arrayTest() {
        String f = "《{}》等待{}审批。";

        System.out.println(StrUtil.format(f, "sdfsdf", "bbbbbb"));
    }

    @Test
    public void date() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse("2023-11-22 15:58:40");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        String leaveStartDayStr = sdf1.format(date);//"yyyy-MM-dd"
        String forenoonStartStr = leaveStartDayStr + " 00:00:00";//上午区间开始时间
        String forenoonEndStr = leaveStartDayStr + " 12:00:00";//上午区间结束时间
        String afternoonStartStr = leaveStartDayStr + " 12:00:00";//下午区间开始时间
        String afternoonEndStr = leaveStartDayStr + " 23:59:59";//下午区间结束时间

        //获取请假开始时间后一天的上午，下午区间
        Instant instant = date.toInstant();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        calendar.setTimeInMillis(instant.toEpochMilli());

        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;//获取请假开始的星期（从星期日开始算，所以需要减1）

        calendar.add(DAY_OF_MONTH, 1);
        Date leaveStartDayTomorrow = calendar.getTime();

        String leaveTomorrowDayStr = sdf1.format(leaveStartDayTomorrow);//"yyyy-MM-dd"
        String forenoonStartTomorrowStr = leaveTomorrowDayStr + " 00:00:00";//上午区间开始时间
        String forenoonEndTomorrowStr = leaveTomorrowDayStr + " 12:00:00";//上午区间结束时间
        String afternoonStartTomorrowStr = leaveTomorrowDayStr + " 12:00:00";//下午区间开始时间
        String afternoonEndTomorrowStr = leaveTomorrowDayStr + " 23:59:59";//下午区间结束时间

        Date forenoonStartDate;
        Date forenoonEndDate;
        Date afternoonStartDate;
        Date afternoonEndDate;
        Date forenoonStartTomorrowDate;
        Date forenoonEndTomorrowDate;
        Date afternoonStartTomorrowDate;
        Date afternoonEndTomorrowDate;
        try {
            forenoonStartDate = sdf.parse(forenoonStartStr);
            forenoonEndDate = sdf.parse(forenoonEndStr);
            afternoonStartDate = sdf.parse(afternoonStartStr);
            afternoonEndDate = sdf.parse(afternoonEndStr);
            forenoonStartTomorrowDate = sdf.parse(forenoonStartTomorrowStr);
            forenoonEndTomorrowDate = sdf.parse(forenoonEndTomorrowStr);
            afternoonStartTomorrowDate = sdf.parse(afternoonStartTomorrowStr);
            afternoonEndTomorrowDate = sdf.parse(afternoonEndTomorrowStr);
        } catch (ParseException e) {
            throw new MyException("出现未知错误，请联系管理员");
        }
        System.out.println(afternoonStartTomorrowDate.compareTo(afternoonEndTomorrowDate));
    }

    @Test
    public void date01() throws ParseException {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = sdf.parse("2023-11-23 15:58:40");
//        Date date01 = sdf.parse("2023-11-25 12:58:40");
//        List<DateRange> list = splitDateRangeByDay(LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()),LocalDateTime.ofInstant(date01.toInstant(), ZoneId.systemDefault()));
//        // 添加元素到列表中
//        list.stream().forEach(element -> {
//            // 对元素进行操作
//            System.out.println(element.getBegin());
//            System.out.println(element.getEnd());
//        });
        LocalDateTime dateTime = LocalDateTime.now();
        DayOfWeek dayOfWeek = dateTime.getDayOfWeek();
        System.out.println(dayOfWeek); // 输出星期几的英文表示，例如：MONDAY, TUESDAY, 等等

        int dayOfWeekValue = dayOfWeek.getValue();
        System.out.println(dayOfWeekValue); // 输出星期几的数字表示，1 表示星期一，2 表示星期二，等等

        String dayOfWeekChinese = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.CHINESE);
        System.out.println(dayOfWeekChinese); // 输出星期几的中文表示，例如：星期一，星期二，等等
    }

    @Data
    public class DateRange {

        /**
         * 开始时间
         */
        private LocalDateTime begin;

        /**
         * 结束时间
         */
        private LocalDateTime end;

        /**
         * 当前时间的第几轮（段）
         */
        private Long turnNum;
    }

    /**
     * 按日分割
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 分割后的时间段集合
     */
    private List<DateRange> splitDateRangeByDay(LocalDateTime startTime, LocalDateTime endTime) {
        long seconds = startTime.until(endTime, ChronoUnit.SECONDS);
        if (seconds < 0) {
            return new ArrayList<>();
        }
        //轮数
        long turnNum = 0;
        //分割的时间段集合，使用累加算法
        List<DateRange> dateList = new ArrayList<>();
        DateRange range = new DateRange();
        range.setBegin(startTime);
        while (true) {
            turnNum++;
            startTime = startTime.plusDays(1);
            //大于截止日期时，不再累加
            if (startTime.isAfter(endTime)) {
                range.setEnd(endTime);
                range.setTurnNum(turnNum);
                dateList.add(range);
                break;
            }
            //将时间调整为该天的 0时 0分 0秒
            startTime = LocalDateTime.of(startTime.getYear(), startTime.getMonth(), startTime.getDayOfMonth(), 0, 0, 0);
            LocalDateTime tmpBegin = startTime;
            //计算出上一天的最后一秒
            LocalDateTime endDate = tmpBegin.minusSeconds(1);
            range.setEnd(endDate);
            range.setTurnNum(turnNum);
            dateList.add(range);
            //创建新的时间段
            range = new DateRange();
            range.setBegin(tmpBegin);
        }
        return dateList;
    }

    @Test
    void test22() {
        String name = "2023年秋季";
        System.out.println(name.contains("秋季"));
    }

    @Test
    public void StringTest() {
        String str = "电子“1+x”集成电路检测技术应用（初级）考试";
        str = str.replace("“", "").replace("”", "").replace("\"", "").replace("\n", "").replace("\r", "").replace("\t", "");
        System.out.println(str);
    }

    @Test
    public void sortCodeTest() throws SQLException {
        DataSource datasource = DatasourceUtil.getDataSource(GlobalConstant.DEFAULT_DATASOURCE_KEY);
        Db use = Db.use(datasource);
        String sql = "SELECT max(sort_code) FROM evaluate_template";
        int sortCodeMax = use.queryNumber(sql, Integer.class).intValue();
        System.err.println(sortCodeMax);
    }

    @Test
    public void listTest(){
        List<EvaluateExecuterVo> executerList = new ArrayList<>();
        System.err.println(executerList.size());
    }

    @Test
    public void evalTest() throws ScriptException {
        ScriptEngine engine = new ScriptEngineManager().getEngineByName("js");
        int totalScore = 5;
        int itemCount = 3;
        String zonghezhishu = "totalScore/itemCount";
        String newStr = zonghezhishu.replace("totalScore",""+totalScore);
        //double t = (double)engine.eval(zonghezhishu);
        System.err.println(newStr);
    }

    @Test
    public void ListTest() {
        String[] str = new String[] { "chen", "yang", "hao" };
        List<String> list = new ArrayList<>();
        list = Arrays.asList(str);
        list.add("kji");
        System.err.println(list.get(3));

        String[] array = {"apple", "banana", "orange"};

        List<String> fixedSizeList = Arrays.asList(array);

        // 转换为可变的ArrayList
        List<String> mutableList = new ArrayList<>(fixedSizeList);

        // 添加元素
        mutableList.add("grape");

        // 删除元素
        mutableList.remove(0);

        System.out.println(mutableList);
    }

    @Test
    public void parseJsonTest() {
        String jsonStr = "{\"apiInfo\":{\"path\":\"ledger/document-received-page\",\"method\":\"GET\",\"apiId\":\"78aebf1b26424de8b39697b5e6cacef1\",\"apiParams\":[{\"key\":\"1\",\"title\":\"Query Params\",\"tableInfo\":[{\"name\":\"receivedTitle\",\"value\":\"123\",\"description\":\"收文标题\",\"required\":false,\"dataType\":\"String\",\"type\":null,\"defaultValue\":null,\"validateType\":null,\"error\":null,\"expression\":null,\"children\":null},{\"name\":\"receivedNumber\",\"value\":null,\"description\":\"收文编号\",\"required\":false,\"dataType\":\"String\",\"type\":null,\"defaultValue\":null,\"validateType\":null,\"error\":null,\"expression\":null,\"children\":null},{\"name\":\"size\",\"value\":null,\"description\":\"每页大小\",\"required\":false,\"dataType\":\"Integer\",\"type\":null,\"defaultValue\":\"10\",\"validateType\":null,\"error\":null,\"expression\":null,\"children\":null},{\"name\":\"limit\",\"value\":null,\"description\":\"当前页标\",\"required\":false,\"dataType\":\"Integer\",\"type\":null,\"defaultValue\":\"1\",\"validateType\":null,\"error\":null,\"expression\":null,\"children\":null}]},{\"key\":\"2\",\"title\":\"Header\",\"tableInfo\":[]},{\"key\":\"3\",\"title\":\"Body\"}],\"script\":\"int page = (limit - 1) * size;\\r\\nreturn db.page(\\\"\\\"\\\"\\r\\n\\tSELECT t1.received_title,t1.received_number,t1.received_date,t1.communication_org,\\r\\n    t1.communication_number,t1.checkout_time,t2.name AS document_level,t3.name AS emergency_level_cn,t4.name AS received_type_cn,t1.file_id FROM  official_document_received t1\\r\\n    LEFT JOIN xjr_dictionary_detail t2 ON t1.document_level = t2.code AND t2.item_id = 1731945940933791746\\r\\n    LEFT JOIN xjr_dictionary_detail t3 ON t1.emergency_level = t3.code AND t3.item_id = 1731946318697975810\\r\\n    LEFT JOIN xjr_dictionary_detail t4 ON t1.received_type = t4.code AND t4.item_id = 1742444951069847553\\r\\n    WHERE t1.delete_mark = 0\\r\\n    <if test=\\\"receivedTitle != null and receivedTitle != ''\\\">\\r\\n      and t1.received_title like concat('%', #{receivedTitle}, '%')\\r\\n    </if>\\r\\n    <if test=\\\"receivedNumber != null and receivedNumber != ''\\\">\\r\\n      and t1.received_number like concat('%', #{receivedNumber}, '%')\\r\\n    </if>\\r\\n\\\"\\\"\\\",size, page);\"},\"tableFieldConfigs\":[{\"fieldName\":\"receivedTitle\",\"fieldComment\":\"receivedTitle\"},{\"fieldName\":\"receivedNumber\",\"fieldComment\":\"receivedNumber\"},{\"fieldName\":\"receivedDate\",\"fieldComment\":\"receivedDate\"},{\"fieldName\":\"communicationNumber\",\"fieldComment\":\"communicationNumber\"},{\"fieldName\":\"checkoutTime\",\"fieldComment\":\"checkoutTime\"},{\"fieldName\":\"documentLevel\",\"fieldComment\":\"documentLevel\"},{\"fieldName\":\"emergencyLevelCn\",\"fieldComment\":\"emergencyLevelCn\"},{\"fieldName\":\"receivedTypeCn\",\"fieldComment\":\"receivedTypeCn\"},{\"fieldName\":\"fileId\",\"fieldComment\":\"fileId\"}],\"columnConfigs\":[{\"key\":\"549452a1434d4aaf9abb75e6e2354bdc\",\"field\":\"receivedTitle\",\"label\":\"receivedTitle\",\"autoWidth\":false,\"width\":100,\"sort\":10},{\"key\":\"c382af822d7a4b7da1a60c619ea9a94b\",\"field\":\"receivedNumber\",\"label\":\"receivedNumber\",\"autoWidth\":false,\"width\":100,\"sort\":10}],\"serachConfigs\":[{\"key\":\"8f4211d75bdd4e728fdba5c158936d3c\",\"field\":\"receivedTitle\",\"label\":\"receivedTitle\",\"component\":\"Input\",\"bindObject\":\"\",\"sort\":10,\"bindValue\":\"\",\"defaultValue\":\"\",\"apiInfo\":{\"path\":\"\"}}],\"buttonConfigs\":{\"main\":[{\"use\":true,\"label\":\"导出\",\"value\":\"export\",\"url\":\"1245\"}],\"item\":[{\"use\":false,\"label\":\"查看\",\"value\":\"view\",\"url\":\"\"},{\"use\":false,\"label\":\"附件预览\",\"value\":\"preview\",\"url\":\"\"}]}}";
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(jsonStr).getAsJsonObject();

        JsonArray columnConfigs = jsonObject.get("columnConfigs").getAsJsonArray();

        for (JsonElement element : columnConfigs) {
            System.out.println(element.getAsJsonObject().get("key").getAsString());
        }

//        System.err.println(columnConfigs.size());

//        String name = jsonObject.get("columnConfigs").getAsString();
//        int age = jsonObject.get("age").getAsInt();
//
//        System.out.println("Name: " + name);
//        System.out.println("Age: " + age);
    }
}
