package com.ruoyi.project.production.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.production.controller.vo.SaiExportVO;
import com.ruoyi.project.production.controller.vo.SaiQueryVO;
import com.ruoyi.project.production.domain.TSaiCategory;
import com.ruoyi.project.production.service.ITSaiCategoryService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.mapper.SysDeptMapper;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ISysUserService;
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.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.production.domain.TSai;
import com.ruoyi.project.production.service.ITSaiService;
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;

/**
 * SAI信息Controller
 *
 * @author ruoyi
 * @date 2023-03-08
 */
@RestController
@RequestMapping("/production/sai")
public class TSaiController extends BaseController
{
    @Autowired
    private ITSaiService tSaiService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private ITSaiCategoryService saiCategoryService;

    @Autowired
    private ITStaffmgrService staffmgrService;

    /**
     * 计算CTS扣分 / 装置人均扣分
     */
    @PreAuthorize("@ss.hasPermi('production:sai:query')")
    @GetMapping(value = "/calcScore2ByYear/{saiYear}")
    public AjaxResult calcScore2ByYear(@PathVariable("saiYear") int saiYear)
    {
        String score = "未知";
        String score2 = "未知";
        SaiQueryVO tSai = new SaiQueryVO();
        tSai.setSaiYear(saiYear);
        List<TSai> tSais = tSaiService.selectTSaiListByYear(tSai);
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal sum2 = BigDecimal.ZERO;
        BigDecimal avg = BigDecimal.ZERO;
        BigDecimal avg2 = BigDecimal.ZERO;
        for (TSai sai : tSais) {
            if (sai.getSource().equals("装置") || sai.getSource().equals("督导")) {
                Long saiLevel = sai.getSaiLevel();
                if (saiLevel != null) {
                    if (saiLevel == 1L) {
                        sum = sum.add(new BigDecimal("1"));
                    }
                    if (saiLevel == 2L) {
                        sum = sum.add(new BigDecimal("2"));
                    }
                    if (saiLevel == 3L) {
                        sum = sum.add(new BigDecimal("3"));
                    }
                }
            }
            if (sai.getSource().equals("CTS")) {
                Long saiLevel = sai.getSaiLevel();
                if (saiLevel != null) {
                    if (saiLevel == 1L) {
                        sum = sum.add(new BigDecimal("1"));
                    }
                    if (saiLevel == 2L) {
                        sum = sum.add(new BigDecimal("2"));
                    }
                    if (saiLevel == 3L) {
                        sum = sum.add(new BigDecimal("3"));
                    }
                }
            }
        }
        TStaffmgr staffmgr = new TStaffmgr();
        staffmgr.setDeptId(103L);
        List<TStaffmgr> tStaffmgrs = staffmgrService.selectTStaffmgrList(staffmgr);
        int num = tStaffmgrs.size();
        if (sum.compareTo(BigDecimal.ZERO) != 0 && num != 0 && sum2.compareTo(BigDecimal.ZERO) != 0) {
            avg = sum.divide(new BigDecimal(num), 3, RoundingMode.HALF_UP);
            avg2 = sum2.divide(avg, 2, RoundingMode.HALF_UP);
            score2 = avg2.toString();
        }
        return AjaxResult.success(score2);
    }

    /**
     * 计算当年装置自查人均扣分
     */
    @PreAuthorize("@ss.hasPermi('production:sai:query')")
    @GetMapping(value = "/calcScoreByYear/{saiYear}")
    public AjaxResult calcScoreByYear(@PathVariable("saiYear") int saiYear)
    {
        String score = "未知";
        SaiQueryVO tSai = new SaiQueryVO();
        tSai.setSaiYear(saiYear);
        List<TSai> tSais = tSaiService.selectTSaiListByYear(tSai);
        BigDecimal sum = BigDecimal.ZERO;
        BigDecimal avg = BigDecimal.ZERO;
        for (TSai sai : tSais) {
            if (sai.getSource().equals("装置") || sai.getSource().equals("督导")) {
                Long saiLevel = sai.getSaiLevel();
                if (saiLevel != null) {
                    if (saiLevel == 1L) {
                        sum = sum.add(new BigDecimal("1"));
                    }
                    if (saiLevel == 2L) {
                        sum = sum.add(new BigDecimal("2"));
                    }
                    if (saiLevel == 3L) {
                        sum = sum.add(new BigDecimal("3"));
                    }
                }
            }
        }
        TStaffmgr staffmgr = new TStaffmgr();
        staffmgr.setDeptId(103L);
        List<TStaffmgr> tStaffmgrs = staffmgrService.selectTStaffmgrList(staffmgr);
        int num = tStaffmgrs.size();
        if (sum.compareTo(BigDecimal.ZERO) != 0 && num != 0) {
            avg = sum.divide(new BigDecimal(num), 2, RoundingMode.HALF_UP);
            score = avg.toString();
        }
        return AjaxResult.success(score);
    }

    /**
     * 查询SAI信息列表
     */
    @PreAuthorize("@ss.hasPermi('production:sai:list')")
    @GetMapping("/listByYear")
    public TableDataInfo listYear(SaiQueryVO tSai)
    {
        startPage();
        List<TSai> list = tSaiService.selectTSaiListByYear(tSai);
        return getDataTable(list);
    }

