package com.template.controller;


import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.template.api.SmartGradeControllerAPI;
import com.template.common.utils.*;
import com.template.config.ControlConfig;
import com.template.model.pojo.SmartGrade;
import com.template.model.pojo.SmartSchool;
import com.template.model.request.insertSmartGradeRequest;
import com.template.model.request.updateSmartGradeRequest;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.BsGradeNoVo;
import com.template.model.vo.BsGradeVo;
import com.template.model.vo.SemesterVo;
import com.template.services.SmartGradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.template.common.utils.AesTestOne.decrypt;

/**
 * <p>
 * 年级表 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-12-25
 */
@RestController
public class SmartGradeController implements SmartGradeControllerAPI {

    @Resource
    private ControlConfig controlConfig;
    @Autowired
    private SmartGradeService smartGradeService;

    @Override
    public CommonResult insertSmartGrade(SmartGrade smartGrade, BindingResult bindingResult) {
        return null;
    }

    @Override
    public CommonResult updateSmartGradeById(updateSmartGradeRequest usgr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        //数据ID是否有效
        SmartGrade oldData = smartGradeService.querySmartGradeById(usgr.getId());
        if(oldData == null){
            return CommonResult.fail("年级数据无效，更新失败");
        }

        //判断重复性
        SmartGrade existData = smartGradeService.existSmartGradeData(usgr.getGradeNo(), usgr.getGradeName());
        if (existData != null && existData.getId().equals(usgr.getId())) {
            return CommonResult.fail("该年级数据已在系统中存在，请勿重复添加");
        }

        //region 修改百胜中的年级数据
        String appId = controlConfig.getAppId();
        String schoolno = controlConfig.getSchoolCode();
        String timestamp = TimeExchange.DateNowTimeStamo();
        String gradeName = usgr.getGradeName();
        String appSecret = controlConfig.getAppSecret();
        String url = controlConfig.getUrl() + "grade/update";

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("appid", appId);
        String str = "{\"grade_no\":\"" + oldData.getBsGradeNo() + "\",\"grade_name\":\"" + gradeName + "\"}";
        String aesStr = URLEncoder.encode(AesTestOne.encrypt(str, controlConfig.getAppSecret()), "UTF-8");
        jsonobject.put("data", aesStr);
        jsonobject.put("schoolno", schoolno);
        jsonobject.put("timestamp", timestamp);

        //appid=ymdd36ed157ac423e2&carNo=赣U123659&parkKey=wdcmq9rc&rand=9.94995525689689966&reserveEndTime=2023-12-22 20:12:10&reserveTime=2023-12-21 18:12:10&version=v1.0&50596cd243dc4547b4c05f01f8ea02a4
        String md5Str = "appid=" + appId + "&data={\"grade_no\":\"" + oldData.getBsGradeNo() + "\",\"grade_name\":\"" + gradeName + "\"}" + "&schoolno=" + schoolno + "&timestamp=" + timestamp + "&key=" + appSecret;
        String sign = CommonUtil.MD5(md5Str);
        //sign签名
        jsonobject.put("sign", sign);

        //返回的结果中 code为1表示成功
        String result = RequestUtils.httpPost(url, jsonobject.toJSONString());

        if (result.contains("更新成功")) {
            oldData.setGradeNo(usgr.getGradeNo());
            oldData.setName(usgr.getGradeName());
            int updateGrade = smartGradeService.updateSmartGrade(oldData);

            if(updateGrade <= 0){
                return CommonResult.fail("年级信息更新失败");
            }
        }else{
            return CommonResult.fail("年级信息更新失败");
        }
        //endregion

        return CommonResult.ok("年级信息更新成功");
    }

    @Override
    public CommonResult queryPageSmartGrades(int currentPage, int pageCount, String name) {
        PageUtils<SmartGrade> result = smartGradeService.queryPageSmartGrade(currentPage, pageCount, name);

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult deleteSmartGradeById(int id) {
        return null;
    }

    @Override
    public CommonResult querySmartGrades() {
        List<SmartGrade> datas = smartGradeService.getSmartGrades();
        List<SemesterVo> result = new ArrayList<>();
        for (SmartGrade data : datas) {
            SemesterVo model = new SemesterVo();
            model.setId(data.getId());
            model.setName(data.getName());
            result.add(model);
        }
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult insertSmartGradeToBaisheng(insertSmartGradeRequest isgr, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        //判断重复性
        int existCount = smartGradeService.existSmartGrade(isgr.getGradeNo(), isgr.getGradeName());
        if (existCount > 0) {
            return CommonResult.fail("该年级数据已在系统中存在，请勿重复添加");
        }

        String appId = controlConfig.getAppId();
        String schoolno = controlConfig.getSchoolCode();
        String timestamp = TimeExchange.DateNowTimeStamo();
        String gradeName = isgr.getGradeName();
        String appSecret = controlConfig.getAppSecret();
        String url = controlConfig.getUrl() + "grade/create";

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("appid", appId);
        String str = "{\"grade_name\":\"" + gradeName + "\"}";
        String aesStr = URLEncoder.encode(AesTestOne.encrypt(str, controlConfig.getAppSecret()), "UTF-8");
        jsonobject.put("data", aesStr);
        jsonobject.put("schoolno", schoolno);
        jsonobject.put("timestamp", timestamp);

        //appid=ymdd36ed157ac423e2&carNo=赣U123659&parkKey=wdcmq9rc&rand=9.94995525689689966&reserveEndTime=2023-12-22 20:12:10&reserveTime=2023-12-21 18:12:10&version=v1.0&50596cd243dc4547b4c05f01f8ea02a4
        String md5Str = "appid=" + appId + "&data={\"grade_name\":\"" + gradeName + "\"}" + "&schoolno=" + schoolno + "&timestamp=" + timestamp + "&key=" + appSecret;
        String sign = CommonUtil.MD5(md5Str);
        //sign签名
        jsonobject.put("sign", sign);

        //返回的结果中 code为1表示成功
        String result = RequestUtils.httpPost(url, jsonobject.toJSONString());

        if (result.contains("添加成功")) {
            ObjectMapper objectMapper = new ObjectMapper();
            BsGradeVo grade = objectMapper.readValue(result, BsGradeVo.class);

            // URL解码
            String decodedUrl = URLDecoder.decode(grade.getData(), "UTF-8");

            BsGradeNoVo gradeNo = objectMapper.readValue(decrypt(decodedUrl, controlConfig.getAppSecret()), BsGradeNoVo.class);

            SmartGrade smartGrade = new SmartGrade();
            smartGrade.setGradeNo(isgr.getGradeNo());
            smartGrade.setName(isgr.getGradeName());
            smartGrade.setBsGradeNo(gradeNo.getGrade_no());

            int insertResult = smartGradeService.insertSmartGrade(smartGrade);

            return insertResult > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");

        } else {
            return CommonResult.fail("添加失败");
        }

    }

}

