package com.qianhe.controller;

import com.qianhe.common.annotation.Log;
import com.qianhe.common.core.controller.BaseController;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.core.page.TableDataInfo;
import com.qianhe.common.enums.BusinessType;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.domain.SjGfjsZsdwkhpjfjx;
import com.qianhe.service.ISjGfjsZsdwkhpjfjxService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 规范建设-直属单位考核评价否决项Controller
 *
 * @author qianhe
 * @date 2024-07-24
 */
@RestController
@RequestMapping("/system/sjGfjsZsdwkhpjfjx")
public class SjGfjsZsdwkhpjfjxController extends BaseController
{
    @Autowired
    private ISjGfjsZsdwkhpjfjxService sjGfjsZsdwkhpjfjxService;

    /**
     * 查询规范建设-直属单位考核评价否决项列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SjGfjsZsdwkhpjfjx sjGfjsZsdwkhpjfjx)
    {
        startPage();
        List<SjGfjsZsdwkhpjfjx> list = sjGfjsZsdwkhpjfjxService.selectSjGfjsZsdwkhpjfjxList(sjGfjsZsdwkhpjfjx);
        return getDataTable(list);
    }

    /**
     * 导出规范建设-直属单位考核评价否决项列表
     */
    @Log(title = "规范建设-直属单位考核评价否决项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjGfjsZsdwkhpjfjx sjGfjsZsdwkhpjfjx)
    {
        List<SjGfjsZsdwkhpjfjx> list = sjGfjsZsdwkhpjfjxService.selectSjGfjsZsdwkhpjfjxList(sjGfjsZsdwkhpjfjx);
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {

            in =this.getClass().getResourceAsStream("/static/gfjs_zsdwfjx.xlsx");
            exl = WorkbookFactory.create(in);
            out = response.getOutputStream();
            response.reset();
            String filename = URLEncoder.encode("否决项.xlsx", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            Sheet sheet = exl.getSheet("Sheet1");
//            sheet.getRow(0).getCell(0).setCellValue(sjGfjsZsdwkhpj.getNd()+"年"+sjGfjsZsdwkhpj.getZqfw()+sjGfjsZsdwkhpj.getDeptName());
            CellStyle cellStyle = exl.createCellStyle();
            cellStyle.setWrapText(true);
            cellStyle.setAlignment(HorizontalAlignment.LEFT);
            cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());
            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());
            String deptName="";
            int lastRow = sheet.getLastRowNum()+1;
            for( SjGfjsZsdwkhpjfjx zsdwkhpj:list){
                deptName= zsdwkhpj.getDeptName();;
                Row row = sheet.createRow(lastRow);
                row.setHeightInPoints(18);
                int m = 0;
                Cell cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getFlmc());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getPjbzmc());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getSffs());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getWtms());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getId());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getZbId());
                lastRow++;
            }
            //合并行
            mergeCellsByColumn(sheet,0);
            sheet.getRow(0).getCell(0).setCellValue(sjGfjsZsdwkhpjfjx.getNd()+sjGfjsZsdwkhpjfjx.getZqfw()+deptName+"否决项评价");
            exl.write(out);
            exl.close();
        }catch (Exception e){
            e.getMessage();
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        }finally {
            if (exl != null) {
                try {
                    exl.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    // 根据某一列的值是否相同，对其他列的单元格进行合并
    private static void mergeCellsByColumn(Sheet sheet, int columnIndex) {
        Map<String, Integer> groups = new HashMap<>();

        // 遍历该列，记录相同值的行索引
        int start=1;
        int end=1;
        String old="";
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            Cell cell = row.getCell(columnIndex);
            String cellValue = cell.getStringCellValue();
            if (!groups.containsKey(cellValue)) {
                if(groups.get(old)!=null){
                    start = groups.get(old);
                }
                old=cellValue;
                groups.put(cellValue, i);
                //合并行
                mergeCellsInRange(sheet, columnIndex, start, end);
                start=i;
                end=i;
            } else {
                end++;
                if(i==sheet.getLastRowNum()){
                    mergeCellsInRange(sheet, columnIndex, start, end);
                }
            }
        }
    }
    // 合并指定范围内的单元格
    private static void mergeCellsInRange(Sheet sheet, int columnIndex, int startIndex, int endIndex) {
        if(startIndex!=endIndex){
            sheet.addMergedRegion(new CellRangeAddress(startIndex, endIndex, columnIndex, columnIndex));
        }
    }

    /**
     * 获取规范建设-直属单位考核评价否决项详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjGfjsZsdwkhpjfjxService.selectSjGfjsZsdwkhpjfjxById(id));
    }

    /**
     * 新增规范建设-直属单位考核评价否决项
     */
    @Log(title = "规范建设-直属单位考核评价否决项", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjGfjsZsdwkhpjfjx sjGfjsZsdwkhpjfjx)
    {
        return toAjax(sjGfjsZsdwkhpjfjxService.insertSjGfjsZsdwkhpjfjx(sjGfjsZsdwkhpjfjx));
    }

    /**
     * 修改规范建设-直属单位考核评价否决项
     */
    @Log(title = "规范建设-直属单位考核评价否决项", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjGfjsZsdwkhpjfjx sjGfjsZsdwkhpjfjx)
    {
        return toAjax(sjGfjsZsdwkhpjfjxService.updateSjGfjsZsdwkhpjfjx(sjGfjsZsdwkhpjfjx));
    }

    /**
     * 删除规范建设-直属单位考核评价否决项
     */
    @Log(title = "规范建设-直属单位考核评价否决项", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sjGfjsZsdwkhpjfjxService.deleteSjGfjsZsdwkhpjfjxByIds(ids));
    }

    /**
     * 修改规范建设-直属单位考核评价否决项
     */
    @Log(title = "规范建设-直属单位考核评价否决项", businessType = BusinessType.UPDATE)
    @PutMapping("/pledit")
    public AjaxResult pledit(@RequestBody List<SjGfjsZsdwkhpjfjx> list)
    {
        return toAjax(sjGfjsZsdwkhpjfjxService.pledit(list));
    }

    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception{

        XSSFWorkbook workbook = null;
//        List<SysDept> deptList = sysDeptMapper.selectDeptList(new SysDept());

        try {
            //装载流
            workbook = new XSSFWorkbook(file.getInputStream());

            // 获取一个工作表，下标从0开始
            XSSFSheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            List<SjGfjsZsdwkhpjfjx> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjGfjsZsdwkhpjfjx zsdwkhpj=new SjGfjsZsdwkhpjfjx();
                System.out.println(row);
                //id
                String id=new DataFormatter().formatCellValue(row.getCell(4));
                if(StringUtils.isEmpty(id)){
                    return AjaxResult.error("id不能为空");
                }
                zsdwkhpj.setId(Long.parseLong(id));
                //主表id
                String zbid=new DataFormatter().formatCellValue(row.getCell(5));
                if(StringUtils.isEmpty(zbid)){
                    return AjaxResult.error("主表id不能为空");
                }
                zsdwkhpj.setZbId(Long.parseLong(zbid));
                //是否发生
                String sffs=new DataFormatter().formatCellValue(row.getCell(2));
                zsdwkhpj.setSffs(sffs);
                //问题描述
                String wtms=new DataFormatter().formatCellValue(row.getCell(3));
                zsdwkhpj.setWtms(wtms);
                list.add(zsdwkhpj);
            }
            if(list.size()>0){
                sjGfjsZsdwkhpjfjxService.pledit(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

        } finally {
            workbook.close();
        }
        return AjaxResult.success("导入成功");
    }


}
