package com.cpms.project.process.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.cpms.common.utils.DateUtils;
import com.cpms.common.utils.file.ExcelUtils;
import org.apache.commons.collections4.CollectionUtils;
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.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.enums.BusinessType;
import com.cpms.project.process.domain.TMoc;
import com.cpms.project.process.service.ITMocService;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * MOC清单Controller
 * 
 * @author admin
 * @date 2024-04-08
 */
@RestController
@RequestMapping("/moc/moc")
public class TMocController extends BaseController
{
    @Autowired
    private ITMocService tMocService;

    /**
     * 查询MOC清单列表
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TMoc tMoc)
    {
        startPage();
        List<TMoc> list = tMocService.selectTMocList(tMoc);
        return getDataTable(list);
    }

    /**
     * 导出MOC清单列表
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:export')")
    @Log(title = "MOC清单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TMoc tMoc)
    {
        List<TMoc> list = tMocService.selectTMocList(tMoc);
        ExcelUtil<TMoc> util = new ExcelUtil<TMoc>(TMoc.class);
        util.exportExcel(response, list, "MOC清单数据");
    }

    /**
     * 获取MOC清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tMocService.selectTMocById(id));
    }

    /**
     * 新增MOC清单
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:add')")
    @Log(title = "MOC清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMoc tMoc) throws Exception {
        TMoc moc = new TMoc();
        moc.setMocNo(tMoc.getMocNo());
        List<TMoc> tMocs = tMocService.selectTMocList(moc);
        if(CollectionUtils.isNotEmpty(tMocs)){
            throw new Exception("已存在相同的MOC No.！");
        }
        return toAjax(tMocService.insertTMoc(tMoc));
    }

    /**
     * 修改MOC清单
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:edit')")
    @Log(title = "MOC清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMoc tMoc)
    {
        return toAjax(tMocService.updateTMoc(tMoc));
    }

    /**
     * 删除MOC清单
     */
    @PreAuthorize("@ss.hasPermi('moc:moc:remove')")
    @Log(title = "MOC清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tMocService.deleteTMocByIds(ids));
    }


    @Log(title = "MOC清单批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TMoc> list = new ArrayList<>();
        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();
                TMoc entity = new TMoc();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    // TODO 添加属性值
                    if (j==0){
                        entity.setMocNo(cellValue);
                    } else if (j==1) {
                        entity.setMocOwner(cellValue);
                    } else if (j==2) {
                        entity.setChangeName(cellValue);
                    } else if (j==3) {
                        entity.settOrP(cellValue);
                    } else if (j==4) {
                        entity.setIssueDate(DateUtils.parseDate(cellValue));
                    } else if (j==5) {
                        entity.setEmocStatus(cellValue);
                    } else if (j==6) {
                        entity.setPriority(cellValue);
                    } else if (j==7) {
                        entity.setRemarks(cellValue);
                    }
                }
                entity.setCreaterCode(String.valueOf(userId));
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TMoc t : list
        ) {
            failNum++;
            try {
                //根据使用证、注册编号、位号，进行数据更新
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                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);
    }
}
