package com.qianhe.controller;

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;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.qianhe.common.constant.HttpStatus;
import com.qianhe.common.core.domain.entity.SysDept;
import com.qianhe.common.core.page.PageDomain;
import com.qianhe.common.core.page.TableSupport;
import com.qianhe.common.exception.BusinessException;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.domain.*;
import com.qianhe.mapper.SjZdbfFjxbzMapper;
import com.qianhe.mapper.SjZdbfKhpjbzMapper;
import com.qianhe.mapper.SjZdbfZsdwfjxcjMapper;
import com.qianhe.mapper.SjZdbfZsdwwtcjMapper;
import com.qianhe.service.ISjZdbfFjxbzService;
import com.qianhe.service.ISjZdbfZsdwkhpjZbService;
import com.qianhe.service.ISjZdbfZsdwkhpjfjxService;
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.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qianhe.common.annotation.Log;
import com.qianhe.common.core.controller.BaseController;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.enums.BusinessType;
import com.qianhe.service.ISjZdbfZsdwkhpjService;
import com.qianhe.common.utils.poi.ExcelUtil;
import com.qianhe.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 指导帮扶-直属单位考核评价Controller
 *
 * @author qianhe
 * @date 2024-07-24
 */
@RestController
@RequestMapping("/system/sjZdbfZsdwkhpj")
public class SjZdbfZsdwkhpjController extends BaseController
{
    @Autowired
    private ISjZdbfZsdwkhpjService sjZdbfZsdwkhpjService;

    @Autowired
    private ISjZdbfZsdwkhpjZbService sjZdbfZsdwkhpjZbService;
    @Autowired
    private SjZdbfKhpjbzMapper sjZdbfKhpjbzMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SjZdbfFjxbzMapper sjZdbfFjxbzMapper;

