package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.enums.CardStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.syzy.domain.BusiWishUniversitySubmitPreRecruitPlan;
import com.ruoyi.syzy.service.IBusiWishUniversitySubmitPreRecruitPlanService;
import com.ruoyi.voluntary.domain.BusiCards;
import com.ruoyi.voluntary.domain.BusiClasses;
import com.ruoyi.voluntary.domain.BusiSchools;
import com.ruoyi.voluntary.service.IBusiCardsService;
import com.ruoyi.voluntary.service.IBusiClassesService;
import com.ruoyi.voluntary.service.IBusiSchoolsService;
import com.ruoyi.web.util.JsonUtils;
import com.ruoyi.web.util.RandomValueUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/mock")
@RestController
public class MockProcessDataController extends BaseController {
    protected static final Logger log = LoggerFactory.getLogger(MockProcessDataController.class);

    @Autowired
    SysLoginController sysLoginController;
    @Autowired
    private IBusiCardsService cardsService;
    @Autowired
    private IBusiSchoolsService schoolService;
    @Autowired
    private IBusiClassesService classesService;

    @Autowired
    private IBusiWishUniversitySubmitPreRecruitPlanService preRecruitPlanService;


    Map<String,String> userTokenMap =new HashMap<>();

    private static String host = "http://localhost:8082";


    @GetMapping("/registerCard2")
    public AjaxResult registerCard2(@RequestParam String startCardNo, @RequestParam String endCardNo,@RequestParam String location) {
//        startCardNo = "002050001331";
//        endCardNo = "002050001332";

        //idea自动补全等号左边：Ctrl+Alt+V
        List<BusiCards> busiCardList = cardsService.selectBusiCardsList(new BusiCards()
                .setStartCard(startCardNo).setEndCard(endCardNo)
                .setStatus(CardStatus.distributed.getValue()));
        List<String> studentNameList = RandomValueUtils.getBatchChineseName(busiCardList.size());
//        List<BusiSchools> busiSchools = schoolService.selectBusiSchoolsByIds(busiCardList.stream().map(BusiCards::getDistributeSchoolId).collect(Collectors.toList()));
//        busiSchools转换为map
//        Map<Long, BusiSchools> schoolsMap = busiSchools.stream().collect(Collectors.toMap(BusiSchools::getId, v -> v));

        //遍历busiCardList后自动登录
        for (int i = 0; i < busiCardList.size(); i++) {
            BusiCards busiCards = busiCardList.get(i);
            if (CardStatus.isActived(busiCards.getStatus())) {
                log.error("card is actived,{}", busiCards.getCardNo());
                continue;
            }
            LoginBody loginBody = new LoginBody();
            loginBody.setUsername(busiCards.getCardNo());
            loginBody.setPassword(busiCards.getPassword());
            String token = this.getUserToken(loginBody);
            if (StringUtils.isEmpty(token)) {
                log.error("token is null,{}", JSONObject.toJSONString(loginBody));
                continue;
            }
            userTokenMap.put(loginBody.getUsername(), token);

            //绑定注册
            bindPhone2(busiCards, token,studentNameList.get(i),location);
        }

        return AjaxResult.success();
    }

