package com.ruoyi.web.controller.mock;



import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.ie.domain.Questions;
import com.ruoyi.ie.service.IQuestionsService;
import com.ruoyi.system.service.IOssService;
import com.ruoyi.syzy.domain.BBusiWishUniversities;
import com.ruoyi.syzy.domain.BBusiWishUniversitiesEnrollBrochure;
import com.ruoyi.syzy.domain.BBusiWishUniversitiesImage;
import com.ruoyi.syzy.service.IBBusiWishUniversitiesEnrollBrochureService;
import com.ruoyi.syzy.service.IBBusiWishUniversitiesService;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/test/mock")
@Api(tags = "测试")
public class TestSelectCourseController extends BaseController{

//    private static String host = "https://front.mingxuejinbang.com/prod-api";
    private static String host = "http://localhost:8083";

//    protected static final Logger log = LoggerFactory.getLogger(this.getClass());
    protected static final Logger log = LoggerFactory.getLogger(TestSelectCourseController.class);
    Map<String,String> userTokenMap =new HashMap<>();

    @Autowired
    private IQuestionsService questionsService;
    @Autowired
    private IOssService ossService;
    @Autowired
    private IBBusiWishUniversitiesService universitiesService;
    @Autowired
    private IBBusiWishUniversitiesEnrollBrochureService brochureService;

