package com.rf.psychological.module.imports;

import com.alibaba.fastjson.JSONObject;
import com.rf.psychological.base.rest.BaseController;
import com.rf.psychological.dao.model.DimensionEntity;
import com.rf.psychological.scale.dao.model.SubjectEntity;
import com.rf.psychological.scale.dao.model.ScaleMarksEntity;
import com.rf.psychological.scale.service.DimensionService;
import com.rf.psychological.scale.service.ScaleConfigService;
import com.rf.psychological.scale.service.ScaleMarksService;
import com.rf.psychological.scale.service.SubjectService;
import com.rf.psychological.utils.ExcelUtil;
import com.rf.psychological.utils.Result;
import com.rf.psychological.utils.StringUtils;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lpf
 * @description: 量表评分规则导入
 * @date 2022/6/4 10:12
 */

@Slf4j
@Api(tags = "量表评分规则导入")
@RestController
@RequestMapping("/import")
public class ScaleRulesImport extends BaseController {

    @Autowired
    private SubjectService subjectService;

    @Autowired
    private ScaleMarksService scaleMarksService;

    @Autowired
    private ScaleConfigService scaleConfigService;

    @Autowired
    private DimensionService dimensionService;

    @ApiOperation(value = "excel多个维度批量导入")
    @PostMapping(value = "/marks/multi", headers = "content-type=multipart/form-data")
    @Transactional(rollbackFor = Exception.class)
    public Result Scl90ExcelImport(@RequestParam("file") List<MultipartFile> file) throws Exception {
        System.out.println(file.size());
        if (file.size() == 0) {
            return fail("文件为空");
        }

        JSONObject result = new JSONObject();
        ArrayList<String> resultFlag = new ArrayList<>();
        ArrayList<String> suffixError = new ArrayList<>();
        ArrayList<String> subjectNotFound = new ArrayList<>();
        ArrayList<String> havingInScaleMark = new ArrayList<>();
        //量表flag
        String scaleFlag = "";
        boolean flag = false;
        for (MultipartFile multipartFile : file) {
            String fileName = multipartFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (!suffix.equals("xlsx")) {
                suffixError.add(fileName);
                flag = true;
                continue;
            }
            //将文件名以.进行分割，.前面是量表名字
            String[] xlsxName = fileName.split("\\.");
            ////通过量表文件名查找信息
            //List<SubjectEntity> subjectByFileName = subjectService.getSubjectByFileName(fileName);
            ////判断等值查询是否存在量表信息
            //if (subjectByFileName.size() != 1) {
            //    subjectNotFound.add(fileName);
            //} else {
            //    if (this.checkScaleMarksByFlag(subjectByFileName, havingInScaleMark)) {
            //        continue;
            //    }
            //    scaleFlag = subjectByFileName.get(0).getFlag();
            //    resultFlag.add(scaleFlag);
            //}

            //通过量表名字查找
            List<SubjectEntity> subjectListByname = subjectService.getSubjectListByname(xlsxName[0], false);
            List<SubjectEntity> subjectListByLikeName = subjectService.getSubjectListByname(xlsxName[0], true);
            //判断等值查询是否存在量表信息
            if (subjectListByname.size() != 1) {
                //判断模糊like查询是否存在量表信息
                if (subjectListByLikeName.size() != 1) {
                    subjectNotFound.add(fileName);
                    flag = true;
                    continue;
                } else {
                    if (this.checkScaleMarksByFlag(subjectListByLikeName, havingInScaleMark)) {
                        continue;
                    }
                    scaleFlag = subjectListByLikeName.get(0).getFlag();
                    resultFlag.add(scaleFlag);
                }
            } else {
                if (this.checkScaleMarksByFlag(subjectListByname, havingInScaleMark)) {
                    continue;
                }
                scaleFlag = subjectListByname.get(0).getFlag();
                resultFlag.add(scaleFlag);
            }

            List<List<Object>> marks = ExcelUtil.getBankListByExcelForUserImport(multipartFile.getInputStream(), fileName);
            if (!importScaleMarksDataBase(marks, scaleFlag)) {
                return fail("导入失败，请联系管理员");
            }
            //将量表计算规则改为新的
            scaleConfigService.updateResultConfig(scaleFlag, "com.rf.psychological.scale.resultBusiness.scaleResult.NEWCOMMONScale");
            //将维度表中量表信息置为1
            updateDimensionIconInfoFlag(scaleFlag);
        }
        result.put("成功入库flag", resultFlag);
        result.put("后缀错误", suffixError);
        result.put("无法通过文件名查找flag", subjectNotFound);
        result.put("量表的维度评分信息已入库", havingInScaleMark);

        if (!flag) {
            return success(result, "入库成功");
        } else {
            return fail(result);
        }
    }


