package com.xinyilu.web.controller.testItemScoreinfo;

import com.xinyilu.common.annotation.Log;
import com.xinyilu.common.constant.Constants;
import com.xinyilu.common.core.controller.BaseController;
import com.xinyilu.common.core.domain.AjaxResult;
import com.xinyilu.common.core.page.TableDataInfo;
import com.xinyilu.common.custominterface.Insert;
import com.xinyilu.common.custominterface.Update;
import com.xinyilu.common.enums.BusinessType;
import com.xinyilu.common.exception.ServiceException;
import com.xinyilu.common.utils.poi.ExcelUtil;
import com.xinyilu.system.domain.dto.ImportTestProjectScoresDTO;
import com.xinyilu.system.domain.dto.TestItemScoreInfoUpdateDTO;
import com.xinyilu.system.domain.vo.TestItemScoreinfoVO;
import com.xinyilu.system.service.testItemScoreinfo.ITestItemScoreService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * 个人成绩录入管理Controller
 *
 * @author xinyilu
 * @date 2022-08-04
 */
@RestController
@RequestMapping("/system/testItemScore")
public class TestItemScoreController extends BaseController {

    @Autowired
    private ITestItemScoreService testItemScoreService;

    /**
     * 查询个人成绩录入管理列表
     */
//    @PreAuthorize("@ss.hasPermi('system:testItemScore:list')")
    @GetMapping("/list")
    public TableDataInfo list(TestItemScoreinfoVO testItemScore) {
        return testItemScoreService.selectTestItemScoreList(testItemScore);
    }

    /**
     * 获取个人成绩录入管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:testItemScore:query')")
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(Long studentId, String batchCode) {
        if (Objects.isNull(studentId)) {
            return AjaxResult.error("学生id不能为空");
        }
        if (StringUtils.isBlank(batchCode)) {
            return AjaxResult.error("批次编号不能为空");
        }
        return testItemScoreService.selectTestItemScoreById(studentId, batchCode);
    }

    /**
     * 新增个人成绩录入管理
     */
    @PreAuthorize("@ss.hasPermi('system:testItemScore:add')")
    @Log(title = "个人成绩录入管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated(Insert.class) @RequestBody TestItemScoreInfoUpdateDTO testItemScore) {
        testItemScore.setCreateBy(getUsername());
        return testItemScoreService.insertTestItemScore(testItemScore);
    }


    /**
     * 修改个人成绩录入管理
     */
    @PreAuthorize("@ss.hasPermi('system:testItemScore:edit')")
    @Log(title = "个人成绩录入管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated(Update.class) @RequestBody TestItemScoreInfoUpdateDTO testItemScore) {
        testItemScore.setUpdateBy(getUsername());
        return testItemScoreService.updateTestItemScore(testItemScore);
    }


    /**
     * 逻辑删除个人成绩录入管理
     */
    @PreAuthorize("@ss.hasPermi('system:testItemScore:remove')")
    @Log(title = "个人成绩录入管理", businessType = BusinessType.UPDATE)
    @PostMapping("/deleteItemScore")
    public AjaxResult remove(Long studentId, String batchCode) {
        return toAjax(testItemScoreService.updateTestItemScoreByIds(studentId, batchCode));
    }

    /**
     * 获取个人成绩的信息
     *
     * @param studentId 学生id
     * @param batchId   批次id
     * @param batchCode 批次编号
     * @return com.xinyilu.common.core.domain.AjaxResult
     **/
    @GetMapping("/getAllTestItemScoreInfo")
    public AjaxResult getAllTestItemScoreInfo(Long studentId, Long batchId, String batchCode) {
        if (Objects.isNull(studentId)) {
            return AjaxResult.error("学生id不能为空");
        }
        if (Objects.isNull(batchId)) {
            return AjaxResult.error("批次id不能为空");
        }
        if (StringUtils.isBlank(batchCode)) {
            return AjaxResult.error("批次编号不能为空");
        }
        return testItemScoreService.getAllTestItemScoreInfo(studentId, batchId, batchCode);
    }


    /**
     * 根据学生的信息查询表中的信息自动匹配得分
     *
     * @param studentId   学生id
     * @param itemId      项目id
     * @param itemScore   项目成绩
     * @param hwfFraction 体重项目成绩
     * @return com.xinyilu.common.core.domain.AjaxResult
     **/
    @GetMapping("/getStudentFraction")
    public AjaxResult getStudentFraction(Long studentId, Long itemId, BigDecimal itemScore, BigDecimal hwfFraction) {
        if (Objects.isNull(studentId)) {
            return AjaxResult.error("学生id不能为空");
        }
        if (Objects.isNull(itemId)) {
            return AjaxResult.error("项目id不能为空");
        }
        return testItemScoreService.getStudentFraction(studentId, itemId, itemScore, hwfFraction);
    }

    /**
     * 导入个人成绩的信息
     */
    @Log(title = "导入个人成绩的信息", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        //判断excel里面是否有数据/文件格式
        if (Objects.isNull(file) || StringUtils.isBlank(file.getOriginalFilename())) {
            return AjaxResult.error("请选择所需要导入的文件！");
        }
        String fileName = file.getOriginalFilename();
        if (!fileName.endsWith(Constants.XLSX) && !fileName.endsWith(Constants.XLS)) {
            return AjaxResult.error("导入文件格式不正确，请导入xlsx或xls格式的文件！");
        }
        ExcelUtil<ImportTestProjectScoresDTO> util = new ExcelUtil<>(ImportTestProjectScoresDTO.class);
        List<ImportTestProjectScoresDTO> list = util.importExcel(file.getInputStream());
        return testItemScoreService.importData(list);
    }

    /**
     * 下载导入模板
     */
    @Log(title = "下载导入模板", businessType = BusinessType.IMPORT)
    @PostMapping("/downloadTemplate")
    public void download(@RequestParam(value = "fileType") String fileType, HttpServletResponse res) throws IOException {
        if (StringUtils.isBlank(fileType)) {
            throw new ServiceException("请选择文件类型！");
        }
        File file = null;
        if (fileType.equals(Constants.TEST_ITEM_SCORE_TEMPLATE)) {
            file = ResourceUtils.getFile("classpath:template/测试项目成绩导入模板.xlsx");
        }
        if (Objects.isNull(file)) {
            throw new ServiceException("下载导入模板文件失败，请联系管理员！");
        }
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Content-Disposition", "inline;filename=" + fileType + ".txt");
        res.setContentType("text/plain;UTF-8");
        ServletOutputStream os = res.getOutputStream();
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }
}
