package com.qianhe.controller;

import com.qianhe.common.annotation.Log;
import com.qianhe.common.constant.HttpStatus;
import com.qianhe.common.core.controller.BaseController;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.core.domain.entity.SysDept;
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.*;
import com.qianhe.mapper.SjGfjsZdgzMapper;
import com.qianhe.mapper.SjGfjsBfzjcMapper;
import com.qianhe.service.ISjGfjsZsdwkhpjService;
import com.qianhe.service.ISjGfjsZsdwkhpjZbService;
import com.qianhe.system.mapper.SysDeptMapper;
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.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;
import java.util.stream.Collectors;

/**
 * 规范建设-帮扶组考核评价Controller
 * 现帮扶组考核评价
 * @author qianhe
 * @date 2024-07-24
 */
@RestController
@RequestMapping("/system/sjGfjsBfzkhpj")
public class SjGfjsBfzkhpjController extends BaseController
{
    @Autowired
    private SysDeptMapper sysDeptMapper;
    
    
    @Autowired
    private ISjGfjsZsdwkhpjService sjGfjsZsdwkhpjService;
    @Autowired
    private ISjGfjsZsdwkhpjZbService sjGfjsZsdwkhpjZbService;
    
    @Autowired
    private SjGfjsBfzjcMapper sjGfjsZsdwwtcjMapper;
    
    @Autowired
    private SjGfjsZdgzMapper sjGfjsZdgzMapper;
    
//    @Autowired
//    private SjGfjsFjxbzMapper sjGfjsFjxbzMapper;
//    @Autowired
//    private ISjGfjsZsdwkhpjfjxService sjGfjsZsdwkhpjfjxService;
//    @Autowired
//    private SjGfjsZsdwfjxcjMapper sjGfjsZsdwfjxcjMapper;
    
