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.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.qianhe.common.core.domain.entity.SysDept;
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.SjZdbfFjxbzCb;
import com.qianhe.domain.SjZdbfKhpjbzCb;
import com.qianhe.domain.SjZdbfZsdwwtcj;
import com.qianhe.mapper.SjZdbfFjxbzMapper;
import com.qianhe.mapper.SjZdbfZsdwfjxcjMapper;
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.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.domain.SjZdbfZsdwfjxcj;
import com.qianhe.service.ISjZdbfZsdwfjxcjService;
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/sjZdbfZsdwfjxcj")
public class SjZdbfZsdwfjxcjController extends BaseController
{
    @Autowired
    private ISjZdbfZsdwfjxcjService sjZdbfZsdwfjxcjService;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SjZdbfFjxbzMapper sjZdbfFjxbzMapper;
    /**
     * 查询指导帮扶-直属单位否决项采集列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:list')")
    @GetMapping("/list")
    public TableDataInfo list(SjZdbfZsdwfjxcj sjZdbfZsdwfjxcj)
    {
        startPage();
        List<SjZdbfZsdwfjxcj> list = sjZdbfZsdwfjxcjService.selectSjZdbfZsdwfjxcjList(sjZdbfZsdwfjxcj);
        return getDataTable(list);
    }

    /**
     * 导出指导帮扶-直属单位否决项采集列表
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:export')")
    @Log(title = "指导帮扶-直属单位否决项采集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SjZdbfZsdwfjxcj sjZdbfZsdwfjxcj)
    {
        Workbook exl = null;
        OutputStream out = null;
        InputStream in  = null;
        try {
            in =this.getClass().getResourceAsStream("/static/zsdwfjxcj.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();
                }
            }
        }
    }

    /**
     * 获取指导帮扶-直属单位否决项采集详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(sjZdbfZsdwfjxcjService.selectSjZdbfZsdwfjxcjById(id));
    }

    /**
     * 新增指导帮扶-直属单位否决项采集
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:add')")
    @Log(title = "指导帮扶-直属单位否决项采集", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SjZdbfZsdwfjxcj sjZdbfZsdwfjxcj)
    {
        return toAjax(sjZdbfZsdwfjxcjService.insertSjZdbfZsdwfjxcj(sjZdbfZsdwfjxcj));
    }

    /**
     * 修改指导帮扶-直属单位否决项采集
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:edit')")
    @Log(title = "指导帮扶-直属单位否决项采集", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SjZdbfZsdwfjxcj sjZdbfZsdwfjxcj)
    {
        return toAjax(sjZdbfZsdwfjxcjService.updateSjZdbfZsdwfjxcj(sjZdbfZsdwfjxcj));
    }

    /**
     * 删除指导帮扶-直属单位否决项采集
     */
    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj:remove')")
    @Log(title = "指导帮扶-直属单位否决项采集", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sjZdbfZsdwfjxcjService.deleteSjZdbfZsdwfjxcjByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('system:sjZdbfZsdwfjxcj: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<SjZdbfZsdwfjxcj> list=new ArrayList<>();
            // 通过循环，逐行取出表中每行数据
            for(int i=0;i<=lastRowNum;i++) {//跳过第一行和第二行
                if(i==0 || i==1){
                    continue;
                }
                // 获取行
                XSSFRow row = sheet.getRow(i);
                SjZdbfZsdwfjxcj zsdwwtcj=new SjZdbfZsdwfjxcj();
                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 jgbm=new DataFormatter().formatCellValue(row.getCell(2)) ;
                if(StringUtils.isEmpty(jgbm)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行机关部门不能为空");
                }
                String[] jgsplit = jgbm.split("/");
                if(jgsplit.length==1){
                    String bm=jgsplit[0]; // 部门
                    SysDept bmdept = deptList.stream().filter(dept -> dept.getDeptName().equals(bm)).findFirst().orElse(null);
                    if(bmdept==null){
                        return AjaxResult.error("导入失败，第"+(i+1)+"行，机关部门：未匹配到机关名称");
                    }
                    zsdwwtcj.setYl3(bmdept.getDeptId());
                }else{
                    String bm=jgsplit[0];// 部门
                    String ks=jgsplit[1];// 科室
                    SysDept bmdept = deptList.stream().filter(dept -> dept.getDeptName().equals(bm)).findFirst().orElse(null);
                    if(bmdept==null){
                        return AjaxResult.error("导入失败，第"+(i+1)+"行，机关部门：未匹配到机关名称");
                    }
                    SysDept ksdept = deptList.stream().filter(dept -> dept.getDeptName().equals(ks) && dept.getParentId().equals(bmdept.getDeptId())).findFirst().orElse(null);
                    if(ksdept==null){
                        return AjaxResult.error("导入失败，第"+(i+1)+"行，机关部门：未匹配到科室名称");
                    }
                    zsdwwtcj.setYl3(ksdept.getDeptId());
                }

                //受检单位
                String dw=new DataFormatter().formatCellValue(row.getCell(3)) ;
                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 flmc=new DataFormatter().formatCellValue(row.getCell(4)) ;
                if(StringUtils.isEmpty(flmc)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行否决项分类不能为空");
                }
                zsdwwtcj.setFlmc(flmc);
                //评价标准
                String pjbz=new DataFormatter().formatCellValue(row.getCell(5)) ;
                if(StringUtils.isEmpty(pjbz)){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行评价标准不能为空");
                }
                //匹配评价标准
                String substring = pjbz.substring(4);
                long l = Long.parseLong(substring);
                SjZdbfFjxbzCb sjZdbfFjxbzCb=new SjZdbfFjxbzCb();
                sjZdbfFjxbzCb.setFlmc(flmc);
                sjZdbfFjxbzCb.setPx(l);
                sjZdbfFjxbzCb.setNd(rq.substring(0,4));
                SjZdbfFjxbzCb cb=sjZdbfFjxbzMapper.selectSjZdbfFjxbzCb(sjZdbfFjxbzCb);
                if(cb==null){
                    return AjaxResult.error("导入失败，第"+(i+1)+"行未匹配到评价标准");
                }
                zsdwwtcj.setPjbzid(cb.getId()+"");
                zsdwwtcj.setPjbzmc(cb.getPjbz());
                String wtms=new DataFormatter().formatCellValue(row.getCell(6)) ;
                zsdwwtcj.setWtmc(wtms);
                zsdwwtcj.setCreateTime(DateUtils.getNowDate());
                zsdwwtcj.setCreateBy(SecurityUtils.getUsername());
                list.add(zsdwwtcj);
            }
            if(list.size()>0){
                sjZdbfZsdwfjxcjService.batchSave(list);
            }
        } catch (IOException e) {
            e.getMessage();
            e.printStackTrace();
            throw new BusinessException("导入Excel失败，请联系网站管理员！");

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