package com.cpms.project.asset.controller;

import com.alibaba.fastjson2.JSON;
import com.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.core.page.TableDataInfo;
import com.cpms.common.enums.BusinessType;
import com.cpms.common.utils.file.ExcelUtils;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.project.asset.domain.TAssetBasedoc;
import com.cpms.project.asset.service.ITAssetBasedocService;
import com.cpms.project.file.domain.TFile;
import com.cpms.project.file.service.ITFileService;
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.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * 资产管理基础文档清单Controller
 *
 * @author admin
 * @date 2024-04-18
 */
@RestController
@RequestMapping("/asset/basedoc")
public class TAssetBasedocController extends BaseController {
    @Autowired
    private ITAssetBasedocService tAssetBasedocService;
    @Autowired
    private ITFileService tFileService;

    /**
     * 查询资产管理基础文档清单列表
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAssetBasedoc tAssetBasedoc) {
        startPage();
        List<TAssetBasedoc> list = tAssetBasedocService.selectTAssetBasedocList(tAssetBasedoc);
        TFile file = new TFile();
        file.setLinkName("basedoc");
        file.setType("1");
        list.forEach(item -> {
            file.setLinkId(item.getId());
            item.setFileNum(0L);
            List<TFile> tFiles = tFileService.selectTFileList(file);
            if (CollectionUtils.isNotEmpty(tFiles))
                item.setFileNum((long) tFiles.size());
        });
        return getDataTable(list);
    }

    /**
     * 导出资产管理基础文档清单列表
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:export')")
    @Log(title = "资产管理基础文档清单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TAssetBasedoc tAssetBasedoc) {
        List<TAssetBasedoc> list = tAssetBasedocService.selectTAssetBasedocList(tAssetBasedoc);
        ExcelUtil<TAssetBasedoc> util = new ExcelUtil<TAssetBasedoc>(TAssetBasedoc.class);
        util.exportExcel(response, list, "资产管理基础文档清单数据");
    }

    /**
     * 获取资产管理基础文档清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tAssetBasedocService.selectTAssetBasedocById(id));
    }

    /**
     * 新增资产管理基础文档清单
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:add')")
    @Log(title = "资产管理基础文档清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAssetBasedoc tAssetBasedoc) {
        tAssetBasedoc.setCreaterCode(getUserId().toString());
        tAssetBasedoc.setCreatedate(new Date());
        return toAjax(tAssetBasedocService.insertTAssetBasedoc(tAssetBasedoc));
    }

    /**
     * 修改资产管理基础文档清单
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:edit')")
    @Log(title = "资产管理基础文档清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAssetBasedoc tAssetBasedoc) {
        tAssetBasedoc.setUpdaterCode(getUserId().toString());
        tAssetBasedoc.setUpdatedate(new Date());
        return toAjax(tAssetBasedocService.updateTAssetBasedoc(tAssetBasedoc));
    }

    /**
     * 删除资产管理基础文档清单
     */
    @PreAuthorize("@ss.hasPermi('asset:basedoc:remove')")
    @Log(title = "资产管理基础文档清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tAssetBasedocService.deleteTAssetBasedocByIds(ids));
    }


    @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<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TAssetBasedoc> 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();
                TAssetBasedoc entity = new TAssetBasedoc();
                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);
                    switch (j) {
                        case 0:
                            entity.setType(cellValue);
                            break;
                        case 1:
                            entity.setDocName(cellValue);
                            break;
                        case 2:
                            entity.setDocStatus(cellValue);
                            break;
                        case 3:
                            entity.setRemarks(cellValue);
                            break;
                    }
                }
                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 (TAssetBasedoc 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);
    }
}
