package com.rf.psychological.scale.rest;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.file.excel.ExcelClass;
import com.rf.psychological.dao.model.HearingTestEntity;
import com.rf.psychological.dao.model.ObjectEntity;
import com.rf.psychological.user.dao.model.UserEntity;
import com.rf.psychological.scale.dao.model.UserRecordEntity;
import com.rf.psychological.opLog.annotation.OperationLogAnnotation;
import com.rf.psychological.security.AesEncryptUtils;
import com.rf.psychological.security.SafetyProcess;
import com.rf.psychological.scale.service.CognitiveTaskService;
import com.rf.psychological.scale.service.HearingTestService;
import com.rf.psychological.scale.service.UserRecordService;
import com.rf.psychological.user.service.UserService;
import com.rf.psychological.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author zsy
 * @description:听觉词语学习测验（华山版）
 * @date 2021/6/17 15:55
 */

@Slf4j
@RestController
@RequestMapping("/hearing")
@Api(tags = "听觉词语学习测验（华山版）")
public class HearingTestController extends BaseController {

    @Autowired
    private HearingTestService hearingTestService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private CognitiveTaskService cognitiveTaskService;

    /**
     * 添加听觉词语学习测验（华山版）信息
     *
     * @param
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/saveHearingTest")
    @ApiOperation("添加听觉词语学习测验（华山版）信息")
    public Result saveHearingTest(@RequestBody String json) throws Exception {
        //public Result saveMemoryCheck(@RequestBody JSONObject jsonObject ) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONObject.parseObject(data);
        String userId = jsonObject.getString("userId");
        String testPlanId = "0";
        if (jsonObject.containsKey("testPlanId")) {
            testPlanId = jsonObject.getString("testPlanId");
        }
        UserEntity userEntity = this.userService.getOne(userId);
        String phone = userEntity.getPhone();
        String institutionNo = userEntity.getInstitutionNo();

        DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        //当前时间
        String testTime = df.format(new Date());
        JSONArray jsonArray = jsonObject.getJSONArray("HearingTests");
        //答题结果列表
        List<HearingTestEntity> dataList = jsonArray.toJavaList(HearingTestEntity.class);
        //创建测试记录所需信息
        List<HearingTestEntity> hearingTestEntityList = new ArrayList<>();
        int y = 0;
        for (HearingTestEntity hearingTestEntity : dataList) {
            hearingTestEntity.setPhone(phone);
            hearingTestEntity.setTestDate(testTime);
            hearingTestEntity.setStatus(1);
            if (hearingTestEntity.getRound().equals("7")) {
                this.hearingTestService.save(hearingTestEntity);
                //根据phone获取用户进行中任务
                hearingTestEntityList = this.hearingTestService.getHearingTestList(phone);
                for (HearingTestEntity hearingTestEntity1 : hearingTestEntityList) {
                    this.hearingTestService.updateStatus(hearingTestEntity1.getId());
                }
            } else {
                y++;
                this.hearingTestService.save(hearingTestEntity);
                if (dataList.size() == y) {
                    return success();
                }
            }
        }
        String datas = new String();
        //生成测试记录文件并在数据库插入用户测试记录
        String userName = userEntity.getPetName();
        String userBirthday = userEntity.getBirthday();
        String userSex = userEntity.getGender();
        if (userSex.equals("0")) {
            userSex = "男";
        } else {
            userSex = "女";
        }
        testTime = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒").format(new Date());
        String fileName = userName + Constant.SPLIT_CHAR + userBirthday + Constant.SPLIT_CHAR + userSex + Constant.SPLIT_CHAR + testTime;
        String testResult = new String();
        String name = new String();
        List<Map<String, String>> resultMapList = new ArrayList<>();
        // 创建返回的json对象
        JSONObject resultJson = new JSONObject(true);
        // 创建入库的json对象
        JSONObject resultDBJson = new JSONObject(true);

        List<ObjectEntity> objectEntityList = new ArrayList<>();
        int x = 1;
        for (HearingTestEntity hearingTestEntity : hearingTestEntityList) {

            ObjectEntity objectEntity1 = new ObjectEntity();
            objectEntity1.setKey("N"+x);
            objectEntity1.setValue(String.valueOf(hearingTestEntity.getGrade()));
            resultJson.put("N"+x, String.valueOf(hearingTestEntity.getGrade()));
            objectEntityList.add(objectEntity1);
            x++;
        }
        datas = hearingTestEntityList.toString();
        fileName = fileName + Constant.SPLIT_CHAR + Constant.SHEET_NAME_MTH + ".xlsx";
        name = Constant.SHEET_NAME_MTH;
        ExcelUtil.createExcelFile(ObjectEntity.class, objectEntityList, null, new ExcelClass().contentExcel(Constant.QUEST_TYPE_MTH), fileName, Constant.SHEET_NAME_MTH);

        // 获取JSON第一层所有的key
        Set<String> keys = resultJson.keySet();

        //计算结果
        JSONArray dbJsonList = new JSONArray();
        JSONObject dbJson = new JSONObject(true);
        JSONArray tableContext = new JSONArray();
        //列名
        List colNames = new ArrayList();
        colNames.add("项目");
        colNames.add("内容");
        dbJson.put("colNames", colNames);

        // 获取第一层每个key对应的值 的类型
        for (String key : keys) {
            //列值
            List colValue = new ArrayList();
            colValue.add(resultJson.get(key));
            JSONObject row = new JSONObject();
            row.put("name", key);
            row.put("value", colValue);
            tableContext.add(row);
        }
        dbJson.put("tableContext", tableContext);
        dbJsonList.add(dbJson);
        int i = 1;
        // 获取第一层每个key对应的值 的类型
        for (String key : keys) {
            if (i == keys.size()) {
                testResult += key + ":" + resultJson.get(key);
            } else {
                testResult += key + ":" + resultJson.get(key) + ";";
            }
            i++;
        }

        //测试记录
        String filePath;
        if (OSUtil.isLinux()) {
            filePath = "./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + name + "/" + fileName;
        } else {
            filePath = "./心理检测/检测结果/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + name + "/" + fileName;
        }
        UserRecordEntity userRecordEntity = testRecord("MTH", phone, institutionNo, testTime, filePath, dbJsonList.toString(), name, "", datas, testResult, testPlanId);
        System.out.println("resultJson:" + resultJson);
        return success(userRecordEntity.getId(), "完成");

    }

    private UserRecordEntity testRecord(String flag, String phone, String institutionNo, String testTime, String fileName, String testResult, String name, String b64Img, String datas, String testResults, String testPlanId) {
        //根据taskCode记录测试数
        this.cognitiveTaskService.addTestNum(flag);
        //添加用户测试记录
        UserRecordEntity userRecordEntity = new UserRecordEntity();
        userRecordEntity.setFlag(flag);
        userRecordEntity.setPhone(phone);
        userRecordEntity.setInstitutionNo(institutionNo);
        userRecordEntity.setTestDate(testTime);
        userRecordEntity.setTestResult(testResult);
        userRecordEntity.setType("1");
        userRecordEntity.setFileName(fileName);
        userRecordEntity.setName(name);
        userRecordEntity.setImg(b64Img);
        userRecordEntity.setTestRecord(datas);
        userRecordEntity.setTestResults(testResults);
        if (testPlanId == null || testPlanId.equals("")) {
            userRecordEntity.setTestPlanId("0");
        } else {
            userRecordEntity.setTestPlanId(testPlanId);
        }
        this.userRecordService.save(userRecordEntity);
        return userRecordEntity;
    }


    /**
     * 查询后续测试是否可用
     *
     * @return
     */
    @SafetyProcess
    @PostMapping("/getIfUsable")
    @ApiOperation(value = "查询后续测试是否可用")
    public Result getIfUsable(@RequestBody String json) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONObject.parseObject(data);
        System.out.println("----------------result-------------------");System.out.println(jsonObject);
        String phone = jsonObject.getString("phone");
        //根据phone获取用户进行中任务
        List<HearingTestEntity> hearingTestEntityList = this.hearingTestService.getHearingTestList(phone);
        // 创建返回的json对象
        JSONObject resultJson = new JSONObject(true);
        resultJson.put("hearingTestEntityList",hearingTestEntityList);
        resultJson.put("waitTime",0);
        if (hearingTestEntityList.size() > 0) {
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
            //当前时间
            Date endTime = df.parse(DateUtil.getNowTime("yyyyMMddHHmm"));
            //开始时间
            Date beginTime = df.parse(hearingTestEntityList.get(hearingTestEntityList.size()-1).getTestDate());
            //计算时间差---分钟
            int diff = DateUtil.getDistanceByUnit(beginTime, endTime, 2);
            if (hearingTestEntityList.get(hearingTestEntityList.size()-1).getRound().equals("3")){
                if (diff < 0 || diff >= 5) {
                    resultJson.put("hearingTestEntityList",hearingTestEntityList);
                    resultJson.put("waitTime",0);
                    return success(resultJson);
                } else {
                    int a = 5 - diff;
                    resultJson.put("hearingTestEntityList",hearingTestEntityList);
                    resultJson.put("waitTime",a);
                    return success(resultJson, "还未到时间");
                }
            }else if (hearingTestEntityList.get(hearingTestEntityList.size()-1).getRound().equals("4")){
                if (diff < 0 || diff >= 20) {
                    resultJson.put("hearingTestEntityList",hearingTestEntityList);
                    resultJson.put("waitTime",0);
                    return success(resultJson);
                } else {
                    int a = 20 - diff;
                    resultJson.put("hearingTestEntityList",hearingTestEntityList);
                    resultJson.put("waitTime",a);
                    return success(resultJson, "还未到时间");
                }
            }
        }
        return success(resultJson, "请先进行第一轮测试");
    }

    /**
     * 清除进行中任务
     *
     * @return
     */
    @SafetyProcess
    @OperationLogAnnotation
    @PostMapping("/clearHearing")
    @ApiOperation(value = "清除进行中任务")
    public Result clearHearing(@RequestBody String json) throws Exception {
        //public Result saveMemoryCheck(@RequestBody JSONObject jsonObject ) throws Exception {
        String data = AesEncryptUtils.decrypt(JSONObject.parseObject(json).getString("data"));
        JSONObject jsonObject = JSONObject.parseObject(data);
        String phone = jsonObject.getString("phone");
        //清除进行中任务
        this.hearingTestService.clearHearing(phone);
        return success();
    }
}
