package com.ruoyi.project.plant.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.document.DocumentHandler;
import com.ruoyi.common.utils.document.PDFTemplateUtil;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.domain.TTargetlist;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.plant.service.ITTargetlistService;
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 freemarker.template.Template;
import org.apache.commons.collections4.CollectionUtils;
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.plant.domain.TTargetreview;
import com.ruoyi.project.plant.service.ITTargetreviewService;
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;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 目标回顾Controller
 *
 * @author ruoyi
 * @date 2020-11-25
 */
@RestController
@RequestMapping("/plant/targetreview")
public class TTargetreviewController extends BaseController
{
    @Autowired
    private ITTargetreviewService tTargetreviewService;

    @Autowired
    private ITTargetlistService tTargetlistService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询目标回顾列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:list')")
    @GetMapping("/list")
    public TableDataInfo list(TTargetreview tTargetreview)
    {
        startPage();

        List<TTargetreview> list;
        if (tTargetreview.getYear()== null) {
            Calendar calendar = Calendar.getInstance();
            tTargetreview.setYear(Long.valueOf(calendar.get(Calendar.YEAR)));
            list = tTargetreviewService.selectTTargetreviewList(tTargetreview);
            if (CollectionUtils.isEmpty(list)){
                tTargetreview.setYear(Long.valueOf(calendar.get(Calendar.YEAR)-1));
                list = tTargetreviewService.selectTTargetreviewList(tTargetreview);
            }
        } else {
            list = tTargetreviewService.selectTTargetreviewList(tTargetreview);
        }
        for (TTargetreview t : list) {
            if (t.getPrincipal() != null) {
                String[] principal = t.getPrincipal().split(",");
                String name = "";
                for (int i = 0; i < principal.length; i++) {
                    TStaffmgr tStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(principal[i]);
                    if (i == 0) {
                        if (tStaffmgr!=null) {
                            name = tStaffmgr.getName();
                        }
                    }else {
                        name = name + "," + tStaffmgr.getName();
                    }
                }
                t.setPrincipalName(name);
            }
        }
        return getDataTable(list);
    }

    /**
     * 导出目标回顾列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:export')")
    @Log(title = "目标回顾", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTargetreview tTargetreview)
    {
        List<TTargetreview> list = tTargetreviewService.selectTTargetreviewList(tTargetreview);
        ExcelUtil<TTargetreview> util = new ExcelUtil<TTargetreview>(TTargetreview.class);
        return util.exportExcel(list, "targetreview");
    }

    /**
     * 获取目标回顾详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTargetreviewService.selectTTargetreviewById(id));
    }

    /**
     * 新增目标回顾
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:add')")
    @Log(title = "目标回顾", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTargetreview tTargetreview)
    {
        tTargetreview.setCreaterCode(getUserId().toString());
        return toAjax(tTargetreviewService.insertTTargetreview(tTargetreview));
    }

    /**
     * 修改目标回顾
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:edit')")
    @Log(title = "目标回顾", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTargetreview tTargetreview)
    {
        tTargetreview.setUpdaterCode(getUserId().toString());
        tTargetreview.setUpdatedate(new Date());
        return toAjax(tTargetreviewService.updateTTargetreview(tTargetreview));
    }

    /**
     * 删除目标回顾
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview:remove')")
    @Log(title = "目标回顾", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tTargetreviewService.deleteTTargetreviewByIds(ids));
    }

    /**
     * 批量导入目标回顾
     */
    @PreAuthorize("@ss.hasPermi('plant:targetreview: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<TTargetreview> list = new ArrayList<TTargetreview>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        for (int i = 1; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
            //    int cellNum = row.getLastCellNum();
                if(row==null){
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TTargetreview entity = new TTargetreview();
                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);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        entity.setItem(cellValue);//序号
                    } else if (j == 2) {
                        entity.setDescription(cellValue);//内容
                    } else if (j == 3) {
                        entity.setTargets(cellValue);//目标
                    } else if (j == 4) {
                        if (cellValue != "") {
                            entity.setYear(Long.parseLong(cellValue));//年度
                        }
                    } else if (j == 5) {
                        entity.setHalfyear(cellValue);//半年
                    } else if (j == 6) {
                        entity.setAnnual(cellValue);//全年
                    } else if (j == 7) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 8) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                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 (TTargetreview t : list
        ) {
            failNum++;
            try {
                tTargetreviewService.insertTTargetreview(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);
    }

    @RequestMapping("/exportPDF")
    public String exportPDF(@RequestParam String year, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out= null;
        try {
            out = response.getOutputStream();
            //获取信息，就是上面的结构
            HashMap<String, Object> map = new HashMap<>();
            DocumentHandler dh = new DocumentHandler();
            Template t = dh.getTemplate();
            TTargetlist targetlist = new TTargetlist();
            targetlist.setYear(year);
            targetlist.setParentId(Long.parseLong("0"));
            List<TTargetlist> tTargetlists = tTargetlistService.selectTTargetlistList(targetlist);
            for (TTargetlist list : tTargetlists) {

            }
            map.put("targetlists", tTargetlists);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            PDFTemplateUtil.exportPdf("measuresFMaker.ftl", year + "目标回顾.pdf","file:/"+ RuoYiConfig.getProfile(), map, response);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(out!=null)
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }
}
