package com.fs.course.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.fs.common.annotation.Log;
import com.fs.common.core.controller.BaseController;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.model.LoginUser;
import com.fs.common.core.page.TableDataInfo;
import com.fs.common.enums.BusinessType;
import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.poi.ExcelUtil;
import com.fs.course.config.CourseConfig;
import com.fs.course.domain.FsCourseQuestionBank;
import com.fs.course.dto.FsCourseQuestionBankImportDTO;
import com.fs.course.dto.ImportResultDTO;
import com.fs.course.service.IFsCourseQuestionBankService;
import com.fs.framework.web.service.TokenService;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 题库Controller
 *
 * @author fs
 * @date 2024-09-07
 */
@RestController
@RequestMapping("/course/courseQuestionBank")
public class FsCourseQuestionBankController extends BaseController
{
    @Autowired
    private IFsCourseQuestionBankService fsCourseQuestionBankService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysConfigService configService;
    /**
     * 查询题库列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsCourseQuestionBank fsCourseQuestionBank)
    {
        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsCourseQuestionBank.setUserId(userId);
        }
        List<FsCourseQuestionBank> list = fsCourseQuestionBankService.selectFsCourseQuestionBankList(fsCourseQuestionBank);
        return getDataTable(list);
    }

    /**
     * 导出题库列表
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:export')")
    @Log(title = "题库", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(FsCourseQuestionBank fsCourseQuestionBank)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsCourseQuestionBank.setUserId(userId);
        }

        List<FsCourseQuestionBankImportDTO> list = fsCourseQuestionBankService.exportData(fsCourseQuestionBank);
        ExcelUtil<FsCourseQuestionBankImportDTO> util = new ExcelUtil<>(FsCourseQuestionBankImportDTO.class);
        return util.exportExcel(list, "题库数据");
    }

    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:exportFail')")
    @Log(title = "题库", businessType = BusinessType.EXPORT)
    @PostMapping("/exportFail")
    public AjaxResult export( @RequestBody List<FsCourseQuestionBankImportDTO> list)
    {
        ExcelUtil<FsCourseQuestionBankImportDTO> util = new ExcelUtil<>(FsCourseQuestionBankImportDTO.class);
        return util.exportExcel(list, "题库错误数据");
    }

    /**
     * 获取题库详细信息
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        FsCourseQuestionBank fsCourseQuestionBank = fsCourseQuestionBankService.selectFsCourseQuestionBankById(id);
        return AjaxResult.success(fsCourseQuestionBank);
    }

    /**
     * 新增题库
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:add')")
    @Log(title = "题库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCourseQuestionBank fsCourseQuestionBank)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        fsCourseQuestionBank.setCreateBy(loginUser.getUser().getNickName());
        Long userId = loginUser.getUser().getUserId();
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);
        if (ObjectUtil.isNotEmpty(config.getIsBound())&&config.getIsBound()){
            fsCourseQuestionBank.setUserId(userId);
        }

        return toAjax(fsCourseQuestionBankService.insertFsCourseQuestionBank(fsCourseQuestionBank));
    }

    /**
     * 修改题库
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:edit')")
    @Log(title = "题库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCourseQuestionBank fsCourseQuestionBank)
    {
        return toAjax(fsCourseQuestionBankService.updateFsCourseQuestionBank(fsCourseQuestionBank));
    }

    /**
     * 删除题库
     */
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:remove')")
    @Log(title = "题库", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(fsCourseQuestionBankService.deleteFsCourseQuestionBankByIds(ids));
    }

    //下载模板
    @GetMapping("/importTemplate")
    public AjaxResult importTemplate() {
        ExcelUtil<FsCourseQuestionBankImportDTO> util = new ExcelUtil<>(FsCourseQuestionBankImportDTO.class);
        return util.importTemplateExcel("课程题目数据");
    }

    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('course:courseQuestionBank:importData')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<FsCourseQuestionBankImportDTO> util = new ExcelUtil<>(FsCourseQuestionBankImportDTO.class);
        List<FsCourseQuestionBankImportDTO> list = util.importExcel(file.getInputStream());

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();

        // 读取配置
        String json = configService.selectConfigByKey("course.config");
        CourseConfig config = JSONUtil.toBean(json, CourseConfig.class);

        // 绑定状态控制 userId
        Long finalUserId = (ObjectUtil.isNotEmpty(config.getIsBound()) && config.getIsBound())
                ? userId
                : null;

        // 调用 service
        String result =
                fsCourseQuestionBankService.importData(list, loginUser.getUser().getNickName(), finalUserId);

        // 返回 message + failList
        Map<String, Object> resp = new HashMap<>();
        resp.put("message", result);
        resp.put("failList", list);

        return AjaxResult.success(resp);
    }

    @GetMapping(value = "/getByIds")
    public AjaxResult getByIds(@RequestParam List<Long> ids)
    {
        List<FsCourseQuestionBank> list = fsCourseQuestionBankService.selectFsCourseQuestionBankByIds(ids);
        return AjaxResult.success(list);
    }

}
