package com.ruoyi.project.apply.controller;

import com.alibaba.fastjson.JSON;
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.interceptor.annotation.RepeatSubmit;
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.apply.domain.TApplyLock;
import com.ruoyi.project.apply.domain.TApplyOfflinevalve;
import com.ruoyi.project.apply.domain.TApplySafetychange;
import com.ruoyi.project.apply.service.ITApplyLockService;
import com.ruoyi.project.apply.service.ITApplyOfflinevalveService;
import com.ruoyi.project.apply.service.ITApplySafetychangeService;
import com.ruoyi.project.pssr.domain.TPssrAboveall;
import com.ruoyi.project.pssr.domain.TPssrSubcontent;
import com.ruoyi.project.pssr.service.ITPssrAboveallService;
import com.ruoyi.project.pssr.service.ITPssrSubcontentService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.service.ISysDeptService;
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.util.*;

/**
 * 破锁管理Controller
 *
 * @author ruoyi
 * @date 2023-03-06
 */
@RestController
@RequestMapping("/apply/lock")
public class TApplyLockController extends BaseController {
    @Autowired
    private ITApplyLockService tApplyLockService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ITPssrAboveallService tPssrAboveallService;


    @Autowired
    private ITApplyOfflinevalveService tApplyOfflinevalveService;

    @Autowired
    private ITApplySafetychangeService tApplySafetychangeService;

    @GetMapping(value = "/getInfoByLock/{lockNo}")
    public AjaxResult getInfoByLock(@PathVariable("lockNo") String lockNo) {
        TApplyOfflinevalve lock = tApplyOfflinevalveService.selectTApplyOfflinevalveByLock(lockNo);
        TApplySafetychange lock1 = tApplySafetychangeService.selectTApplySafetychangeByLock(lockNo);
        Map<String, Object> map = new HashMap<>();
        if (lock != null) {
            map.put("type", 1);
            map.put("data", lock);
        } else if (lock1 != null) {
            map.put("type", 2);
            map.put("data", lock1);
        } else {
            map.put("type", 3);
        }
        return AjaxResult.success(map);
    }