    @Autowired
    private ISjZdbfZsdwkhpjfjxService sjZdbfZsdwkhpjfjxService;
    @Autowired
    private SjZdbfZsdwwtcjMapper sjZdbfZsdwwtcjMapper;
    @Autowired
    private SjZdbfZsdwfjxcjMapper sjZdbfZsdwfjxcjMapper;
    /**
     * 查询指导帮扶-直属单位考核评价列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:list')")
    @GetMapping("/list")
    public TableDataInfo list(SjZdbfZsdwkhpj sjZdbfZsdwkhpj)
    {
        startPage();
        List<SjZdbfZsdwkhpj> list = sjZdbfZsdwkhpjService.selectSjZdbfZsdwkhpjList(sjZdbfZsdwkhpj);
        return getDataTable(list);
    }

    /**
     * 查询考核评价
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:listAll')")
    @GetMapping("/listAll")
    public Map<String,Object> listAll(SjZdbfZsdwkhpj sjZdbfZsdwkhpj)
    {
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        Integer pageNum = pageDomain.getPageNum();
//        Integer pageSize = pageDomain.getPageSize();
        Map<String,Object> map=new HashMap<>();
        Long deptId = sjZdbfZsdwkhpj.getDeptId();
        String nd = sjZdbfZsdwkhpj.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 = sjZdbfZsdwkhpj.getZqfw();
        String startRq=null;
        String endRq=null;
        if("上半年".equals(zqfw)){
            startRq=nd+"-01";
            endRq=nd+"-06";
        }else {
            startRq=nd+"-07";
            endRq=nd+"-12";
        }

        //查询考核评价是否保存到从表
        List<SjZdbfZsdwkhpj> sjZdbfZsdwkhpjs = sjZdbfZsdwkhpjService.selectSjZdbfZsdwkhpjList(sjZdbfZsdwkhpj);
//        List<SjZdbfZsdwkhpj>
        if(sjZdbfZsdwkhpjs.size()<=0){
            //查询主表信息
            SjZdbfZsdwkhpjZb sjZdbfZsdwkhpjZb=new SjZdbfZsdwkhpjZb();
            sjZdbfZsdwkhpjZb.setNd(nd);
            sjZdbfZsdwkhpjZb.setDeptId(deptId);
            sjZdbfZsdwkhpjZb.setZqfw(sjZdbfZsdwkhpj.getZqfw());
            SjZdbfZsdwkhpjZb sjZdbfZsdwkhpjZbnew =sjZdbfZsdwkhpjZbService.selectSjZdbfZsdwkhpjZb(sjZdbfZsdwkhpjZb);
            if(sjZdbfZsdwkhpjZbnew==null){
                sjZdbfZsdwkhpjZbnew=new SjZdbfZsdwkhpjZb();
                sjZdbfZsdwkhpjZbnew.setNd(nd);
                sjZdbfZsdwkhpjZbnew.setDeptId(deptId);
                sjZdbfZsdwkhpjZbnew.setParentDeptId(dept.getParentId());
                sjZdbfZsdwkhpjZbnew.setZqfw(sjZdbfZsdwkhpj.getZqfw());
                sjZdbfZsdwkhpjZbnew.setZqlx("半年度");
                sjZdbfZsdwkhpjZbnew.setJb("直属单位");
                sjZdbfZsdwkhpjZbnew.setDeptDfl(dept.getDeptDfl());
                sjZdbfZsdwkhpjZbnew.setDeptLx(dept.getDeptLx());
                sjZdbfZsdwkhpjZbnew.setDeptYwfl(dept.getDeptYwfl());
                sjZdbfZsdwkhpjZbService.insertSjZdbfZsdwkhpjZb(sjZdbfZsdwkhpjZbnew);
            }

            //先保存再查询
            SjZdbfKhpjbz sjZdbfKhpjbz=new SjZdbfKhpjbz();
            sjZdbfKhpjbz.setLx(deptLx);
            sjZdbfKhpjbz.setNd(nd);
            List<SjZdbfKhpjbzCb> sjZdbfKhpjbzList=sjZdbfKhpjbzMapper.selectSjZdbfKhpjbzCxBzList(sjZdbfKhpjbz);
            List<SjZdbfZsdwkhpj> addList=new ArrayList<>();
            //查询问题
            SjZdbfZsdwwtcj sjZdbfZsdwwtcj =new SjZdbfZsdwwtcj();
            sjZdbfZsdwwtcj.setDeptId(deptId);
            sjZdbfZsdwwtcj.setStartRq(startRq);
            sjZdbfZsdwwtcj.setEndRq(endRq);
            sjZdbfZsdwwtcj.setJcjb("直属单位自查");
            List<SjZdbfZsdwwtcj> sjZdbfZsdwwtcjs = sjZdbfZsdwwtcjMapper.selectSjZdbfZsdwwtcjList(sjZdbfZsdwwtcj);

            for(int i=0;i<sjZdbfKhpjbzList.size();i++){
                SjZdbfKhpjbzCb sjZdbfKhpjbzCb = sjZdbfKhpjbzList.get(i);
                SjZdbfZsdwkhpj zsdwkhpj=new SjZdbfZsdwkhpj();
                zsdwkhpj.setKhnr(sjZdbfKhpjbzCb.getKhnr());
                zsdwkhpj.setKhxd(sjZdbfKhpjbzCb.getKhxd());
                zsdwkhpj.setPjbzid(sjZdbfKhpjbzCb.getId()+"");
                zsdwkhpj.setPjbzmc(sjZdbfKhpjbzCb.getPjbz());
                zsdwkhpj.setDeptId(deptId);
                zsdwkhpj.setNd(nd);
                zsdwkhpj.setZqfw(sjZdbfZsdwkhpj.getZqfw());
                zsdwkhpj.setZqlx("半年度");
                zsdwkhpj.setJb("直属单位");
                zsdwkhpj.setZbId(sjZdbfZsdwkhpjZbnew.getId());
                zsdwkhpj.setYl1(i+1L);
                zsdwkhpj.setKhfz("-0");
                //计算问题
                List<String> collect = sjZdbfZsdwwtcjs.stream().filter(item -> item.getPjbzid().equals(zsdwkhpj.getPjbzid()))
                        .map(SjZdbfZsdwwtcj::getWtmc).collect(Collectors.toList());
                zsdwkhpj.setSj(collect.size()+"");
                zsdwkhpj.setWtms(String.join(";",collect));
                addList.add(zsdwkhpj);

            }
            //保存考核评价
            if(addList.size()>0){
                sjZdbfZsdwkhpjService.batchSave(addList);
            }
            //保存否决项
            SjZdbfFjxbzCb sjZdbfFjxbzCb =new SjZdbfFjxbzCb();
            sjZdbfFjxbzCb.setNd(nd);
            List<SjZdbfFjxbzCb> cbList=sjZdbfFjxbzMapper.selectSjZdbfFjxbzCxBzList(sjZdbfFjxbzCb);
            List<SjZdbfZsdwkhpjfjx> fjxList=new ArrayList<>();
            //查询否决
            SjZdbfZsdwfjxcj sjZdbfZsdwfjxcj=new SjZdbfZsdwfjxcj();
            sjZdbfZsdwfjxcj.setDeptId(deptId);
            sjZdbfZsdwfjxcj.setStartRq(startRq);
            sjZdbfZsdwfjxcj.setEndRq(endRq);
            List<SjZdbfZsdwfjxcj> sjZdbfZsdwfjxcjs = sjZdbfZsdwfjxcjMapper.selectSjZdbfZsdwfjxcjList(sjZdbfZsdwfjxcj);
            for(int i=0;i<cbList.size();i++){
                SjZdbfFjxbzCb cb = cbList.get(i);
                SjZdbfZsdwkhpjfjx fjx=new SjZdbfZsdwkhpjfjx();
                fjx.setFlmc(cb.getFlmc());
                fjx.setPjbzid(cb.getId()+"");
                fjx.setPjbzmc(cb.getPjbz()+"");
                fjx.setDeptId(deptId);
                fjx.setNd(nd);
                fjx.setZqfw(sjZdbfZsdwkhpj.getZqfw());
                fjx.setZqlx("半年度");
                fjx.setJb("直属单位");
                fjx.setZbId(sjZdbfZsdwkhpjZbnew.getId());
                fjx.setYl1(i+1L);
                List<String> collect = sjZdbfZsdwfjxcjs.stream().filter(item -> item.getPjbzid().equals(cb.getId()+"")).map(SjZdbfZsdwfjxcj::getWtmc).collect(Collectors.toList());
                if(collect.size()>0){
                    fjx.setSffs("是");
                    fjx.setWtms(String.join(";",collect));
                }
                fjxList.add(fjx);
            }
            if(fjxList.size()>0){
                sjZdbfZsdwkhpjfjxService.batchSave(fjxList);
            }

        }
        //查询考核评价
        List<SjZdbfZsdwkhpj> resjZdbfZsdwkhpjs = sjZdbfZsdwkhpjService.selectSjZdbfZsdwkhpjList(sjZdbfZsdwkhpj);
        //查询否决项
        SjZdbfZsdwkhpjfjx sjZdbfZsdwkhpjfjx =new SjZdbfZsdwkhpjfjx();
        sjZdbfZsdwkhpjfjx.setNd(nd);
        sjZdbfZsdwkhpjfjx.setDeptId(deptId);
        sjZdbfZsdwkhpjfjx.setZqfw(sjZdbfZsdwkhpj.getZqfw());
        List<SjZdbfZsdwkhpjfjx> resjZdbfZsdwkhpjfjxList = sjZdbfZsdwkhpjfjxService.selectSjZdbfZsdwkhpjfjxList(sjZdbfZsdwkhpjfjx);


        map.put("code",HttpStatus.SUCCESS);
        map.put("msg","查询成功");
        map.put("khpjData",resjZdbfZsdwkhpjs);
        map.put("fjxData",resjZdbfZsdwkhpjfjxList);
        return  map;

    }
    /**
     * 导出指导帮扶-直属单位考核评价列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:export')")
    @Log(title = "指导帮扶-直属单位考核评价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjZdbfZsdwkhpj sjZdbfZsdwkhpj)
    {
        List<SjZdbfZsdwkhpj> list = sjZdbfZsdwkhpjService.selectSjZdbfZsdwkhpjList(sjZdbfZsdwkhpj);
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {

            in =this.getClass().getResourceAsStream("/static/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");
//            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( SjZdbfZsdwkhpj 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(sjZdbfZsdwkhpj.getNd()+sjZdbfZsdwkhpj.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:sjZdbfZsdwkhpj:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjZdbfZsdwkhpjService.selectSjZdbfZsdwkhpjById(id));
    }

    /**
     * 新增指导帮扶-直属单位考核评价
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:add')")
    @Log(title = "指导帮扶-直属单位考核评价", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjZdbfZsdwkhpj sjZdbfZsdwkhpj)
    {
        return toAjax(sjZdbfZsdwkhpjService.insertSjZdbfZsdwkhpj(sjZdbfZsdwkhpj));
    }

    /**
     * 修改指导帮扶-直属单位考核评价
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:edit')")
    @Log(title = "指导帮扶-直属单位考核评价", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjZdbfZsdwkhpj sjZdbfZsdwkhpj)
    {
        return toAjax(sjZdbfZsdwkhpjService.updateSjZdbfZsdwkhpj(sjZdbfZsdwkhpj));
    }

    /**
     * 删除指导帮扶-直属单位考核评价
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:remove')")
    @Log(title = "指导帮扶-直属单位考核评价", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sjZdbfZsdwkhpjService.deleteSjZdbfZsdwkhpjByIds(ids));
    }

    /**
     * 修改指导帮扶-直属单位考核评价
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj:pledit')")
    @Log(title = "指导帮扶-直属单位考核评价", businessType = BusinessType.UPDATE)
    @PutMapping("/pledit")
    public AjaxResult pledit(@RequestBody List<SjZdbfZsdwkhpj> list)
    {
        return toAjax(sjZdbfZsdwkhpjService.pledit(list));
    }


    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwkhpj: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<SjZdbfZsdwkhpj> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjZdbfZsdwkhpj zsdwkhpj=new SjZdbfZsdwkhpj();
                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(1));
                zsdwkhpj.setKhnr(khnr);

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

                String pj=new DataFormatter().formatCellValue(row.getCell(3));
                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){
                sjZdbfZsdwkhpjService.pledit(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

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