    private Boolean bindPhone2(BusiCards card,String token,String nickName,String provinceName){
        //{"username":"15112341234","code":"123456","name":"李旧一","provinceName":"湖南","sex":"0","score":"539","mode":"物理,生物,政治","schoolId":162,"gradeId":500,"classId":1945}
//        body.setValidPhone(false);
        String cardNo = card.getCardNo();
        nickName = StringUtils.isEmpty(nickName)?cardNo:nickName;
        String mobile = 1178+StringUtils.leftPad(cardNo,8,"0");
        String username = StringUtils.isEmpty(mobile)?("1"+cardNo.substring(cardNo.length()-10)):mobile;
        //0男 1女,2未知 ; 旧数据 1男0女
        String sex = "男";
        sex = StringUtils.isEmpty(sex)?"1":("1".equalsIgnoreCase(sex)? "0":"1");
        Integer liberalScience = RandomValueUtils.getNum(0,10)>1?1:0;
        String mode = StringUtils.EMPTY;
        if(provinceName.contains("湖南")||provinceName.contains("湖北")||provinceName.contains("广东")){
            mode = null==liberalScience?"物理,生物,政治":(liberalScience==1?"物理,化学,政治":"历史,生物,政治");
        }else {
            mode = null==liberalScience?"理科":(liberalScience==1?"理科":"文科");
        }
        Integer score = 588;
        Integer gaoKaoYear = 2023;
        gaoKaoYear = null==gaoKaoYear?2023:gaoKaoYear;
        Long gradeId = gaoKaoYear==2023L?700L:(gaoKaoYear==2024L?600L:gaoKaoYear==2025L?500L:700L);
        RegisterBody body = new RegisterBody();
        body.setUsername(username);
        body.setName(nickName);
        body.setProvinceName(provinceName);
        body.setSex(sex);
        body.setScore(score);
        body.setMode(mode);
        body.setGradeId(gradeId);

        body.setSchoolId(card.getDistributeSchoolId());
        BusiClasses query = new BusiClasses();
        query.setSchoolId(card.getDistributeSchoolId());
        query.setGradeId(gradeId);
        classesService.selectBusiClassesList(query).stream().findFirst().ifPresent(v->{
            body.setClassId(v.getClassId());
        });
        if(StringUtils.isNull(body.getClassId())){
            body.setClassId(537L);//prod
        }

        String url= host+"/bindPhone?isMock="+true;
        String res = HttpUtils.postBody(url, JSONObject.toJSONString(body),token);
        JSONObject obj = JSONObject.parseObject(res);
        if(obj.getInteger("code")==200){
            System.out.println("绑定用户信息成功 request"+JSONObject.toJSONString(body)+" response "+res);
        }else {
            log.error("绑定用户信息失败 request {} , response {}",JSONObject.toJSONString(body),res);
        }

        return true;
    }


    @GetMapping("/registerCard")
    public AjaxResult registerCard(String startCardNo, String endCardNo) {
//        startCardNo = "002050001331";
//        endCardNo = "002050001332";

        //idea自动补全等号左边：Ctrl+Alt+V
        List<BusiCards> busiCardList = cardsService.selectBusiCardsList(new BusiCards()
                .setStartCard(startCardNo).setEndCard(endCardNo)
                .setStatus(CardStatus.distributed.getValue()));
        //遍历busiCardList后自动登录
        JSONObject studentMap=getRegisterdStudent();
        busiCardList.forEach(busiCards -> {
            if(CardStatus.isActived(busiCards.getStatus())){
                log.error("card is actived,{}",busiCards.getCardNo());
                return;
            }
            LoginBody loginBody = new LoginBody();
            loginBody.setUsername(busiCards.getCardNo());
            loginBody.setPassword(busiCards.getPassword());
            String token = this.getUserToken(loginBody);
            if(StringUtils.isEmpty(token)){
                log.error("token is null,{}",JSONObject.toJSONString(loginBody));
//                return;
            }
            userTokenMap.put(loginBody.getUsername(),token);

            //绑定注册
            bindPhone(loginBody.getUsername(), studentMap,token);
        });

        return AjaxResult.success();
    }