    @PostMapping("/batchProcessImgs")
    public void batchProcessYzyImgs(String questionIds){
        /**
         * questions：title、parse、options、answer
         */
        int type = 1;
        List<String> imgTagList = Arrays.asList("https://img2.meite.com","https://static.dingkao.cn");
        for (String tag : imgTagList) {
            Questions query = new Questions();
            query.setTitle(tag);
            if (StringUtils.isNotBlank(questionIds)) {
                Map paramMap = new HashMap();
                paramMap.put("ids", Arrays.asList(StringUtils.split(questionIds, ",")));
                query.setParams(paramMap);
            }
//            query.setId(174261678L);
            query.setSource("1");
            List<Questions> list = questionsService.selectQuestionsFilter(query);

            for (Questions question : list) {
                Long questionId = question.getId();
                String source = question.getSource();
                System.out.println("start process questionId = " + questionId);
                String title0 = question.getTitle0();
                String parse0 = question.getParse0();
                String options0 = question.getOptions0();
                String answer0 = question.getAnswer0();
                String title10 = question.getTitle1();

                String title = question.getTitle();
                String parse = question.getParse();
                String options = question.getOptions();
                String answer1 = question.getAnswer1();
                String title1 = question.getTitle1();

                if (title.contains(".png") && title.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because title contains png and jpg");
                    continue;
                }
                //材料题
                if (title1.contains(".png") && title1.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because title1 contains png and jpg");
                    continue;
                }
                if (parse.contains(".png") && parse.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because parse contains png and jpg");
                    continue;
                }
                if (options.contains(".png") && options.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because options contains png and jpg");
                    continue;
                }
                if (answer1.contains(".png") && answer1.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because answer1 contains png and jpg");
                    continue;
                }

                if (title.contains(".jpg") || title1.contains(".jpg") || parse.contains(".jpg")
                        || options.contains(".jpg") || answer1.contains(".jpg")) {
                    System.out.println("filter the questionId " + questionId + ",because it contains .jpg");
//                    return;
                }

                if (title.contains("https://edu-tiku.cdn.bcebos.com") || title1.contains("https://edu-tiku.cdn.bcebos.com") || parse.contains("https://edu-tiku.cdn.bcebos.com")
                        || options.contains("https://edu-tiku.cdn.bcebos.com") || answer1.contains("https://edu-tiku.cdn.bcebos.com")) {
                    System.out.println("filter the questionId " + questionId + ",because it contains https://edu-tiku.cdn.bcebos.com");
                    continue;
                }
                if (title.contains(".PNG") || title1.contains(".PNG") || parse.contains(".PNG")
                        || options.contains(".PNG") || answer1.contains(".PNG")) {
                    System.out.println("filter the questionId " + questionId + ",because it contains .PNG");
                    continue;
                }

                Questions qUpdate = new Questions();

                //更新title中的图片
                Boolean isUpdate = false;
                Boolean isContinue = false;
                while (StringUtils.isNotBlank(title) && title.contains(tag)) {
                    isUpdate = true;

                    String logo = StringUtils.EMPTY;
                    if (title.contains(".png")) {
                        logo = title.substring(title.indexOf(tag), title.indexOf(".png") + 4);
                    } else if (title.contains(".gif")) {
                        logo = title.substring(title.indexOf(tag), title.indexOf(".gif") + 4);
                    } else if (title.contains(".jpg")) {
                        logo = title.substring(title.indexOf(tag), title.indexOf(".jpg") + 4);
                    } else if (title.contains(".jpeg")) {
                        logo = title.substring(title.indexOf(tag), title.indexOf(".jpeg") + 5);
                    }

                    System.out.println(logo);
                    title = title.replace(logo, "");
                    //oss上传图片
                    try {
                        if (StringUtils.isNotBlank(logo)) {
                            String newLogo = ossService.uploadFileByUrl(logo, logo.substring(logo.lastIndexOf("/") + 1), "ie/questionImgs/");
                            log.error("title:questionId is {}, oldImg is {}, newImg is {}", questionId, logo, newLogo);
                            title0 = title0.replace(logo, newLogo);
                            //保存图片更新记录
                            saveImgQuestions(questionId, logo, newLogo, type);
                        }
                    } catch (Exception e) {
                        log.info(e.toString());
                        isContinue = true;
                        break;
                    }
                }
                if(isContinue){
                    continue;
                }
                if (isUpdate) {
                    qUpdate.setId(questionId);
                    if (StringUtils.isNotBlank(title0)) {
                        qUpdate.setTitle(title0);
                    }
                }

                //更新title1中的图片
                isUpdate = false;
                while (StringUtils.isNotBlank(title1) && title1.contains(tag)) {
                    isUpdate = true;

                    String logo = StringUtils.EMPTY;
                    if (title1.contains(".png")) {
                        logo = title1.substring(title1.indexOf(tag), title1.indexOf(".png") + 4);
                    } else if (title1.contains(".gif")) {
                        logo = title1.substring(title1.indexOf(tag), title1.indexOf(".gif") + 4);
                    } else if (title1.contains(".jpg")) {
                        logo = title1.substring(title1.indexOf(tag), title1.indexOf(".jpg") + 4);
                    } else if (title1.contains(".jpeg")) {
                        logo = title1.substring(title1.indexOf(tag), title1.indexOf(".jpeg") + 5);
                    }

                    System.out.println(logo);
                    title1 = title1.replace(logo, "");
                    //oss上传图片
                    try {
                        if (StringUtils.isNotBlank(logo)) {
                            String newLogo = ossService.uploadFileByUrl(logo, logo.substring(logo.lastIndexOf("/") + 1), "ie/questionImgs/");
                            log.error("title1:questionId is {}, oldImg is {}, newImg is {}", questionId, logo, newLogo);
                            title10 = title10.replace(logo, newLogo);
                            //保存图片更新记录
                            saveImgQuestions(questionId, logo, newLogo, type);
                        }
                    } catch (Exception e) {
                        log.info(e.toString());
                        break;
                    }
                }
                if (isUpdate) {
                    qUpdate.setId(questionId);
                    if (StringUtils.isNotBlank(title10)) {
                        qUpdate.setTitle1(title10);
                    }
                }

                //更新parse中的图片
                isUpdate = false;
                while (StringUtils.isNotBlank(parse) && parse.contains(tag)) {
                    isUpdate = true;
//                    String logo = parse.substring(parse.indexOf(tag),parse.indexOf(".png")+4);
                    String logo = StringUtils.EMPTY;
                    if (parse.contains(".png")) {
                        logo = parse.substring(parse.indexOf(tag), parse.indexOf(".png") + 4);
                    } else if (parse.contains(".gif")) {
                        logo = parse.substring(parse.indexOf(tag), parse.indexOf(".gif") + 4);
                    } else if (parse.contains(".jpg")) {
                        logo = parse.substring(parse.indexOf(tag), parse.indexOf(".jpg") + 4);
                    } else if (parse.contains(".jpeg")) {
                        logo = parse.substring(parse.indexOf(tag), parse.indexOf(".jpeg") + 5);
                    }

                    System.out.println(logo);
                    parse = parse.replace(logo, "");
                    //oss上传图片
                    if (StringUtils.isNotBlank(logo)) {
                        String newLogo = ossService.uploadFileByUrl(logo, logo.substring(logo.lastIndexOf("/") + 1), "ie/questionImgs/");
                        log.error("parse:questionId is {}, oldImg is {}, newImg is {}", questionId, logo, newLogo);
                        parse0 = parse0.replace(logo, newLogo);
                        //保存图片更新记录
                        saveImgQuestions(questionId, logo, newLogo, type);
                    }
                }
                if (isUpdate) {
                    qUpdate.setId(questionId);
                    qUpdate.setParse(parse0);
                }


                //更新options中的图片
                isUpdate = false;
                while (StringUtils.isNotBlank(options) && options.contains(tag)) {
                    JSONArray optionArray = JSONArray.parseArray(options);
                    if ("2".equals(source)) {
                        //来源（0self，1gzdz，2dk）
                        //将option中的内容转换成map的key-value形式，即source=1的格式
                        List opArray = new LinkedList();
                        for (int i1 = 0; i1 < optionArray.size(); i1++) {
                            String value = (String) optionArray.get(i1);
                            String key = StringUtils.EMPTY;
                            switch (i1) {
                                case 0:
                                    key = "A";
                                    break;
                                case 1:
                                    key = "B";
                                    break;
                                case 2:
                                    key = "C";
                                    break;
                                case 3:
                                    key = "D";
                                    break;
                                case 4:
                                    key = "E";
                                    break;
                                case 5:
                                    key = "F";
                                    break;
                                case 6:
                                    key = "G";
                                    break;
                            }
                            JSONObject tempJSON = new JSONObject();
                            tempJSON.put("key", key);
                            tempJSON.put("value", value);
                            opArray.add(tempJSON);
                        }
                        optionArray = new JSONArray();
                        opArray.forEach(optionArray::add);
                    }

                    if (optionArray != null && optionArray.size() > 0) {
                        for (int i = 0; i < optionArray.size(); i++) {
                            //开始处理options
                            //[{"key":"A","value":"卧室"},{"key":"B","value":"洗手间"},{"key":"C","value":"厨房"}]
                            JSONObject option = optionArray.getJSONObject(i);
                            String key = option.getString("key");
                            String value = option.getString("value");
                            while (StringUtils.isNotBlank(value) && value.contains(tag)) {
                                isUpdate = true;
                                String logo = StringUtils.EMPTY;
                                if (value.contains(".png")) {
                                    logo = value.substring(value.indexOf(tag), value.indexOf(".png") + 4);
                                } else if (value.contains(".gif")) {
                                    logo = value.substring(value.indexOf(tag), value.indexOf(".gif") + 4);
                                } else if (value.contains(".jpg")) {
                                    logo = value.substring(value.indexOf(tag), value.indexOf(".jpg") + 4);
                                } else if (value.contains(".jpeg")) {
                                    logo = value.substring(value.indexOf(tag), value.indexOf(".jpeg") + 5);
                                }

                                System.out.println(logo);
                                value = value.replace(logo, "");
                                options = options.replace(logo, "");
                                //oss上传图片
                                if (StringUtils.isNotBlank(logo)) {
                                    String newLogo = ossService.uploadFileByUrl(logo, logo.substring(logo.lastIndexOf("/") + 1), "ie/questionImgs/");
                                    log.error("options:questionId is {}, oldImg is {}, newImg is {}", questionId, logo, newLogo);
                                    option.put("value", value.replace(logo, newLogo));
                                    options0 = options0.replace(logo, newLogo);
                                    //保存图片更新记录
                                    saveImgQuestions(questionId, logo, newLogo, type);
                                }
                            }


                        }
                    }
                }
                if (isUpdate) {
                    qUpdate.setId(questionId);
                    qUpdate.setOptions(options0);

                }
                //更新各个选项
//                if(isUpdate&&StringUtils.isNotBlank(options0)){
//                    JSONArray optionArray = JSONArray.parseArray(options0);
//                    if(optionArray!=null&&optionArray.size()>0){
//                        for(int i=0;i<optionArray.size();i++){
//                            JSONObject option = (JSONObject) optionArray.getJSONObject(i);
//                            String key = option.getString("key");
//                            String value = option.getString("value");
//                            if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("A")){
//                                qUpdate.setOptionA(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("B")){
//                                qUpdate.setOptionB(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("C")){
//                                qUpdate.setOptionC(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("D")){
//                                qUpdate.setOptionD(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("E")){
//                                qUpdate.setOptionE(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("F")){
//                                qUpdate.setOptionF(value);
//                            }if(StringUtils.isNotBlank(key)&&key.equalsIgnoreCase("G")){
//                                qUpdate.setOptionG(value);
//                            }
//                        }
//                    }
//                }

                //更新answer1中的图片
                isUpdate = false;
                while (StringUtils.isNotBlank(answer1) && answer1.contains(tag)) {
                    isUpdate = true;
//                    String logo = answer1.substring(answer1.indexOf(tag),answer1.indexOf(".png")+4);

                    String logo = StringUtils.EMPTY;
                    if (answer1.contains(".png")) {
                        logo = answer1.substring(answer1.indexOf(tag), answer1.indexOf(".png") + 4);
                    } else if (answer1.contains(".gif")) {
                        logo = answer1.substring(answer1.indexOf(tag), answer1.indexOf(".gif") + 4);
                    } else if (answer1.contains(".jpg")) {
                        logo = answer1.substring(answer1.indexOf(tag), answer1.indexOf(".jpg") + 4);
                    } else if (answer1.contains(".jpeg")) {
                        logo = answer1.substring(answer1.indexOf(tag), answer1.indexOf(".jpeg") + 5);
                    }

                    System.out.println(logo);
                    answer1 = answer1.replace(logo, "");
                    //oss上传图片
                    if (StringUtils.isNotBlank(logo)) {
                        String newLogo = ossService.uploadFileByUrl(logo, logo.substring(logo.lastIndexOf("/") + 1), "ie/questionImgs/");
                        log.error("answer1:questionId is {}, oldImg is {}, newImg is {}", questionId, logo, newLogo);
                        answer0 = answer0.replace(logo, newLogo);
                        //保存图片更新记录
                        saveImgQuestions(questionId, logo, newLogo, type);
                    }
                }
                if (isUpdate) {
                    qUpdate.setId(questionId);
                    qUpdate.setAnswer1(answer0);
                }

                System.out.println(JSONObject.toJSONString(qUpdate));

                qUpdate.setIsUpdate(1);
                questionsService.updateQuestions(qUpdate);
                System.out.println("updated questionId= " + questionId);

            }
        }

        System.out.println("finished all questions");
    }


