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.SjZdbfZsdwkhpjfjx;
import com.qianhe.service.ISjZdbfJcdwkhpjfjxService;
import com.qianhe.service.ISjZdbfZsdwkhpjfjxService;
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/sjZdbfJcdwkhpjfjx")
public class SjZdbfJcdwkhpjfjxController extends BaseController
{
    @Autowired
    private ISjZdbfJcdwkhpjfjxService sjZdbfZsdwkhpjfjxService;

    /**
     * 查询指导帮扶-基层单位考核评价否决项列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:list')")
    @GetMapping("/list")
    public TableDataInfo list(SjZdbfZsdwkhpjfjx sjZdbfZsdwkhpjfjx)
    {
        startPage();
        List<SjZdbfZsdwkhpjfjx> list = sjZdbfZsdwkhpjfjxService.selectSjZdbfZsdwkhpjfjxList(sjZdbfZsdwkhpjfjx);
        return getDataTable(list);
    }

    /**
     * 导出指导帮扶-基层单位考核评价否决项列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:export')")
    @Log(title = "指导帮扶-基层单位考核评价否决项", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjZdbfZsdwkhpjfjx sjZdbfZsdwkhpjfjx)
    {
        List<SjZdbfZsdwkhpjfjx> list = sjZdbfZsdwkhpjfjxService.selectSjZdbfZsdwkhpjfjxList(sjZdbfZsdwkhpjfjx);
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {

            in =this.getClass().getResourceAsStream("/static/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(sjZdbfZsdwkhpj.getNd()+"年"+sjZdbfZsdwkhpj.getZqfw()+sjZdbfZsdwkhpj.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( SjZdbfZsdwkhpjfjx 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(sjZdbfZsdwkhpjfjx.getNd()+sjZdbfZsdwkhpjfjx.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));
        }
    }

    /**
     * 获取指导帮扶-基层单位考核评价否决项详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjZdbfZsdwkhpjfjxService.selectSjZdbfZsdwkhpjfjxById(id));
    }

    /**
     * 新增指导帮扶-基层单位考核评价否决项
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:add')")
    @Log(title = "指导帮扶-基层单位考核评价否决项", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjZdbfZsdwkhpjfjx sjZdbfZsdwkhpjfjx)
    {
        return toAjax(sjZdbfZsdwkhpjfjxService.insertSjZdbfZsdwkhpjfjx(sjZdbfZsdwkhpjfjx));
    }

    /**
     * 修改指导帮扶-基层单位考核评价否决项
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:edit')")
    @Log(title = "指导帮扶-基层单位考核评价否决项", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjZdbfZsdwkhpjfjx sjZdbfZsdwkhpjfjx)
    {
        return toAjax(sjZdbfZsdwkhpjfjxService.updateSjZdbfZsdwkhpjfjx(sjZdbfZsdwkhpjfjx));
    }

    /**
     * 删除指导帮扶-基层单位考核评价否决项
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:remove')")
    @Log(title = "指导帮扶-基层单位考核评价否决项", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sjZdbfZsdwkhpjfjxService.deleteSjZdbfZsdwkhpjfjxByIds(ids));
    }

    /**
     * 修改指导帮扶-基层单位考核评价否决项
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:pledit')")
    @Log(title = "指导帮扶-基层单位考核评价否决项", businessType = BusinessType.UPDATE)
    @PutMapping("/pledit")
    public AjaxResult pledit(@RequestBody List<SjZdbfZsdwkhpjfjx> list)
    {
        return toAjax(sjZdbfZsdwkhpjfjxService.pledit(list));
    }

    @PreAuthorize("@ss.hasPermi('system:sjZdbfJcdwkhpjfjx:importData')")
    @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<SjZdbfZsdwkhpjfjx> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjZdbfZsdwkhpjfjx zsdwkhpj=new SjZdbfZsdwkhpjfjx();
                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){
                sjZdbfZsdwkhpjfjxService.pledit(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

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


}
