package com.ruoyi.project.shiftmgr.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.shiftmgr.domain.TShiftRoster;
import com.ruoyi.project.shiftmgr.service.ITShiftRosterService;
import com.ruoyi.project.training.bccnew.domain.TTsTrainer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 排班计划管理Controller
 *
 * @author ssy
 * @date 2024-08-19
 */
@RestController
@RequestMapping("/shiftmgr/roster")
public class TShiftRosterController extends BaseController {
    @Autowired
    private ITShiftRosterService tShiftRosterService;

    /**
     * 查询排班计划管理列表
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:list')")
    @GetMapping("/list")
    public TableDataInfo list(TShiftRoster tShiftRoster) {
        startPage();
        List<TShiftRoster> list = tShiftRosterService.selectTShiftRosterList(tShiftRoster);
        return getDataTable(list);
    }

    /**
     * 导出排班计划管理列表
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:export')")
    @Log(title = "排班计划管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TShiftRoster tShiftRoster) {
        List<TShiftRoster> list = tShiftRosterService.selectTShiftRosterList(tShiftRoster);
        ExcelUtil<TShiftRoster> util = new ExcelUtil<TShiftRoster>(TShiftRoster.class);
        return util.exportExcel(list, "roster");
    }

    /**
     * 获取排班计划管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tShiftRosterService.selectTShiftRosterById(id));
    }

    /**
     * 新增排班计划管理
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:add')")
    @Log(title = "排班计划管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TShiftRoster tShiftRoster) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(tShiftRoster.getShiftDate());
        tShiftRoster.setWeek((long) calendar.get(Calendar.DAY_OF_WEEK));
        return toAjax(tShiftRosterService.insertTShiftRoster(tShiftRoster));
    }

    /**
     * 修改排班计划管理
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:edit')")
    @Log(title = "排班计划管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TShiftRoster tShiftRoster) {
        return toAjax(tShiftRosterService.updateTShiftRoster(tShiftRoster));
    }

    /**
     * 删除排班计划管理
     */
    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:remove')")
    @Log(title = "排班计划管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tShiftRosterService.deleteTShiftRosterByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('shiftmgr:roster:add')")
    @Log(title = "排班计划管理导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TShiftRoster> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TShiftRoster entity = new TShiftRoster();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setShiftDate(DateUtils.parseDate(cellValue));
                    } else if (j == 1) {
                        entity.setVacation("是".equals(cellValue) ? 1L : 0L);
                    } else if (j == 2) {
                        entity.setDclass(cellValue);
                    } else if (j == 3) {
                        entity.setNclass(cellValue);
                    }
                }
                entity.setCreaterCode(getUserId());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TShiftRoster t : list
        ) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + successNumber);
        logger.info("failNumber:" + failNumber);
        logger.info("failRow:" + failRow);
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
