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.SjGfjsZdgzCb;
import com.qianhe.domain.SjGfjsZsdwwtcj;
import com.qianhe.mapper.SjGfjsZdgzMapper;
import com.qianhe.service.ISjGfjsBfzwhService;
import com.qianhe.service.ISjGfjsBfzjcService;
import com.qianhe.system.mapper.SysDeptMapper;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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.Date;
import java.util.List;

/**
 * 规范建设-帮扶组检查Controller
 *
 * @author qianhe
 * @date 2024-07-23
 */
@RestController
@RequestMapping("/system/sjGfjsBfzjc")
public class SjGfjsBfzjcController extends BaseController
{
    @Autowired
    private ISjGfjsBfzjcService sjGfjsJcdwwtcjService;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SjGfjsZdgzMapper sjGfjsZdgzMapper;

    @Autowired
    private ISjGfjsBfzwhService sjGfjsBfzwhService;
    /**
     * 查询规范建设-帮扶组检查列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SjGfjsZsdwwtcj sjGfjsZsdwwtcj)
    {
        sjGfjsZsdwwtcj.setJcjb("帮扶组检查");
        List<SjGfjsZsdwwtcj> list = sjGfjsJcdwwtcjService.selectSjGfjsZsdwwtcjList(sjGfjsZsdwwtcj);
        return getDataTable(list);
    }

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

    }

    /**
     * 获取规范建设-帮扶组检查详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjGfjsJcdwwtcjService.selectSjGfjsZsdwwtcjById(id));
    }

    /**
     * 新增规范建设-帮扶组检查
     */
    @Log(title = "规范建设-帮扶组检查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjGfjsZsdwwtcj sjGfjsZsdwwtcj)
    {
        sjGfjsZsdwwtcj.setJcjb("帮扶组检查");
        return toAjax(sjGfjsJcdwwtcjService.insertSjGfjsZsdwwtcj(sjGfjsZsdwwtcj));
    }

    /**
     * 修改规范建设-帮扶组检查
     */
    @Log(title = "规范建设-帮扶组检查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjGfjsZsdwwtcj sjGfjsZsdwwtcj)
    {
        sjGfjsZsdwwtcj.setJcjb("帮扶组检查");
        return toAjax(sjGfjsJcdwwtcjService.updateSjGfjsZsdwwtcj(sjGfjsZsdwwtcj));
    }

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

        return toAjax(sjGfjsJcdwwtcjService.deleteSjGfjsZsdwwtcjByIds(ids));
    }


    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, SjGfjsZsdwwtcj sjGfjsZsdwwtcj) 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 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjGfjsZsdwwtcj zsdwwtcj=new SjGfjsZsdwwtcj();
                System.out.println(row);
                //日期
                String rq=new DataFormatter().formatCellValue(row.getCell(1));
                if(StringUtils.isEmpty(rq)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行日期不能为空");
                }

                Date date = DateUtils.parseDate(rq);
                if(date==null){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行日期格式错误");
                }
                zsdwwtcj.setRq(DateUtils.parseDateToStr("yyyy-MM",date));
                //单位
                String dw=new DataFormatter().formatCellValue(row.getCell(2)) ;
                if(StringUtils.isEmpty(dw)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行单位不能为空");
                }
                //查询单位id
                String[] split = dw.split("/");
                if(split.length<2){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行输入的单位格式有误!");
                }
                String ejdw=split[0];
                SysDept ejdept = deptList.stream().filter(dept -> dept.getDeptName().equals(ejdw)).findFirst().orElse(null);
                if(ejdept==null){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行未匹配到二级单位");
                }
                String sjdw=split[1];
                SysDept sjdept = deptList.stream().filter(dept -> dept.getDeptName().equals(sjdw) && dept.getParentId().equals(ejdept.getDeptId())).findFirst().orElse(null);
                if(sjdept==null){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行未匹配到三级单位");
                }
                zsdwwtcj.setDeptId(sjdept.getDeptId());

                //考核内容
                String khnr=new DataFormatter().formatCellValue(row.getCell(3)) ;
                if(StringUtils.isEmpty(khnr)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行实施路径不能为空");
                }
                zsdwwtcj.setKhnr(khnr);
                //考核项点
                String khxd=new DataFormatter().formatCellValue(row.getCell(4)) ;
                if(StringUtils.isEmpty(khxd)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行重点工作不能为空");
                }
                zsdwwtcj.setKhxd(khxd);

                //问题描述
                String wtms=new DataFormatter().formatCellValue(row.getCell(5)) ;
                if(StringUtils.isEmpty(wtms)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行问题描述不能为空");
                }
                zsdwwtcj.setWtmc(wtms);

                String ldnr=new DataFormatter().formatCellValue(row.getCell(6)) ;
                zsdwwtcj.setLdnr(ldnr);
                String zgzrr=new DataFormatter().formatCellValue(row.getCell(7)) ;
                zsdwwtcj.setZgzrr(zgzrr);
                String zgcs=new DataFormatter().formatCellValue(row.getCell(8)) ;
                zsdwwtcj.setZgcs(zgcs);
                String zgqx=new DataFormatter().formatCellValue(row.getCell(9)) ;
                zsdwwtcj.setZgqx(zgqx);
                String zgzt=new DataFormatter().formatCellValue(row.getCell(10)) ;
                zsdwwtcj.setZgzt(zgzt);
                zsdwwtcj.setJcjb("帮扶组检查");
                zsdwwtcj.setCreateTime(DateUtils.getNowDate());
                zsdwwtcj.setCreateBy(SecurityUtils.getUsername());
                zsdwwtcj.setYl3(sjGfjsZsdwwtcj.getYl3());
                list.add(zsdwwtcj);
            }
            if(list.size()>0){
                sjGfjsJcdwwtcjService.batchSave(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

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


    /**
     * 查询规范建设-帮扶组检查列表
     */
    @GetMapping("/list_bfz")
    public TableDataInfo list_bfz(SjGfjsZsdwwtcj sjGfjsZsdwwtcj)
    {
        sjGfjsZsdwwtcj.setJcjb("帮扶组检查");
        List<SjGfjsZsdwwtcj> list = sjGfjsJcdwwtcjService.selectSjGfjsZsdwwtcjList_bfz(sjGfjsZsdwwtcj);
        return getDataTable(list);
    }





    //批量提交 ids
    @Log(title = "批量提交 帮扶组检查", businessType = BusinessType.UPDATE)
    @PostMapping("/pltj")
    public AjaxResult pltj(@RequestBody SjGfjsZsdwwtcj fjx)
    {
        fjx.setZt("1");
        return toAjax(sjGfjsJcdwwtcjService.plxg(fjx));
    }



}