    @ApiOperation(value = "评分规则导入--单个量表导入")
    @PostMapping("/marks/scl90/{flag}")
    @Transactional(rollbackFor = Exception.class)
    public Result Scl90ExcelImport(@PathVariable String flag, MultipartFile file) throws Exception {
        if (file == null) {
            return fail("文件为空");
        }
        if (flag == null) {
            return fail("所属量表标识为空");
        }
        List<ScaleMarksEntity> scaleMarksByFlag = scaleMarksService.getScaleMarksByFlag(flag);
        if (scaleMarksByFlag.size() != 0) {
            return fail("该量表的维度评分信息已入库，请联系管理员");
        }
        String filePath = "";//用户信息上传之后生成的用户名密码文件保存路径
        String fileName = file.getOriginalFilename();
        List<List<Object>> marks = ExcelUtil.getBankListByExcelForUserImport(file.getInputStream(), fileName);
        if (!importScaleMarksDataBase(marks, flag)) {
            return fail("导入失败，请联系管理员");
        }
        //将量表计算规则改为新的
        scaleConfigService.updateResultConfig(flag, "com.rf.psychological.scale.resultBusiness.scaleResult.NEWCOMMONScale");
        //将维度表中量表信息置为1
        updateDimensionIconInfoFlag(flag);
        return success("入库成功");
    }

    //检查评分规则表中是否已经有该量表信息
    private boolean checkScaleMarksByFlag(List<SubjectEntity> subjectList, ArrayList<String> havingInScaleMark) {
        scaleMarksService.deleteScaleMarkByFlag(subjectList.get(0).getFlag());
        List<ScaleMarksEntity> scaleMarksByFlag = scaleMarksService.getScaleMarksByFlag(subjectList.get(0).getFlag());
        if (scaleMarksByFlag.size() != 0) {
            havingInScaleMark.add(subjectList.get(0).getFlag());
            return true;
        }
        return false;
    }

    private boolean importScaleMarksDataBase(List<List<Object>> marks, String flag) {
        try {
            for (List<Object> mark : marks) {
                log.info("excel每行信息：{}", mark);
                //因子（维度名称）	最低分（起始分）最高分(结束分) 常模参考值 标准差 结论（该分段症状）
                //因子解释 等级解释(该分段指导语） 建议 是否为总分结论
                //图表信息iconInfo isIconFlag
                ScaleMarksEntity tempUserDB = new ScaleMarksEntity();
                tempUserDB.setName(String.valueOf(mark.get(0)));
                tempUserDB.setScoreStart(String.valueOf(mark.get(1)));
                tempUserDB.setScoreEnd(String.valueOf(mark.get(2)));
                if (("").equals(String.valueOf(mark.get(3)))) {
                    tempUserDB.setReference("无");
                } else {
                    tempUserDB.setReference(String.valueOf(mark.get(3)));
                }
                //如果常模参考值为无则标准差也是无
                if (("无").equals(tempUserDB.getReference())) {
                    tempUserDB.setStandardDeviation("无");
                    tempUserDB.setSymptom(String.valueOf(mark.get(4)));
                    tempUserDB.setNameExplain(String.valueOf(mark.get(5)));
                    tempUserDB.setImprovementSuggestions(String.valueOf(mark.get(6)));
                    tempUserDB.setSuggestion(String.valueOf(mark.get(7)));
                    tempUserDB.setIsTotalScoreExplain(String.valueOf(mark.get(8)));
                } else {
                    //如果常模参考值有给且也有标准差，则标准差是由excel表格确定
                    if (StringUtils.isNumber(String.valueOf(mark.get(4)))) {
                        tempUserDB.setStandardDeviation(String.valueOf(mark.get(4)));
                        tempUserDB.setSymptom(String.valueOf(mark.get(5)));
                        tempUserDB.setNameExplain(String.valueOf(mark.get(6)));
                        tempUserDB.setImprovementSuggestions(String.valueOf(mark.get(7)));
                        tempUserDB.setSuggestion(String.valueOf(mark.get(8)));
                        tempUserDB.setIsTotalScoreExplain(String.valueOf(mark.get(9)));
                    } else {
                        //如果常模参考值有给但是excel没有给标准差，则标准差是无
                        tempUserDB.setStandardDeviation("无");
                        tempUserDB.setSymptom(String.valueOf(mark.get(4)));
                        tempUserDB.setNameExplain(String.valueOf(mark.get(5)));
                        tempUserDB.setImprovementSuggestions(String.valueOf(mark.get(6)));
                        tempUserDB.setSuggestion(String.valueOf(mark.get(7)));
                        tempUserDB.setIsTotalScoreExplain(String.valueOf(mark.get(8)));
                    }

                }

                tempUserDB.setFlag(flag);
                System.out.println(tempUserDB.toString());
                this.scaleMarksService.saveScaleMarks(tempUserDB);
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return false;
        }
        return true;
    }

    private boolean updateDimensionIconInfoFlag(String flag) {
        List<DimensionEntity> dimensionByFlag = dimensionService.getDimensionByFlag(flag);
        if (!CollectionUtils.isEmpty(dimensionByFlag)) {
            //维度表有3个维度以上才可以进行改变
            if (dimensionByFlag.size() > 2) {
                for (DimensionEntity dimensionEntity : dimensionByFlag) {
                    dimensionEntity.setIsIconFlag("1");
                    dimensionService.saveDimension(dimensionEntity);
                }
            }

        }
        return true;
    }


}