    /**
     * 查询破锁管理列表
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApplyLock tApplyLock) {
        startPage();
        List<TApplyLock> list = tApplyLockService.selectTApplyLockList(tApplyLock);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('apply:lock:list')")
    @GetMapping("/listLockBranch")
    public TableDataInfo listLockBranch(TApplyLock tApplyLock) {
        //查询所有锁数据
        startPage();
        List<TApplyLock> list = tApplyLockService.selectTApplyLockList(tApplyLock);
        List<List<TApplyLock>> result = new ArrayList<>();//行元素
        List<TApplyLock> item = new ArrayList<>();//列元素
        int count = 1;//列统计
        for (int i = 0; i < list.size(); i++) {
            item.add(list.get(i));//添加列
            if (count == 35) {//当列达到35个
                count = 0;
                result.add(item);//将所有列添加到行
                item = new ArrayList<>();
            } else if ((list.size() % 35) == (list.size() - i)) {//总数%35=它本身，即剩余锁个数不满35个时
                item = new ArrayList<>(list.subList(i, list.size()));//将剩下的所有锁添加到列
                for (int j = 0; j < (35 - (list.size() - i)); j++) {//填充空对象充满该行
                    item.add(new TApplyLock());
                }
                result.add(item);
                break;
            }
            count++;
        }
        return getDataTable(result);
    }

    @GetMapping("/listAllLock")
    public AjaxResult listAllLock(TApplyLock tApplyLock) {
        return AjaxResult.success(tApplyLockService.selectTApplyLockList(tApplyLock));
    }

    @GetMapping("/listLockPid")
    public AjaxResult listLockPid(TApplyLock tApplyLock) {
        if (tApplyLock.getSubId() != null) {
            TPssrSubcontent subcontent = tPssrSubcontentService.selectTPssrSubcontentById(tApplyLock.getSubId());
            TPssrAboveall aboveall = tPssrAboveallService.selectTPssrAboveallById(subcontent.getAboveallId());
            List<String> posts = null;
            List<String> units = new ArrayList<>();
            if (StringUtils.isNotEmpty(aboveall.getUnit())) {
                units.addAll(Arrays.asList(aboveall.getUnit().split(",")));
            } else {
                if (aboveall.getRegion().contains("裂解")) {
                    units.add("310");
                    units.add("320");
                    units.add("710");
                    units.add("720");
                    units.add("730");
                } else if (aboveall.getRegion().contains("压缩")) {
                    units.add("330");
                    units.add("610");
                } else if (aboveall.getRegion().contains("分离")) {
                    units.add("340");
                    units.add("350");
                    units.add("360");
                    units.add("380");
                }else if (aboveall.getRegion().contains("AEU")) {
                    units.add("410");
                    units.add("430");
                    units.add("440");
                    units.add("450");
                    units.add("460");
                    units.add("470");
                }else if (aboveall.getRegion().contains("PGU")) {
                    units.add("510");
                    units.add("520");
                    units.add("530");
                }
            }
//            if (aboveall.getIncludePublic() == 1) {
                posts = new ArrayList<>();
                posts.add("公共区域");
//            }
            tApplyLock.setPosts(posts);
            tApplyLock.setUnits(units);
        }
        return AjaxResult.success(tApplyLockService.selectTApplyLockPidList(tApplyLock));
    }

    /**
     * 导出破锁管理列表
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:export')")
    @Log(title = "破锁管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApplyLock tApplyLock) {
        List<TApplyLock> list = tApplyLockService.selectTApplyLockList(tApplyLock);
        ExcelUtil<TApplyLock> util = new ExcelUtil<TApplyLock>(TApplyLock.class);
        return util.exportExcel(list, "lock");
    }

    /**
     * 获取破锁管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tApplyLockService.selectTApplyLockById(id));
    }

    /**
     * 新增破锁管理
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:add')")
    @Log(title = "破锁管理", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody TApplyLock tApplyLock) {
        tApplyLock.setCreaterCode(getUserId().toString());
        tApplyLock.setCreatedate(new Date());
        return toAjax(tApplyLockService.insertTApplyLock(tApplyLock));
    }

    /**
     * 修改破锁管理
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:edit')")
    @Log(title = "破锁管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping
    public AjaxResult edit(@RequestBody TApplyLock tApplyLock) {
        return toAjax(tApplyLockService.updateTApplyLock(tApplyLock));
    }

    /**
     * 删除破锁管理
     */
    @PreAuthorize("@ss.hasPermi('apply:lock:remove')")
    @Log(title = "破锁管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApplyLockService.deleteTApplyLockByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('apply:lock: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<TApplyLock> list = new ArrayList<>();
        int rowNum = sheet.getPhysicalNumberOfRows();
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TApplyLock entity = new TApplyLock();
                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) {
                        entity.setUnit(cellValue.trim());
                    } else if (j == 1) {
                        entity.setLockPost(cellValue.trim());
                    } else if (j == 2) {
                        entity.setPidNo(cellValue.trim());
                    } else if (j == 3) {
                        entity.setLockCode(cellValue.trim());
                    } else if (j == 4) {
                        entity.setMedium(cellValue.trim());
                    } else if (j == 5) {
                        entity.setPosition(cellValue.trim());
                    } else if (j == 6) {
                        entity.setReason(cellValue.trim());
                    } else if (j == 7) {
                        entity.setTechnology(cellValue.trim());
                    } else if (j == 8) {
                        entity.setRiskLevel(cellValue.trim());
                    } else if (j == 9) {
                        entity.setLockSize(cellValue.trim());
                    } else if (j == 10) {
                        entity.setValveStatus(cellValue.trim());
                    } else if (j == 11) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }
                }
                entity.setCreaterCode(userId.toString());
                entity.setCreatedate(new Date());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                logger.error("Exception:{}", e.getMessage());
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TApplyLock t : list
        ) {
            failNum++;
            try {
                tApplyLockService.insertTApplyLock(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);
    }
}