    String tableName = "questions_image";

    /**
     * 1题目，2院校图，3院校招生简章
     * @param questionId
     * @param oldImg
     * @param newImg
     * @param type
     */
    private void saveImgQuestions(Long questionId,String oldImg,String newImg,int type){
        JSONObject insertData = new JSONObject();
        insertData.put("questionId", questionId);
        insertData.put("oldImg", oldImg);
        insertData.put("newImg", newImg);
        insertData.put("type", type);
        insertData.put("update_time", new Date());

        Entity majorTable = Entity.create(tableName);
        majorTable.putAll(insertData);

        //单个插入专业
        try {
            DbUtil.use().insertOrUpdate(majorTable, "oldImg");
            log.info("插入题目图片数据id：：{}, 数据：{}", insertData.getString("questionId"), JSONObject.toJSONString(insertData));
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /**
     * 批量处理院校图片
     */
    @PostMapping("/batchProcessUniversityImgs")
    public void batchProcessUniversityImgs(){
        /**
         * b_busi_wish_universities：logo、bannerUrl、
         * b_busi_wish_universities_enroll_brochure：content字段内的<img>标签
         */
        List<String> imgTagList = Arrays.asList("https://img2.meite.com");
        imgTagList.forEach(imgTag-> {
            BBusiWishUniversities universities= new BBusiWishUniversities();
            universities.setLogo(imgTag);
            Map<Long,BBusiWishUniversities> universitiesAllMap = universitiesService.selectBBusiWishUniversitiesList(universities).stream().collect(Collectors.toMap(BBusiWishUniversities::getId, Function.identity()));
            universities= new BBusiWishUniversities();
//            universities.setBannerUrl(yzyImgTag);
            universitiesAllMap.putAll(universitiesService.selectBBusiWishUniversitiesList(universities).stream().collect(Collectors.toMap(BBusiWishUniversities::getId,Function.identity())));
            universitiesAllMap.values().forEach(ll->{
                String logo = ll.getLogo();
//                String bannerUrl = ll.getBannerUrl();
                Boolean isUpdate=false;
                if(StringUtils.isNotBlank(logo)&&logo.contains(imgTag)){
                    String newLogo = ossService.uploadFileByUrl(logo,logo.substring(logo.lastIndexOf("/")+1),"ie/universityLog/");
                    ll.setLogo(newLogo);
                    isUpdate=true;
                    log.error("university is {}, newLogo is {}",ll.getName(),newLogo);
                    //保存图片更新记录
                    saveImgQuestions(ll.getId(),logo,newLogo,2);
                }
                if(isUpdate){
                    //更新logo或bannerUrl
                    universitiesService.updateBBusiWishUniversities(ll);
                }
                log.error("finished university");
            });
        });


        imgTagList.forEach(imgTag-> {
            BBusiWishUniversitiesEnrollBrochure query = new BBusiWishUniversitiesEnrollBrochure();
            query.setContent(imgTag);
//            query.setId(112L);
            List<BBusiWishUniversitiesEnrollBrochure> brochureList = brochureService.selectBBusiWishUniversitiesEnrollBrochureList(query);

            brochureList.forEach(ll->{
                String content = ll.getContent();
                Long brochureId = ll.getId();
                if(content.contains(".jpg")&&content.contains(imgTag)){
                    System.out.println("skip brochureId  "+brochureId+"\r\n  content  "+content);
//                    return;
                }
                String content0 = ll.getContent();
                Boolean isUpdate=false;



                BBusiWishUniversitiesEnrollBrochure qUpdate = new BBusiWishUniversitiesEnrollBrochure();
                //更新content中的图片
                while (StringUtils.isNotBlank(content)&&content.contains(imgTag)){
                    isUpdate = true;
//                    String logo = content.substring(content.indexOf(imgTag),content.indexOf(".png")+4);
                    String logo=StringUtils.EMPTY;
//                    if (content.contains(".png")){
//                        logo= content.substring(content.indexOf(imgTag),content.indexOf(".png")+4);
//                    }else if (content.contains(".gif")){
//                        logo= content.substring(content.indexOf(imgTag),content.indexOf(".gif")+4);
//                    }else if (content.contains(".jpg")){
//                        logo= content.substring(content.indexOf(imgTag),content.indexOf(".jpg")+4);
//                    }else if (content.contains(".jpeg")){
//                        logo= content.substring(content.indexOf(imgTag),content.indexOf(".jpeg")+5);
//                    }

                    if (content.contains(".jpg")){
                        logo= content.substring(content.indexOf(imgTag),content.indexOf(".jpg")+4);
                    }

                    System.out.println(logo);
                    content = content.replace(logo,"");
                    //oss上传图片
                    if(StringUtils.isNotBlank(logo)){
                        String newLogo = ossService.uploadFileByUrl(logo,logo.substring(logo.lastIndexOf("/")+1),"ie/universityLog/brochure/");
                        log.error("content:brochureId is {}, oldImg is {}, newImg is {}",brochureId,logo,newLogo);
                        content0 = content0.replace(logo,newLogo);
                        qUpdate.setContent(content0);
                        //保存图片更新记录
                        saveImgQuestions(brochureId,logo,newLogo,3);
                    }
                }
                if(isUpdate){
                    qUpdate.setId(brochureId);
                    qUpdate.setContent(content0);
                    brochureService.updateBBusiWishUniversitiesEnrollBrochure(qUpdate);
                }
                log.error("finished brochure");
            });
        });

    }


    public static void main(String[] args) {
        String logo= "已知<img src=\"https://img2.meite.com/questions/202210/31635f475d6f097.png\" /><br />(1)求<img src=\"https://img2.meite.com/questions/202210/31635f476a0173e.png\" />的值；<br />(2)求<img src=\"https://img2.meite.com/questions/202210/31635f4774b2c56.png\" />的值.";
        while (logo.contains("https://img2.meite.com")){
            String substring = logo.substring(logo.indexOf("https://img2.meite.com"),logo.indexOf(".png")+4);
            System.out.println(substring);
            logo = logo.replace(substring,"");
            System.out.println("替换后："+logo);
        }



    }

}
