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.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.DateUtils;
import com.qianhe.common.utils.SecurityUtils;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.domain.SjGfjsYdjcjl;
import com.qianhe.domain.SjGfjsZdgzCb;
import com.qianhe.domain.SjGfjsZsdwwtcj;
import com.qianhe.domain.SjZdbfZsdwkhpj;
import com.qianhe.mapper.SjGfjsZdgzMapper;
import com.qianhe.service.ISjGfjsYdjcjlService;
import com.qianhe.system.mapper.SysDeptMapper;
import org.apache.poi.ss.usermodel.*;
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.Date;
import java.util.List;

/**
 * 规范建设 月度检查记录Controller
 * 现基层单位问题采集
 * @author qianhe
 * @date 2025-07-10
 */
@RestController
@RequestMapping("/system/sjGfjsYdjcjl")
public class SjGfjsYdjcjlController extends BaseController
{
    @Autowired
    private ISjGfjsYdjcjlService sjGfjsYdjcjlService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SjGfjsZdgzMapper sjGfjsZdgzMapper;
    /**
     * 查询规范建设 月度检查记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SjGfjsYdjcjl sjGfjsYdjcjl)
    {

        sjGfjsYdjcjl.setJcjb("基层单位自查");
        startPage();
        List<SjGfjsYdjcjl> list = sjGfjsYdjcjlService.selectSjGfjsYdjcjlList(sjGfjsYdjcjl);
        return getDataTable(list);
    }

    /**
     * 导出规范建设 月度检查记录列表
     */
    @Log(title = "规范建设 月度检查记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjGfjsYdjcjl ydjl)
    {
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {
            in =this.getClass().getResourceAsStream("/static/gfjs_ydjcjl_wt.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);
            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();
                }
            }
        }
    }

