package com.zehong.web.controller.train;

import com.alibaba.fastjson.JSONObject;
import com.zehong.common.annotation.Log;
import com.zehong.common.core.controller.BaseController;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.core.page.TableDataInfo;
import com.zehong.common.enums.BusinessType;
import com.zehong.common.exception.CustomException;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.poi.ExcelUtil;
import com.zehong.system.domain.train.TBankSubject;
import com.zehong.system.service.train.ITBankSubjectService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 题目Controller
 *
 * @author zehong
 * @date 2022-12-15
 */
@RestController
@RequestMapping("/train/subject")
public class TBankSubjectController extends BaseController
{
    @Autowired
    private ITBankSubjectService tBankSubjectService;

    /**
     * 查询题库题目列表
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:list')")
    @GetMapping("/list")
    public TableDataInfo list(TBankSubject tBankSubject)
    {
        startPage();
        List<TBankSubject> list = tBankSubjectService.selectTBankSubjectList(tBankSubject);
        return getDataTable(list);
    }

    /**
     * 导出题库题目列表
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:export')")
    @Log(title = "题库题目", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TBankSubject tBankSubject)
    {
        List<TBankSubject> list = tBankSubjectService.selectTBankSubjectList(tBankSubject);
        ExcelUtil<TBankSubject> util = new ExcelUtil<TBankSubject>(TBankSubject.class);
        return util.exportExcel(list, "题库题目数据");
    }

    /**
     * 获取题库题目详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:query')")
    @GetMapping(value = "/{subjectId}")
    public AjaxResult getInfo(@PathVariable("subjectId") Long subjectId)
    {
        return AjaxResult.success(tBankSubjectService.selectTBankSubjectById(subjectId));
    }

    /**
     * 新增题库题目
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:add')")
    @Log(title = "题库题目", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TBankSubject tBankSubject)
    {
        return toAjax(tBankSubjectService.insertTBankSubject(tBankSubject));
    }

    /**
     * 修改题库题目
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:edit')")
    @Log(title = "题库题目", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TBankSubject tBankSubject)
    {
        return toAjax(tBankSubjectService.updateTBankSubject(tBankSubject));
    }

    /**
     * 删除题库题目
     */
    //@PreAuthorize("@ss.hasPermi('system:subject:remove')")
    @Log(title = "题库题目", businessType = BusinessType.DELETE)
	@DeleteMapping("/{subjectIds}")
    public AjaxResult remove(@PathVariable Long[] subjectIds)
    {
        return toAjax(tBankSubjectService.deleteTBankSubjectByIds(subjectIds));
    }

    /**
     * 导入题目信息管理列表
     */
    @Log(title = "题库题目", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importDevice(MultipartFile file, boolean updateSupport, Long bankId) throws Exception
    {
        //装载流
        XSSFWorkbook workbook = null;
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        try {
//            workbook = new XSSFWorkbook(file.getInputStream());
            //解析xls
            workbook = new XSSFWorkbook(file.getInputStream());
        }catch (IOException e) {
            e.printStackTrace();
        }
        //最终添加数据 存储数组
        List<TBankSubject> list = new ArrayList<>();
        // 获取一个工作表，下标从0开始
        XSSFSheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        // 通过循环，逐行取出表中每行数据
        for(int i=0;i<=lastRowNum;i++){//跳过第一行和第二行
            if(i<=1){
                continue;
            }
            // 获取行
            XSSFRow row = sheet.getRow(i);
            TBankSubject excelEntity = new TBankSubject();
            List jsonArray=new ArrayList();
            try{
                //判断题目 和答案不能为空
                if (!StringUtils.isEmpty(row.getCell(0).toString())&&!StringUtils.isEmpty(row.getCell(9).toString())
                        &&!StringUtils.isEmpty(row.getCell(10).toString())){
                    successNum++;
                    /**题库id*/
                    excelEntity.setBankId(bankId);
                    /**题目*/
                    excelEntity.setTopicTitle(row.getCell(0).toString());

                    String  s1= row.getCell(10).toString();
                    String s2 = StringUtils.substringBefore(s1, ".");

                    /**题目类型*/
                    excelEntity.setTopicType(Integer.valueOf(s2));
                    /**题目*/
                    for (int s=1;s<=8;s++){
                        JSONObject jsonObject=new JSONObject();
                        if (!StringUtils.isEmpty(row.getCell(s).toString())) {
                            jsonObject.put("value", row.getCell(s).toString());
                            jsonArray.add(jsonObject);
                        }
                    }
                    System.out.println(row.getCell(9).toString());
                    /**答案*/
                    excelEntity.setAnswer((row.getCell(9).toString()).replace("，",",") );

//                    if ("A".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(0);
//                    }else if ("B".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(1);
//                    }else if ("C".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(2);
//                    }else if ("D".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(3);
//                    }else if ("E".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(4);
//                    }else if ("F".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(5);
//                    }else if ("G".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(6);
//                    }else if ("H".equals(row.getCell(9).toString())){
//                        excelEntity.setAnswer(7);
//                    }
                    excelEntity.setTopicOption(String.valueOf(jsonArray));
                    excelEntity.setDatetime(new Date());
                    list.add(excelEntity);
                }
//                else {
//                    failureNum++;
//                    String msg = "<br/>" + failureNum + "、题目 " + excelEntity.getTopicOption() + " 导入失败：";
//                    failureMsg.append(msg);
//                }
            }
            catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "题目 " + excelEntity.getTopicOption()  + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "导入完成，共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "数据已全部导入成功！共 " + successNum + " 条");
        }
        if (list.size()!=0){
            /**数据添加方法*/
            tBankSubjectService.insertBank(list);
        }
//        String message = tBankSubjectService.importDevice(file, updateSupport);
        return AjaxResult.success(successMsg.toString());
    }
}