    /**
     * 查询规范建设-帮扶组考核评价列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SjGfjsZsdwkhpj sjGfjsZsdwkhpj)
    {
        startPage();
        List<SjGfjsZsdwkhpj> list = sjGfjsZsdwkhpjService.selectSjGfjsZsdwkhpjList(sjGfjsZsdwkhpj);
        return getDataTable(list);
    }

    /**
     * 查询考核评价
     * @return
     */
    @GetMapping("/listAll")
    public Map<String,Object> listAll(SjGfjsZsdwkhpj sjGfjsZsdwkhpj)
    {

        Map<String,Object> map=new HashMap<>();
        Long deptId = sjGfjsZsdwkhpj.getDeptId();
        String nd = sjGfjsZsdwkhpj.getNd();
        SysDept dept = sysDeptMapper.selectDeptById(deptId);
        String deptLx = dept.getDeptLx();
        if(StringUtils.isEmpty(deptLx)){
            map.put("code",5);
            map.put("msg","该单位未维护单位类型");
            map.put("khpjData",new ArrayList<>());
            map.put("fjxData",new ArrayList<>());
            return  map;
        }
        String zqfw = sjGfjsZsdwkhpj.getZqfw();
        String startRq=null;
        String endRq=null;

        if("全年".equals(zqfw)){
            startRq=nd+"-01";
            endRq=nd+"-12";
        }

        //查询考核评价是否保存到从表
        List<SjGfjsZsdwkhpj> sjGfjsZsdwkhpjs = sjGfjsZsdwkhpjService.selectSjGfjsZsdwkhpjList(sjGfjsZsdwkhpj);
//        List<SjGfjsZsdwkhpj>
        if(sjGfjsZsdwkhpjs.size()<=0){
            //查询主表信息
            SjGfjsZsdwkhpjZb sjGfjsZsdwkhpjZb=new SjGfjsZsdwkhpjZb();
            sjGfjsZsdwkhpjZb.setNd(nd);
            sjGfjsZsdwkhpjZb.setDeptId(deptId);
            sjGfjsZsdwkhpjZb.setZqfw(sjGfjsZsdwkhpj.getZqfw());
            SjGfjsZsdwkhpjZb sjGfjsZsdwkhpjZbnew =sjGfjsZsdwkhpjZbService.selectSjGfjsZsdwkhpjZb(sjGfjsZsdwkhpjZb);
            if(sjGfjsZsdwkhpjZbnew==null){
                sjGfjsZsdwkhpjZbnew=new SjGfjsZsdwkhpjZb();
                sjGfjsZsdwkhpjZbnew.setNd(nd);
                sjGfjsZsdwkhpjZbnew.setDeptId(deptId);
                sjGfjsZsdwkhpjZbnew.setParentDeptId(dept.getParentId());
                sjGfjsZsdwkhpjZbnew.setZqfw(sjGfjsZsdwkhpj.getZqfw());
                sjGfjsZsdwkhpjZbnew.setZqlx("年度");
                sjGfjsZsdwkhpjZbnew.setJb("帮扶组");
                sjGfjsZsdwkhpjZbnew.setDeptDfl(dept.getDeptDfl());
                sjGfjsZsdwkhpjZbnew.setDeptLx(dept.getDeptLx());
                sjGfjsZsdwkhpjZbnew.setDeptYwfl(dept.getDeptYwfl());
                sjGfjsZsdwkhpjZbnew.setZt("0");//未提交
                sjGfjsZsdwkhpjZbService.insertSjGfjsZsdwkhpjZb(sjGfjsZsdwkhpjZbnew);
            }

            //先保存再查询
            SjGfjsZdgz sjGfjsZdgz=new SjGfjsZdgz();
//            sjGfjsZdgz.setLx(deptLx);
            sjGfjsZdgz.setLx("基础");
            sjGfjsZdgz.setNd(nd);
            List<SjGfjsZdgzCb> sjGfjsZdgzList=sjGfjsZdgzMapper.selectSjGfjsZdgzCxBzList(sjGfjsZdgz);
            List<SjGfjsZsdwkhpj> addList=new ArrayList<>();
            //查询问题
            SjGfjsZsdwwtcj sjGfjsZsdwwtcj =new SjGfjsZsdwwtcj();
            sjGfjsZsdwwtcj.setDeptId(deptId);
            sjGfjsZsdwwtcj.setStartRq(startRq);
            sjGfjsZsdwwtcj.setEndRq(endRq);
            sjGfjsZsdwwtcj.setJcjb("帮扶组检查");
            List<SjGfjsZsdwwtcj> sjGfjsZsdwwtcjs = sjGfjsZsdwwtcjMapper.selectSjGfjsZsdwwtcjList(sjGfjsZsdwwtcj);

            for(int i=0;i<sjGfjsZdgzList.size();i++){
                SjGfjsZdgzCb sjGfjsZdgzCb = sjGfjsZdgzList.get(i);
                SjGfjsZsdwkhpj zsdwkhpj = new SjGfjsZsdwkhpj();
                zsdwkhpj.setKhnr(sjGfjsZdgzCb.getKhnr());
                zsdwkhpj.setKhxd(sjGfjsZdgzCb.getKhxd());
                zsdwkhpj.setPjbzid(sjGfjsZdgzCb.getId()+"");
                zsdwkhpj.setPjbzmc(sjGfjsZdgzCb.getPjbz());
                zsdwkhpj.setDeptId(deptId);
                zsdwkhpj.setNd(nd);
                zsdwkhpj.setZqfw(sjGfjsZsdwkhpj.getZqfw());
                zsdwkhpj.setZqlx("年度");
                zsdwkhpj.setJb("帮扶组");
                zsdwkhpj.setZbId(sjGfjsZsdwkhpjZbnew.getId());
                zsdwkhpj.setYl1(i+1L);
                zsdwkhpj.setKhfz("A");
                //计算问题
                List<String> collect = sjGfjsZsdwwtcjs.stream().filter(item -> item.getPjbzid().equals(zsdwkhpj.getPjbzid()))
                        .map(SjGfjsZsdwwtcj::getWtmc).collect(Collectors.toList());
                zsdwkhpj.setSj(collect.size()+"");
                zsdwkhpj.setWtms(String.join(";",collect));
                addList.add(zsdwkhpj);

            }
            //保存考核评价
            if(addList.size()>0){
                sjGfjsZsdwkhpjService.batchSave(addList);
            }


        }
        //查询考核评价
        List<SjGfjsZsdwkhpj> resjGfjsZsdwkhpjs = sjGfjsZsdwkhpjService.selectSjGfjsZsdwkhpjList(sjGfjsZsdwkhpj);

        //查询主表信息
        SjGfjsZsdwkhpjZb zb_qry = new SjGfjsZsdwkhpjZb();
        zb_qry.setNd(nd);
        zb_qry.setDeptId(deptId);
        zb_qry.setZqfw(sjGfjsZsdwkhpj.getZqfw());
        SjGfjsZsdwkhpjZb zb =sjGfjsZsdwkhpjZbService.selectSjGfjsZsdwkhpjZb(zb_qry);
        String zt = zb.getZt();

        map.put("code",HttpStatus.SUCCESS);
        map.put("msg","查询成功");
        map.put("khpjData",resjGfjsZsdwkhpjs);
        map.put("zt", zt);
        return  map;

    }
    /**
     * 导出规范建设-帮扶组考核评价列表
     */
    @Log(title = "规范建设-帮扶组考核评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjGfjsZsdwkhpj sjGfjsZsdwkhpj)
    {
        List<SjGfjsZsdwkhpj> list = sjGfjsZsdwkhpjService.selectSjGfjsZsdwkhpjList(sjGfjsZsdwkhpj);

        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {

            in =this.getClass().getResourceAsStream("/static/gfjs_zsdwkhpj.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");
            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( SjGfjsZsdwkhpj 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.getKhnr());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getKhxd());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getPjbzmc());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getSj());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getWtms());
                cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(zsdwkhpj.getKhfz());
                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);
            mergeCellsByColumn(sheet,1);
            sheet.getRow(0).getCell(0).setCellValue(sjGfjsZsdwkhpj.getNd()+sjGfjsZsdwkhpj.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(sjGfjsZsdwkhpjService.selectSjGfjsZsdwkhpjById(id));
    }

    /**
     * 新增规范建设-帮扶组考核评价
     */
    @Log(title = "规范建设-帮扶组考核评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjGfjsZsdwkhpj sjGfjsZsdwkhpj)
    {
        return toAjax(sjGfjsZsdwkhpjService.insertSjGfjsZsdwkhpj(sjGfjsZsdwkhpj));
    }

    /**
     * 修改规范建设-帮扶组考核评价
     */
    @Log(title = "规范建设-帮扶组考核评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjGfjsZsdwkhpj sjGfjsZsdwkhpj)
    {
        return toAjax(sjGfjsZsdwkhpjService.updateSjGfjsZsdwkhpj(sjGfjsZsdwkhpj));
    }

    /**
     * 删除规范建设-帮扶组考核评价
     */
    @Log(title = "规范建设-帮扶组考核评价", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sjGfjsZsdwkhpjService.deleteSjGfjsZsdwkhpjByIds(ids));
    }

    /**
     * 修改规范建设-帮扶组考核评价
     */
    @Log(title = "规范建设-帮扶组考核评价", businessType = BusinessType.UPDATE)
    @PutMapping("/pledit")
    public AjaxResult pledit(@RequestBody List<SjGfjsZsdwkhpj> list)
    {
        return toAjax(sjGfjsZsdwkhpjService.pledit(list));
    }
    /**
     * 修改并提交 规范建设-帮扶组考核评价
     */
    @Log(title = "修改并提交 规范建设-帮扶组考核评价", businessType = BusinessType.UPDATE)
    @PutMapping("/pleditAndTj")
    public AjaxResult pleditAndTj(@RequestBody List<SjGfjsZsdwkhpj> list)
    {
        sjGfjsZsdwkhpjService.pledit(list);

        SjGfjsZsdwkhpj sjGfjsZsdwkhpj = list.get(0);
        SjGfjsZsdwkhpjZb zb = sjGfjsZsdwkhpjZbService.selectSjGfjsZsdwkhpjZbById(sjGfjsZsdwkhpj.getZbId());
        zb.setZt("1");
        return toAjax(sjGfjsZsdwkhpjZbService.updateSjGfjsZsdwkhpjZb(zb));
    }


    @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<SjGfjsZsdwkhpj> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjGfjsZsdwkhpj zsdwkhpj=new SjGfjsZsdwkhpj();
                System.out.println(row);
                //id
                String id=new DataFormatter().formatCellValue(row.getCell(6));
                if(StringUtils.isEmpty(id)){
                    return AjaxResult.error("id不能为空");
                }
                zsdwkhpj.setId(Long.parseLong(id));
                //主表id
                String zbid=new DataFormatter().formatCellValue(row.getCell(7));
                if(StringUtils.isEmpty(zbid)){
                    return AjaxResult.error("主表id不能为空");
                }
                zsdwkhpj.setZbId(Long.parseLong(zbid));

                String khnr=new DataFormatter().formatCellValue(row.getCell(0));
                zsdwkhpj.setKhnr(khnr);

                String xd=new DataFormatter().formatCellValue(row.getCell(1));
                zsdwkhpj.setKhxd(xd);

                String pj=new DataFormatter().formatCellValue(row.getCell(2));
                zsdwkhpj.setPjbzmc(pj);

                String sl=new DataFormatter().formatCellValue(row.getCell(3));
                zsdwkhpj.setSj(sl);
                //问题描述
                String wtms=new DataFormatter().formatCellValue(row.getCell(4));
                zsdwkhpj.setWtms(wtms);
                //考核分值
                String khfz=new DataFormatter().formatCellValue(row.getCell(5));
                zsdwkhpj.setKhfz(khfz);

                list.add(zsdwkhpj);
            }
            if(list.size()>0){
                sjGfjsZsdwkhpjService.pledit(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

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