package com.inspect.taskinfo.controller;

import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.RequiresPermissions;

import com.inspect.task.domain.PatrolTask;
import com.inspect.task.service.IPatrolTaskService;

import com.inspect.taskinfo.domain.PatrolTaskInfo;
import com.inspect.taskinfo.service.IPatrolTaskInfoService;

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

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/taskinfo"})
public class PatrolTaskInfoController extends BaseController {
    private final IPatrolTaskInfoService patrolTaskInfoService;
    private final IPatrolTaskService patrolTaskService;

    public PatrolTaskInfoController(IPatrolTaskInfoService patrolTaskInfoService, IPatrolTaskService patrolTaskService) {
        this.patrolTaskInfoService = patrolTaskInfoService;
        this.patrolTaskService = patrolTaskService;
    }

    @RequiresPermissions({"system:taskinfo:list"})
    @GetMapping({"/list"})
    public TableDataInfo list(PatrolTaskInfo patrolTaskInfo) {
        this.startPage();
        List<PatrolTaskInfo> list = this.patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
        return this.getDataTable(list);
    }

    @RequiresPermissions({"system:taskinfo:export"})
    @Log(
            title = "巡视任务从",
            businessType = BizType.EXPORT
    )
    @PostMapping({"/export"})
    public void export(HttpServletResponse response, PatrolTaskInfo patrolTaskInfo) {
        List<PatrolTaskInfo> list = this.patrolTaskInfoService.selectPatrolTaskInfoList(patrolTaskInfo);
        ExcelUtil<PatrolTaskInfo> util = new ExcelUtil<>(PatrolTaskInfo.class);
        util.exportExcel(response, list, "Task Data");
    }

    @RequiresPermissions({"system:taskinfo:query"})
    @GetMapping({"/{lineId}"})
    public AjaxResult getInfo(@PathVariable("lineId") Long lineId) {
        return AjaxResult.success(this.patrolTaskInfoService.selectPatrolTaskInfoByLineId(lineId));
    }

    @RequiresPermissions({"system:taskinfo:add"})
    @Log(
            title = "巡视任务从",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@RequestBody PatrolTaskInfo patrolTaskInfo) {
        return this.toAjax(this.patrolTaskInfoService.insertPatrolTaskInfo(patrolTaskInfo));
    }

    @RequiresPermissions({"system:taskinfo:edit"})
    @Log(
            title = "巡视任务从",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/edit"})
    public AjaxResult edit(@RequestBody PatrolTaskInfo patrolTaskInfo) {
        return this.toAjax(this.patrolTaskInfoService.updatePatrolTaskInfo(patrolTaskInfo));
    }

    @RequiresPermissions({"system:taskinfo:remove"})
    @Log(
            title = "巡视任务从",
            businessType = BizType.DELETE
    )
    @PostMapping({"/remove/{lineIds}"})
    public AjaxResult remove(@PathVariable Long[] lineIds) {
        return this.toAjax(this.patrolTaskInfoService.deletePatrolTaskInfoByLineIds(lineIds));
    }

    @PostMapping({"/importDataToPatrilTask"})
    public AjaxResult importDataToPatrolTask(MultipartFile file) throws Exception {
        if (file == null) {
            return AjaxResult.error("上传文件为空！");
        }
        String filename = file.getOriginalFilename();
        if (filename != null && !filename.isEmpty()) {
            String str;
            try {
                str = this.importDataToPatrolTask(filename, file.getInputStream());
            } catch (IOException e) {
                throw new Exception(e.getMessage());
            }

            return AjaxResult.success("导入结果", str);
        } else {
            return AjaxResult.error("文件名称为空！");
        }
    }

    private String importDataToPatrolTask(String filename, InputStream is) throws Exception {
        String taskNames = "";

        try {
            Workbook workbook = null;
            if (filename.endsWith(".xls")) {
                workbook = new HSSFWorkbook(is);
            }

            if (filename.endsWith(".xlsx")) {
                workbook = new XSSFWorkbook(is);
            }

            if (workbook == null) {
                return "工作簿为空！";
            } else {
                Sheet sheet = workbook.getSheetAt(0);
                if (sheet == null) {
                    return "工作表为空！";
                } else {
                    for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); ++rowNum) {
                        Row row = sheet.getRow(rowNum);
                        if (row != null) {
                            if (row.getCell(2) != null) {
                                row.getCell(2).setCellType(CellType.STRING);
                                row.getCell(0).getStringCellValue();
                            }

                            if (row.getCell(4) != null) {
                                row.getCell(4).setCellType(CellType.STRING);
                                row.getCell(1).getStringCellValue();
                            }

                            if (row.getCell(5) != null) {
                                row.getCell(5).setCellType(CellType.STRING);
                                row.getCell(2).getStringCellValue();
                            }

                            if (row.getCell(6) != null) {
                                row.getCell(6).setCellType(CellType.STRING);
                                row.getCell(3).getStringCellValue();
                            }

                            if (row.getCell(7) != null) {
                                row.getCell(7).setCellType(CellType.STRING);
                                row.getCell(4).getStringCellValue();
                            }

                            if (row.getCell(10) != null) {
                                row.getCell(10).setCellType(CellType.STRING);
                                row.getCell(5).getStringCellValue();
                            }

                            if (row.getCell(11) != null) {
                                row.getCell(11).setCellType(CellType.STRING);
                                row.getCell(6).getStringCellValue();
                            }

                            String patrolpointName = "";
                            if (row.getCell(12) != null) {
                                row.getCell(12).setCellType(CellType.STRING);
                                patrolpointName = row.getCell(7).getStringCellValue().trim();
                            }

                            String patrolpointId = "";
                            if (row.getCell(13) != null) {
                                row.getCell(13).setCellType(CellType.STRING);
                                patrolpointId = row.getCell(8).getStringCellValue().trim();
                            }

                            if (StringUtils.isAllBlank(patrolpointName, patrolpointId)) {
                                throw new Exception("请检查必填项！");
                            }

                            PatrolTaskInfo patrolTaskInfo = new PatrolTaskInfo();
                            int i = this.patrolTaskInfoService.insertPatrolTaskInfo(patrolTaskInfo);
                            if (i <= 0) {
                                return "第" + rowNum + "条失败！";
                            }
                        }
                    }

                    PatrolTask patrolTask = new PatrolTask();
                    patrolTask.setTaskName(taskNames);
                    patrolTask.setPriority("1");
                    patrolTask.setCreateTime(new Date());
                    patrolTask.setDevType("1");
                    patrolTask.setExecutionMode("0");
                    patrolTask.setDeviceList("");
                    patrolTask.setDevNo("");
                    patrolTask.setAreaName("");
                    patrolTask.setAreaIdS("");
                    int i = this.patrolTaskService.insertPatrolTask(patrolTask);
                    return i > 0 ? "成功！" : "失败！";
                }
            }
        } catch (IOException e) {
            e.getMessage();
            return "失败！";
        }
    }
}
