package com.ruoyi.project.plant.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.plant.domain.TTargetreview;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.plant.service.ITTargetmeasuresService;
import com.ruoyi.project.plant.service.ITTargetreviewService;
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.commons.collections.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.TTargetlist;
import com.ruoyi.project.plant.service.ITTargetlistService;
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.annotation.Resource;

/**
 * 目标录入Controller
 *
 * @author ruoyi
 * @date 2020-11-24
 */
@RestController
@RequestMapping("/plant/targetlist")
public class TTargetlistController extends BaseController
{
    @Autowired
    private ITTargetlistService tTargetlistService;

    @Autowired
    private ITTargetreviewService tTargetreviewService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询目标录入列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:list')")
    @GetMapping("/list")
    public AjaxResult list(TTargetlist tTargetlist)
    {

        List<TTargetlist> list;
        if (StringUtils.isEmpty(tTargetlist.getYear())) {
            Calendar calendar = Calendar.getInstance();
            tTargetlist.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
            list = tTargetlistService.selectTTargetlistList(tTargetlist);
            if (CollectionUtils.isEmpty(list)) {
                tTargetlist.setYear(String.valueOf(calendar.get(Calendar.YEAR)-1));
                list = tTargetlistService.selectTTargetlistList(tTargetlist);
            }
        } else {
            list = tTargetlistService.selectTTargetlistList(tTargetlist);
        }
        return AjaxResult.success(list);
    }

    /**
     * 查询目标录入列表（目标措施）
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:list')")
    @GetMapping("/listMeasures")
    public TableDataInfo listMeasures(TTargetlist tTargetlist)
    {
        startPage();

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

    /**
     * 导出目标录入列表
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:export')")
    @Log(title = "目标录入", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TTargetlist tTargetlist)
    {
        List<TTargetlist> list = tTargetlistService.selectTTargetlistList(tTargetlist);
        ExcelUtil<TTargetlist> util = new ExcelUtil<TTargetlist>(TTargetlist.class);
        return util.exportExcel(list, "targetlist");
    }

    /**
     * 获取目标录入详细信息
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tTargetlistService.selectTTargetlistById(id));
    }

    /**
     * 新增目标录入
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:add')")
    @Log(title = "目标录入", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TTargetlist tTargetlist)
    {
        int doInsert = tTargetlistService.insertTTargetlist(tTargetlist);
        tTargetlist.setCreaterCode(getUserId().toString());
        if (tTargetlist.getParentId() != 0) {
            TTargetreview review = new TTargetreview();
            review.setListId(tTargetlist.getId());
            review.setDeptId(tTargetlist.getDeptId());
            tTargetreviewService.insertTTargetreview(review);
        }
        return toAjax(doInsert);
    }

    /**
     * 修改目标录入
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:edit')")
    @Log(title = "目标录入", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TTargetlist tTargetlist)
    {
        tTargetlist.setUpdaterCode(getUserId().toString());
        tTargetlist.setUpdatedate(new Date());
        return toAjax(tTargetlistService.updateTTargetlist(tTargetlist));
    }

    /**
     * 删除目标录入
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist:remove')")
    @Log(title = "目标录入", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long listId : ids) {
            tTargetreviewService.deleteTTargetreviewByListId(listId);
        }
        return toAjax(tTargetlistService.deleteTTargetlistByIds(ids));
    }

    /**
     * 批量导入目标录入
     */
    @PreAuthorize("@ss.hasPermi('plant:targetlist: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<TTargetlist> list = new ArrayList<TTargetlist>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> partners = iSysDictTypeService.selectDictDataByType("PARTNERS");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        int successNumber = 0;
        int failNum = 0;
        for (int i = 1; i < rowNum; i++) {
            //父菜单查询
            List<TTargetlist> tTargetlists = tTargetlistService.selectTTargetlistList(new TTargetlist());
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TTargetlist entity = new TTargetlist();
                String year = null;
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        //  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) {
                            entity.setItem(cellValue);//序号
                        } else if (j == 2) {
                            entity.setDescription(cellValue);//内容
                        } else if (j == 3) {
                            entity.setTargets(cellValue);//目标
                        } else if (j == 4) {
                            if (!cellValue.equals("")) {
                                entity.setYear(cellValue);//年度
                                year = cellValue;
                            }
                        } else if (j == 5) {
                            if (!cellValue.equals("")) {
                                for (TTargetlist t : tTargetlists) {
                                    if (t.getItem().equals(cellValue.trim()) && t.getYear().equals(year)) {
                                        entity.setParentId(t.getId());//父菜单ID
                                    }
                                }
                            } else {
                                entity.setParentId(Long.parseLong("0"));
                            }
                        } else if (j == 6) {
                            entity.setYardstick(cellValue);//判断标准
                        } else if (j == 7) {
                            String[] split = cellValue.split(",");
                            String partner = "";
                            for (String s : split) {
                                for (SysDictData p : partners) {
                                    if (p.getDictLabel().equals(s.trim())&&!partner.contains(s)) {
                                        partner += p.getDictValue() + ",";//合作者
                                        break;
                                    }
                                }
                            }
                            if (partner.length() > 0)
                                partner = partner.substring(0,partner.length()-1);
                            entity.setPartners(partner);
                        } else if (j == 8) {
                            for (SysDept d : dept) {
                                if (d.getDeptName().equals(cellValue.trim())) {
                                    entity.setDeptId(d.getDeptId());//部门编号
                                }
                            }
                        } else if (j == 9) {
                            entity.setRemarks(cellValue);//备注
                        }
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
                failNum++;
                try {
                    tTargetlistService.insertTTargetlist(entity);
                    entity.setCreaterCode(getUserId().toString());
                    if (entity.getParentId() != 0) {
                        TTargetreview review = new TTargetreview();
                        review.setListId(entity.getId());
                        review.setDeptId(entity.getDeptId());
                        tTargetreviewService.insertTTargetreview(review);
                    }
                    successNumber++;
                }catch (Exception e){
                    failNumber++;
                    failRow.add(failNum+1);
                }
            }catch (Exception e){
                failNumber++;
                failRow.add(i+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);
    }

    @GetMapping("/getAllContent")
    public AjaxResult getAllContent(TTargetlist tTargetlist){
        List<TTargetlist> list;
        if (StringUtils.isEmpty(tTargetlist.getYear())) {
            Calendar calendar = Calendar.getInstance();
            tTargetlist.setYear(String.valueOf(calendar.get(Calendar.YEAR)));
            list = tTargetlistService.selectAllContent(tTargetlist);
            if (CollectionUtils.isEmpty(list)) {
                tTargetlist.setYear(String.valueOf(calendar.get(Calendar.YEAR)-1));
                list = tTargetlistService.selectAllContent(tTargetlist);
            }
        } else {
            list = tTargetlistService.selectAllContent(tTargetlist);
        }
        return AjaxResult.success(list);
    }
    @GetMapping("/getAllMeasures")
    public AjaxResult getAllMeasures(TTargetlist tTargetlist){
        return AjaxResult.success(tTargetlistService.selectAllMeasures(tTargetlist));
    }
}
