package com.ruoyi.system.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.util.PoitlIOUtils;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysPlan;
import com.ruoyi.system.domain.SysReport;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysPlanService;
import com.ruoyi.system.service.ISysReportService;
import com.ruoyi.system.service.impl.SysDictDataServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-06-20
 */
@RestController
@RequestMapping("/system/report")
public class SysReportController extends BaseController
{
    @Autowired
    private ISysReportService sysReportService;
    @Autowired
    private ISysPlanService sysPlanService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询【请填写功能名称】列表
     */

    @GetMapping("/list")
    public TableDataInfo list(SysReport sysReport)
    {
        startPage();
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId())){

        }else{
            sysReport.setClashId(SecurityUtils.getLoginUser().getDeptId()+"");

        }

        sysReport.setIsMerge("-1");
        List<SysReport> list = sysReportService.selectSysReportList(sysReport);
        return getDataTable(list);
    }


    @GetMapping("/clashList")
    public TableDataInfo clashList(SysReport sysReport)
    {
        List<SysReport> list = sysReportService.selectSysReportList(sysReport);
        return getDataTable(list);
    }
    /**
     * 导出【请填写功能名称】列表
     */

    @Log(title = "施工报备导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HttpServletRequest request, SysReport sysReport)
    {

         String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/template/";
        String templatePath =path+"report.docx";

        List<SysReport> list = sysReportService.selectSysReportList(sysReport);
        if(list.size()<1)  AjaxResult.error("不存在！");;
        list.get(0);
        SysPlan plan = sysPlanService.selectSysPlanById(list.get(0).getPlanId());
        SysDictData dictData =new SysDictData();dictData.setDictType("content_one");
        List<SysDictData> onedatalist = sysDictDataService.selectDictDataList(dictData);
        Map<String,String> onemap = new HashMap<>();
        for (SysDictData d:onedatalist
             ) {
            onemap.put(d.getDictValue(),d.getDictLabel());
        }
        dictData.setDictType("content_two");
        List<SysDictData> twodatalist = sysDictDataService.selectDictDataList(dictData);
        Map<String,String> twomap = new HashMap<>();
        for (SysDictData d:twodatalist
        ) {
            twomap.put(d.getDictValue(),d.getDictLabel());
        }

//        ExcelUtil<SysReport> util = new ExcelUtil<SysReport>(SysReport.class);
//        util.exportExcel(response, list, "数据");
        try{
            XWPFTemplate template = XWPFTemplate.compile(templatePath).render(
                    new HashMap<String, Object>(){{
                        put("date", DateUtils.parseDateToStr("yyyy年MM月dd日",list.get(0).getCreateTime()));
                        put("name", plan.getName());
                        put("length", plan.getBridgeHeightWidth());
                        put("dengji", plan.getLevel());
                        put("luduan", list.get(0).getSection()+("K"+ (list.get(0).getStartKm()==null?list.get(0).getStartKm():"0" )+"+"+(list.get(0).getStartHectometer()==null?list.get(0).getStartHectometer():"000" )+" ~ K"+ (list.get(0).getEndKm()==null?list.get(0).getEndKm():"0")+"+"+(list.get(0).getEndHectometer()==null?list.get(0).getEndHectometer():"000" )));
                        put("content",(list.get(0).getContentOne()==null?"":onemap.get( list.get(0).getContentOne())) +(list.get(0).getContentTwo()==null?"":twomap.get( list.get(0).getContentTwo())) );
                        put("daterange", DateUtils.parseDateToStr("yyyy年MM月dd日hh:mm:ss",list.get(0).getStartTime())+" 至 "+DateUtils.parseDateToStr("yyyy年MM月dd日hh:mm:ss",list.get(0).getEndTime()));
                        put("danwei", list.get(0).getDept());
                        put("shuoming", list.get(0).getContentDes());
                    }});


            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");

            OutputStream out = response.getOutputStream();

            template.write(out);
            out.flush();
            out.close();
            template.close();
        }catch (Exception e){

        }



    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sysReportService.selectSysReportById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysReport sysReport)
    {
        return toAjax(sysReportService.insertSysReport(sysReport));
    }

    /**
     * 修改【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysReport sysReport)
    {
        return toAjax(sysReportService.updateSysReport(sysReport));
    }

    /**
     * 删除【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sysReportService.deleteSysReportByIds(ids));
    }


    @GetMapping("collisionDetection/{ids}")
    public AjaxResult collisionDetection(@PathVariable Long[] ids)
    {
        return AjaxResult.success(sysReportService.collisionDetection(ids));
    }

    @GetMapping("mergeQuery/{ids}")
    public AjaxResult mergeQuery(@PathVariable Long[] ids)
    {
        return AjaxResult.success(sysReportService.mergeQuery(ids));
    }

    @GetMapping("mergeReport/{ids}")
    public AjaxResult mergeReport(@PathVariable Long[] ids)
    {
        try{
            return AjaxResult.success(sysReportService.mergeReport(ids));

        }catch (Error e){
            AjaxResult.error("所选报备无法合并！");
        }
        return AjaxResult.success();

    }
}