    private Boolean bindPhone(String cardNo,JSONObject studentMap,String token){
        //{"username":"15112341234","code":"123456","name":"李旧一","provinceName":"湖南","sex":"0","score":"539","mode":"物理,生物,政治","schoolId":162,"gradeId":500,"classId":1945}
//        body.setValidPhone(false);
        if(!studentMap.containsKey(cardNo)){
            log.error("cardNo is not registered,{}",cardNo);
//            return false;
        }
        JSONObject student = studentMap.getJSONObject(cardNo);
        if(null==student) {
            log.error("卡未激活,{}", cardNo);
            return false;
        }
        String name = student.getString("realName");
        name = StringUtils.isEmpty(name)?cardNo:name;
        String mobile = student.getString("mobile");
        String username = StringUtils.isEmpty(mobile)?("1"+cardNo.substring(cardNo.length()-10)):mobile;
        String provinceName = student.getString("provinceName");
        //0男 1女,2未知 ; 旧数据 1男0女
        String sex = student.getString("gender");
        sex = StringUtils.isEmpty(sex)?"1":("1".equalsIgnoreCase(sex)? "0":"1");
        Integer liberalScience = student.getInteger("liberalScience");
        String mode = null==liberalScience?"物理,生物,政治":(liberalScience==1?"物理,化学,政治":"历史,生物,政治");
        Integer score = 588;
        Integer gaoKaoYear = student.getInteger("gaoKaoYear");
        gaoKaoYear = null==gaoKaoYear?2023:gaoKaoYear;
        Long gradeId = gaoKaoYear==2023L?700L:(gaoKaoYear==2024L?600L:gaoKaoYear==2025L?500L:700L);
        RegisterBody body = new RegisterBody();
        body.setUsername(username);
        body.setName(name);
        body.setProvinceName(provinceName);
        body.setSex(sex);
        body.setScore(score);
        body.setMode(mode);
        body.setGradeId(gradeId);

        String middleSchool = student.getString("middleSchool");
        middleSchool = StringUtils.isEmpty(middleSchool)?"临湘市第一中学":middleSchool;
        JSONObject school= getSchool();
        if(!school.containsKey(middleSchool)) {
            log.error("失败：school is not registered,{},body is {}", middleSchool,JSONObject.toJSONString(body));
            return false;
        }
        body.setSchoolId(school.getJSONObject(middleSchool).getLong("id"));
//        body.setClassId(1963L);//test
        body.setClassId(537L);//prod

        String url= host+"/bindPhone";
        String res = HttpUtils.postBody(url, JSONObject.toJSONString(body),token);
        JSONObject obj = JSONObject.parseObject(res);
        if(obj.getInteger("code")==200){
            System.out.println("绑定用户信息成功 request"+JSONObject.toJSONString(body)+" response "+res);
        }else {
            log.error("绑定用户信息失败 request {} , response {}",JSONObject.toJSONString(body),res);
        }

        return true;
    }

    public String getUserToken(LoginBody loginBody){
        if(userTokenMap.containsKey(loginBody.getUsername())){
            userTokenMap.get(loginBody.getUsername());
        }
        String url= host+"/login?type=front";

        StringBuilder sb = new StringBuilder();
        sb.append(url);
        String res = HttpUtils.postBody(url, JSONObject.toJSONString(loginBody),null);
//        log.error("res is {}" ,res);

        JSONObject obj = JSONObject.parseObject(res);
        String token= StringUtils.EMPTY;
        if(obj.getInteger("code")==200){
            token = obj.getString("token");

            return token;
        }else {
            log.error("res is {},{}",JSONObject.toJSONString(obj),JSONObject.toJSONString(loginBody));
            if(userTokenMap.containsKey(loginBody.getUsername())){
                userTokenMap.remove(loginBody.getUsername());
            }
            return token;
//            this.getUserToken(loginBody);
        }

//        return token;
    }

    private JSONObject getRegisterdStudent(){
        JSONArray jsonArray = JsonUtils.readJsonArray("datadata.json");
        JSONObject result = new JSONObject();
        jsonArray.stream().forEach(o->{
            JSONObject jsonObject = (JSONObject) o;
            String cardNo = jsonObject.getString("cardNumber");
            result.put(cardNo,jsonObject);
        });
        return result;
    }

    private JSONObject getSchool(){
//        JSONArray jsonArray = JsonUtils.readJsonArray("school_test.json");
        JSONArray jsonArray = JsonUtils.readJsonArray("school_prod.json");
        JSONObject result = new JSONObject();
        jsonArray.stream().forEach(o->{
            JSONObject jsonObject = (JSONObject) o;
            String name = jsonObject.getString("name");
            result.put(name,jsonObject);
        });
        return result;
    }


    @GetMapping("/processPreEnrollTree")
    public AjaxResult processPreEnrollTree(){
        JSONObject jsonObject = JsonUtils.readJsonObject("tag_all.json");
        jsonObject.keySet().stream().forEach(tag->{
            String tagCode = jsonObject.getString(tag);
            if(StringUtils.isEmpty(tagCode)){
                System.out.println("tag["+tag+"]is empty");
            }

            BusiWishUniversitySubmitPreRecruitPlan update = new BusiWishUniversitySubmitPreRecruitPlan();
            update.setTagCode(tagCode);
            update.setTag(tag);
            preRecruitPlanService.updateBusiWishUniversitySubmitPreRecruitPlanTagCode(update);

//            List<String> tags = preRecruitPlanService.getTags("湖南",2022);
//            tags.stream().forEach(o-> {
//
//                tags.add(tag);
//            });
        });


        return AjaxResult.success(DateUtils.getTime());
    }

    public static void main(String[] args) {
        new MockProcessDataController().processPreEnrollTree();
    }


}
