package com.ruoyi.project.plant.controller;

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

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.plant.domain.TManageactivity;
import com.ruoyi.project.plant.service.ITManageactivityService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 管理活动抽查Controller
 *
 * @author ruoyi
 * @date 2020-11-25
 */
@RestController
@RequestMapping("/plant/manageactivity")
public class TManageactivityController extends BaseController
{
    @Autowired
    private ITManageactivityService tManageactivityService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询管理活动抽查列表
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:list')")
    @GetMapping("/list")
    public TableDataInfo list(TManageactivity tManageactivity)
    {
        startPage();
        List<TManageactivity> list = tManageactivityService.selectTManageactivityList(tManageactivity);
        return getDataTable(list);
    }

    /**
     * 导出管理活动抽查列表
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:export')")
    @Log(title = "管理活动抽查", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TManageactivity tManageactivity)
    {
        List<TManageactivity> list = tManageactivityService.selectTManageactivityList(tManageactivity);
        ExcelUtil<TManageactivity> util = new ExcelUtil<TManageactivity>(TManageactivity.class);
        return util.exportExcel(list, "manageactivity");
    }

    /**
     * 获取管理活动抽查详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tManageactivityService.selectTManageactivityById(id));
    }

    /**
     * 新增管理活动抽查
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:add')")
    @Log(title = "管理活动抽查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TManageactivity tManageactivity)
    {
        tManageactivity.setCreaterCode(getUserId().toString());
        return toAjax(tManageactivityService.insertTManageactivity(tManageactivity));
    }

    /**
     * 修改管理活动抽查
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:edit')")
    @Log(title = "管理活动抽查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TManageactivity tManageactivity)
    {
        tManageactivity.setUpdaterCode(getUserId().toString());
        tManageactivity.setUpdatedate(new Date());
        return toAjax(tManageactivityService.updateTManageactivity(tManageactivity));
    }

    /**
     * 删除管理活动抽查
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:remove')")
    @Log(title = "管理活动抽查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tManageactivityService.deleteTManageactivityByIds(ids));
    }

    /**
     * 批量导入管理活动抽查
     */
    @PreAuthorize("@ss.hasPermi('plant:manageactivity:add')")
    @Log(title = "管理活动抽查", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException
    {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow =new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TManageactivity> list = new ArrayList<TManageactivity>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TManageactivity entity = new TManageactivity();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        if (cellValue != ""){
                            entity.setSerialnumber(Long.parseLong(cellValue));//序号
                        }
                    } else if (j == 2) {
                        entity.setAclevel(cellValue);//等级
                    } else if (j == 3) {
                        entity.setActivity(cellValue);//管理活动
                    } else if (j == 4) {
                        entity.setRccode(cellValue);//RC代码
                    } else if (j == 5) {
                        entity.setProgfreq(cellValue);//程序定义频次
                    } else if (j == 6) {
                        entity.setSamplreq(cellValue);//抽检频次
                    } else if (j == 7) {
                        entity.setResponsible(cellValue);//抽检负责人
                    } else if (j == 8) {
                        if (cellValue != ""){
                            entity.setYear(Long.parseLong(cellValue));//年份
                        }
                    } else if (j == 9) {
                        entity.setJan(cellValue);//一月
                    } else if (j == 10) {
                        entity.setFeb(cellValue);//二月
                    } else if (j == 11) {
                        entity.setMar(cellValue);//三月
                    } else if (j == 12) {
                        entity.setApr(cellValue);//四月
                    } else if (j == 13) {
                        entity.setMay(cellValue);//五月
                    } else if (j == 14) {
                        entity.setJun(cellValue);//六月
                    } else if (j == 15) {
                        entity.setJul(cellValue);//七月
                    } else if (j == 16) {
                        entity.setAug(cellValue);//八月
                    } else if (j == 17) {
                        entity.setSep(cellValue);//九月
                    } else if (j == 18) {
                        entity.setOct(cellValue);//十月
                    } else if (j == 19) {
                        entity.setNov(cellValue);//十一月
                    } else if (j == 20) {
                        entity.setDec(cellValue);//十二月
                    } else if (j == 21) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 22) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TManageactivity t : list
        ) {
            failNum++;
            try {
                tManageactivityService.insertTManageactivity(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                failRow.add(failNum+1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" +String.valueOf(successNumber));
        logger.info("failNumber:" +String.valueOf(failNumber));
        logger.info("failRow:" +String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
