package com.ruoyi.powerdistribution.controller;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.powerdistribution.util.ImportExcelHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.powerdistribution.domain.PdmStopTarge;
import com.ruoyi.powerdistribution.service.IPdmStopTargeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 停电预算Controller
 *
 * @author ruoyi
 * @date 2024-12-09
 */
@RestController
@Api(value = "PdmStopTargeController", tags = "停电预算(目标展板)")
@RequestMapping("/power/stopTarge")
public class PdmStopTargeController extends BaseController
{
    @Autowired
    private IPdmStopTargeService pdmStopTargeService;

    /**
     * 查询停电预算列表
     */
    @ApiOperation(value = "查询停电预算列表")
    @PreAuthorize("@ss.hasPermi('system:targe:list')")
    @GetMapping("/list")
    public TableDataInfo list(PdmStopTarge pdmStopTarge)
    {
        startPage();
        List<PdmStopTarge> list = pdmStopTargeService.selectPdmStopTargeList(pdmStopTarge);
        return getDataTable(list);
    }

    /**
     * 导出停电预算列表
     */
    @PreAuthorize("@ss.hasPermi('system:targe:export')")
    @Log(title = "停电预算", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PdmStopTarge pdmStopTarge)
    {
        List<PdmStopTarge> list = pdmStopTargeService.selectPdmStopTargeList(pdmStopTarge);
        ExcelUtil<PdmStopTarge> util = new ExcelUtil<PdmStopTarge>(PdmStopTarge.class);
        util.exportExcel(response, list, "停电预算数据");
    }

    /**
     * 获取停电预算详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:targe:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(pdmStopTargeService.selectPdmStopTargeById(id));
    }

    /**
     * 新增停电预算
     */
    @PreAuthorize("@ss.hasPermi('system:targe:add')")
    @Log(title = "停电预算", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody PdmStopTarge pdmStopTarge)
    {
        return toAjax(pdmStopTargeService.insertPdmStopTarge(pdmStopTarge));
    }

    /**
     * 修改停电预算
     */
    @PreAuthorize("@ss.hasPermi('system:targe:edit')")
    @Log(title = "停电预算", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult edit(@RequestBody PdmStopTarge pdmStopTarge)
    {
        return toAjax(pdmStopTargeService.updatePdmStopTarge(pdmStopTarge));
    }

    /**
     * 删除停电预算
     */
    @PreAuthorize("@ss.hasPermi('system:targe:remove')")
    @Log(title = "停电预算", businessType = BusinessType.DELETE)
	@GetMapping("delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(pdmStopTargeService.deletePdmStopTargeByIds(ids));
    }

    @PostMapping("/downloadTemplate")
    @ApiOperation(value = "停电预算下载模板")
    public void downloadTemplate(HttpServletResponse response) {
        String filePath = "excelTemplate/stopTarget.xlsx";//未完成
        byte[] buffer = new byte[1024];
        InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
        BufferedInputStream bis = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + URLEncoder.encode(UUID.fastUUID().toString(), "UTF-8"));
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bis.close();
                fis.close();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 导入excel
     * @param file
     * @param reportYear
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    @ApiOperation(value = "停电预算导入", notes = "停电预算导入")
    public R invoiceImport(@RequestParam("file") MultipartFile file,@RequestParam("reportYear") String reportYear) throws IOException {
        ImportExcelHelper<PdmStopTarge> helper = new ImportExcelHelper<>();
        List<PdmStopTarge> list = helper.getList(file.getInputStream(), PdmStopTarge.class, 0, 2);
        boolean resultFlag = pdmStopTargeService.batchSaveOrUpdate(list,reportYear);
        if(resultFlag){
            return R.ok("导入成功");
        }
        return R.fail("导入失败");

    }
}