    //导出 月度检查记录详细 带从表信息 类似 采油管理一区2025-07.xlsx
    @Log(title = "规范建设 月度检查记录详细", businessType = BusinessType.EXPORT)
    @PostMapping("/exportXx")
    public void exportXx(HttpServletResponse response, SjGfjsYdjcjl ydjl)
    {

        //根据id查询 从表数据
        Long id = ydjl.getId();
        ydjl = sjGfjsYdjcjlService.selectSjGfjsYdjcjlById(id);
        String rq = ydjl.getRq();
        String dwmc = ydjl.getDeptName();


        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {
            in =this.getClass().getResourceAsStream("/static/gfjs_ydjcjl_wt.xlsx");
            exl = WorkbookFactory.create(in);
            out = response.getOutputStream();
            response.reset();
            String filename = URLEncoder.encode(dwmc + " " + rq + ".xlsx", "UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            dcExcelCb(exl, ydjl);

            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();
                }
            }
        }
    }
    //导出excel 动态设置从表数据
    private void dcExcelCb(Workbook exl, SjGfjsYdjcjl ydjl){
        List<SjGfjsZsdwwtcj> cbList = ydjl.getSjGfjsZsdwwtcjList();

        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());

        int lastRow = sheet.getLastRowNum()+1;
        for(SjGfjsZsdwwtcj tmp:cbList){
            Row row = sheet.createRow(lastRow);
            row.setHeightInPoints(18);
            int m = 0;
            int xh = 1;//第一列的序号
            Cell cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(xh);
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getWtmc());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getKhnr());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getKhxd());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getPjbzmc());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getZgzrr());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getZgcs());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getZgqx());
            cell = row.createCell(m++);cell.setCellStyle(cellStyle); cell.setCellValue(tmp.getZgzt());
            lastRow++;
            xh++;
        }
    }

    /**
     * 获取规范建设 月度检查记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjGfjsYdjcjlService.selectSjGfjsYdjcjlById(id));
    }

    /**
     * 新增规范建设 月度检查记录
     */
    @Log(title = "规范建设 月度检查记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjGfjsYdjcjl sjGfjsYdjcjl)
    {
        sjGfjsYdjcjl.setJcjb("基层单位自查");
        sjGfjsYdjcjl.setYl3(sjGfjsYdjcjl.getDeptId());
        return toAjax(sjGfjsYdjcjlService.insertSjGfjsYdjcjl(sjGfjsYdjcjl));
    }

    /**
     * 修改规范建设 月度检查记录
     */
    @Log(title = "规范建设 月度检查记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjGfjsYdjcjl sjGfjsYdjcjl)
    {
        sjGfjsYdjcjl.setJcjb("基层单位自查");
        sjGfjsYdjcjl.setYl3(sjGfjsYdjcjl.getDeptId());
        return toAjax(sjGfjsYdjcjlService.updateSjGfjsYdjcjl(sjGfjsYdjcjl));
    }

    /**
     * 删除规范建设 月度检查记录
     */
    @Log(title = "规范建设 月度检查记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(sjGfjsYdjcjlService.deleteSjGfjsYdjcjlByIds(ids));
    }


    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, SjGfjsYdjcjl jl) 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<SjGfjsZsdwwtcj> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 ){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjGfjsZsdwwtcj zsdwwtcj=new SjGfjsZsdwwtcj();
                System.out.println(row);
                //日期
                String rq = jl.getRq();
                if(StringUtils.isEmpty(rq)){
                    return AjaxResult.error("导入失败，日期不能为空，请在录入界面中选择日期");
                }

                Date date = DateUtils.parseDate(rq);
                if(date==null){
                    return AjaxResult.error("导入失败，日期格式错误");
                }
                zsdwwtcj.setRq(DateUtils.parseDateToStr("yyyy-MM",date));
                //单位
                Long dw = jl.getDeptId();
                if(dw == null){
                    return AjaxResult.error("导入失败，单位不能为空，请在录入界面中选择单位");
                }
                zsdwwtcj.setDeptId(jl.getDeptId());
                zsdwwtcj.setYl3(jl.getDeptId());
                //问题描述
                String wtms=new DataFormatter().formatCellValue(row.getCell(1)) ;
                if(StringUtils.isEmpty(wtms)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行问题描述不能为空");
                }
                zsdwwtcj.setWtmc(wtms);
                //考核内容
                String khnr=new DataFormatter().formatCellValue(row.getCell(2)) ;
                if(StringUtils.isEmpty(khnr)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行实施路径不能为空");
                }
                zsdwwtcj.setKhnr(khnr);
                //考核项点
                String khxd=new DataFormatter().formatCellValue(row.getCell(3)) ;
                if(StringUtils.isEmpty(khxd)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行重点工作不能为空");
                }
                zsdwwtcj.setKhxd(khxd);
                String pjbz=new DataFormatter().formatCellValue(row.getCell(4)) ;
                if(StringUtils.isEmpty(pjbz)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行主要工作要求不能为空");
                }
                //匹配评价标准
                String substring = pjbz.substring(6);
                long l = Long.parseLong(substring);
                SjGfjsZdgzCb sjGfjsZdGzCb=new SjGfjsZdgzCb();
                sjGfjsZdGzCb.setKhxd(khxd);
                sjGfjsZdGzCb.setKhnr(khnr);
                sjGfjsZdGzCb.setPx(l);
                sjGfjsZdGzCb.setNd(jl.getRq().substring(0,4));
                SjGfjsZdgzCb cb=sjGfjsZdgzMapper.selectSjGfjsZdgzCb(sjGfjsZdGzCb);
                if(cb==null){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行未匹配到主要工作要求");
                }
                zsdwwtcj.setPjbzid(cb.getId()+"");
                zsdwwtcj.setPjbzmc(cb.getPjbz());
                String zgzrr=new DataFormatter().formatCellValue(row.getCell(5)) ;
                zsdwwtcj.setZgzrr(zgzrr);
                String zgcs=new DataFormatter().formatCellValue(row.getCell(6)) ;
                zsdwwtcj.setZgcs(zgcs);
                String zgqx=new DataFormatter().formatCellValue(row.getCell(7)) ;
                zsdwwtcj.setZgqx(zgqx);
                String zgzt=new DataFormatter().formatCellValue(row.getCell(8)) ;
                zsdwwtcj.setZgzt(zgzt);
                zsdwwtcj.setJcjb("基层单位自查");
                zsdwwtcj.setCreateTime(DateUtils.getNowDate());
                zsdwwtcj.setCreateBy(SecurityUtils.getUsername());
                list.add(zsdwwtcj);
            }
            if(list.size()>0){
//                sjGfjsYdjcjlService.batchSave(list);
                return AjaxResult.success(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

        } finally {
            workbook.close();
        }
        return AjaxResult.success("导入失败");
    }


    @Log(title = "规范建设 月度检查记录提交", businessType = BusinessType.UPDATE)
    @PostMapping("/tj")
    public AjaxResult tj(SjGfjsYdjcjl ydjl)
    {
        return toAjax(sjGfjsYdjcjlService.tjSjGfjsYdjcjl(ydjl));
    }


}