    /**
     * 查询SAI信息列表
     */
    @PreAuthorize("@ss.hasPermi('production:sai:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSai tSai)
    {
        startPage();
        List<TSai> list = tSaiService.selectTSaiList(tSai);
        return getDataTable(list);
    }

    /**
     * 批量导入SAI信息列表
     */
    @PreAuthorize("@ss.hasPermi('production:sai:add')")
    @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<TSai> list = new ArrayList<TSai>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
//        List<SysDictData> tempStateDict = iSysDictTypeService.selectDictDataByType("TEMP_STATE");
        //部门查询
        List<SysDept> sysDeptList = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSai entity = new TSai();
                entity.setDelFlag("0");
                entity.setDeptId(userService.selectUserById(userId).getDeptId());
                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 (SysDept sysDept : sysDeptList) {
                            if (sysDept.getDeptName().equals(cellValue)) {
                                entity.setPlantId(sysDept.getDeptId().toString());
                            }
                        }
                    } else if (j == 1) {
                        if (cellValue.length() > 3) {
                            entity.setInspectionDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                        }
                    } else if (j == 2) {
                        entity.setDificiency(cellValue);
                    } else if (j == 3) {
                        entity.setSaiLevel(Long.parseLong(cellValue));
                    } else if (j == 4) {
                        entity.setCategory(cellValue);
                    } else if (j == 5) {
                        entity.setActions(cellValue);
                    } else if (j == 6) {
                        for (SysDept sysDept : sysDeptList) {
                            if (sysDept.getDeptName().equals(cellValue)) {
                                entity.setUserDept(sysDept.getDeptId().toString());
                            }
                        }
                    } else if (j == 7) {
                        entity.setSource(cellValue);
                    }
                }
                entity.setCreateBy(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TSai t : list
        ) {
            failNum++;
            try {
                tSaiService.insertTSai(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                logger.info("e:" + e);
                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);
    }

    /**
     * 导出SAI信息列表
     */
    @PreAuthorize("@ss.hasPermi('production:sai:export')")
    @Log(title = "SAI信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSai tSai)
    {
        List<TSai> list = tSaiService.selectTSaiList(tSai);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(new SysDept());
        List<TSaiCategory> saiCategories = saiCategoryService.selectTSaiCategoryList(null);
        for (TSai sai : list) {
            for (SysDept sysDept : sysDepts) {
                if (sysDept.getDeptId().toString().equals(sai.getPlantId())) {
                    sai.setPlantName(sysDept.getDeptName());
                }
                if (sysDept.getDeptId().toString().equals(sai.getUserDept())) {
                    sai.setUserDeptName(sysDept.getDeptName());
                }
                String applicant = sai.getApplicant();
                if (applicant != null) {
                    sai.setApplicantName(userService.selectUserById(Long.parseLong(applicant)).getNickName());
                }
            }
        }
        List<SaiExportVO> saiExportVOList = new ArrayList<SaiExportVO>();
        for (int i = 0; i < list.size(); i++) {
            TSai entity = list.get(i);
            SaiExportVO saiExportVO = new SaiExportVO();
            saiExportVO.setNo((i + 1) + "");
            saiExportVO.setInspectionDate(entity.getInspectionDate());
            saiExportVO.setDificiency(entity.getDificiency());
            saiExportVO.setActions(entity.getActions());
            saiExportVO.setSaiLevel(entity.getSaiLevel());
            if (entity.getCategory() != null) {
                for (TSaiCategory saiCategory : saiCategories) {
                    if ((saiCategory.getSaiCategoryId() + "").equals(entity.getCategory())) {
                        saiExportVO.setCategory(saiCategory.getSaiCategoryName());
                    }
                }
            }
            saiExportVO.setApplicant(entity.getApplicantName());
            saiExportVOList.add(saiExportVO);
        }
        ExcelUtil<SaiExportVO> util = new ExcelUtil<SaiExportVO>(SaiExportVO.class);
        return util.exportExcel(saiExportVOList, "SAI检查数据");
    }

    /**
     * 获取SAI信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:sai:query')")
    @GetMapping(value = "/{saiId}")
    public AjaxResult getInfo(@PathVariable("saiId") Long saiId)
    {
        return AjaxResult.success(tSaiService.selectTSaiById(saiId));
    }

    /**
     * 新增SAI信息
     */
    @PreAuthorize("@ss.hasPermi('production:sai:add')")
    @Log(title = "SAI信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSai tSai)
    {
        Long saiApplyId = tSai.getSaiApplyId();
        if (saiApplyId != null) {
            TSai sai = new TSai();
            sai.setSaiApplyId(saiApplyId);
            List<TSai> tSais = tSaiService.selectTSaiList(sai);
            if (tSais.size() != 0) {
                tSai.setSaiId(tSais.get(0).getSaiId());
                return toAjax(tSaiService.updateTSai(tSai));
            } else {
                return toAjax(tSaiService.insertTSai(tSai));
            }
        } else {
            return toAjax(tSaiService.insertTSai(tSai));
        }
    }

    /**
     * 修改SAI信息
     */
    @PreAuthorize("@ss.hasPermi('production:sai:edit')")
    @Log(title = "SAI信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSai tSai)
    {
        return toAjax(tSaiService.updateTSai(tSai));
    }

    /**
     * 删除SAI信息
     */
    @PreAuthorize("@ss.hasPermi('production:sai:remove')")
    @Log(title = "SAI信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{saiIds}")
    public AjaxResult remove(@PathVariable Long[] saiIds)
    {
        return toAjax(tSaiService.deleteTSaiByIds(saiIds));
    }
}
