package com.ruoyi.project.reliability.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.DateUtils;
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.reliability.domain.TAssetlist;
import com.ruoyi.project.reliability.service.ITAssetlistService;
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-27
 */
@RestController
@RequestMapping("/reliability/assetlist")
public class TAssetlistController extends BaseController
{
    @Autowired
    private ITAssetlistService tAssetlistService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询资产清单列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAssetlist tAssetlist)
    {
        startPage();
        List<TAssetlist> list = tAssetlistService.selectTAssetlistList(tAssetlist);
        return getDataTable(list);
    }

    /**
     * 导出资产清单列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:export')")
    @Log(title = "资产清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TAssetlist tAssetlist)
    {
        List<TAssetlist> list = tAssetlistService.selectTAssetlistList(tAssetlist);
        ExcelUtil<TAssetlist> util = new ExcelUtil<TAssetlist>(TAssetlist.class);
        return util.exportExcel(list, "assetlist");
    }

    /**
     * 获取资产清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tAssetlistService.selectTAssetlistById(id));
    }

    /**
     * 新增资产清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:add')")
    @Log(title = "资产清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAssetlist tAssetlist)
    {
        tAssetlist.setCreaterCode(getUserId().toString());
        return toAjax(tAssetlistService.insertTAssetlist(tAssetlist));
    }

    /**
     * 修改资产清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:edit')")
    @Log(title = "资产清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAssetlist tAssetlist)
    {
        tAssetlist.setUpdaterCode(getUserId().toString());
        tAssetlist.setUpdatedate(new Date());
        return toAjax(tAssetlistService.updateTAssetlist(tAssetlist));
    }

    /**
     * 删除资产清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:assetlist:remove')")
    @Log(title = "资产清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tAssetlistService.deleteTAssetlistByIds(ids));
    }

    /**
     * 批量导入可靠性管理措施
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs: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<TAssetlist> list = new ArrayList<TAssetlist>();
        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();
                TAssetlist entity = new TAssetlist();
                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.setAssetclass(cellValue);//资产类别
                    } else if (j == 3) {
                        entity.setAssetno(cellValue);//资产编号
                    } else if (j == 4) {
                        entity.setAssetnoref(cellValue);//参考
                    } else if (j == 5) {
                        entity.setCostcenter(cellValue);//成本中心
                    } else if (j == 6) {
                        if (cellValue.length() > 3) {
                            entity.setCapitalizedon(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//资本化时间
                        }
                    } else if (j == 7) {
                        entity.setDescription(cellValue);//描述
                    } else if (j == 8) {
                        entity.setResponsible(cellValue);//责任人
                    } else if (j == 9) {
                        entity.setRoom(cellValue);//房间
                    } else if (j == 10) {
                        entity.setTagno(cellValue);//位号
                    } else if (j == 11) {
                        entity.setAssetresult(cellValue);//清查结果
                    } else if (j == 12) {
                        entity.setComments(cellValue);//说明事项
                    } else if (j == 13) {
                        entity.setCcmanager(cellValue);//经理
                    } else if (j == 14) {
                        entity.setBu(cellValue);//BU
                    } else if (j == 15) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 16) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }
                }
                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 (TAssetlist t : list
        ) {
            failNum++;
            try {
                tAssetlistService.insertTAssetlist(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);
    }
}
