package com.yeejoin.amos.boot.module.jxiop.biz.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.module.jxiop.api.dto.HouseholdPvImport;
import com.yeejoin.amos.boot.module.jxiop.api.entity.HouseholdPv;
import com.yeejoin.amos.boot.module.jxiop.api.service.IHouseholdPvService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.HouseholdPvServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.jxiop.api.dto.HouseholdPvDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

/**
 * 户用光伏表
 *
 * @author system_generator
 * @date 2023-03-17
 */
@RestController
@Api(tags = "户用光伏表Api")
@RequestMapping(value = "/household-pv")
public class HouseholdPvController extends BaseController {

    @Autowired
    HouseholdPvServiceImpl householdPvServiceImpl;

    @Autowired
    IHouseholdPvService iHouseholdPvService;

    /**
     * 新增户用光伏表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "新增户用光伏表", notes = "新增户用光伏表")
    public ResponseModel<HouseholdPvDto> save(@RequestBody HouseholdPvDto model) {
        model = householdPvServiceImpl.createWithModel(model);
        return ResponseHelper.buildResponse(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新户用光伏表", notes = "根据sequenceNbr更新户用光伏表")
    public ResponseModel<HouseholdPvDto> updateBySequenceNbrHouseholdPv(@RequestBody HouseholdPvDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        model.setSequenceNbr(sequenceNbr);
        return ResponseHelper.buildResponse(householdPvServiceImpl.updateWithModel(model));
    }

    /**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除户用光伏表", notes = "根据sequenceNbr删除户用光伏表")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        return ResponseHelper.buildResponse(householdPvServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET", value = "根据sequenceNbr查询单个户用光伏表", notes = "根据sequenceNbr查询单个户用光伏表")
    public ResponseModel<HouseholdPvDto> selectOne(@PathVariable Long sequenceNbr) {
        return ResponseHelper.buildResponse(householdPvServiceImpl.queryBySeq(sequenceNbr));
    }

    /**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/page")
    @ApiOperation(httpMethod = "GET", value = "户用光伏表分页查询", notes = "户用光伏表分页查询")
    public ResponseModel<IPage<HouseholdPv>> queryForPage(@RequestParam(value = "current") String current,
                                                          @RequestParam(value = "size") String size,
                                                            HouseholdPvDto dto) {
        Page<HouseholdPv> page = new Page<>();
        page.setCurrent(Long.parseLong(current));
        page.setSize(Long.parseLong(size));
        return ResponseHelper.buildResponse(householdPvServiceImpl.queryForHouseholdPvPage(page, dto));
    }

    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "户用光伏表列表全部数据查询", notes = "户用光伏表列表全部数据查询")
    @GetMapping(value = "/list")
    public ResponseModel<List<HouseholdPvDto>> selectForList() {
        return ResponseHelper.buildResponse(householdPvServiceImpl.queryForHouseholdPvList());
    }


    @GetMapping(value = "/exportTemplates")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "模板下载", notes = "模板下载")
    public void exportTemplates(HttpServletResponse response) {
        DataInputStream in = null;
        OutputStream out = null;
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("模板.xlsx", "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            FileInputStream fileInputStream = new FileInputStream(new File("amos-boot-system-jxiop/amos-boot-module-jxiop-biz/src/main/resource/templates/householdTemplates.xls"));
            in = new DataInputStream(fileInputStream);
            out = response.getOutputStream();
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            response.reset();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @GetMapping(value = "/importData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "模板下载", notes = "模板下载")
    public ResponseModel<Object> importData(MultipartFile file) {
        try {
            ExcelReader reader = EasyExcelFactory.read(file.getInputStream()).build();
            List<HouseholdPvImport> list = ExcelUtil.readExcel(reader, HouseholdPvImport.class, 0);
            iHouseholdPvService.importData(list);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BadRequest(e.getMessage());
        }
        return ResponseHelper.buildResponse("ok");
    }


    @GetMapping(value = "/exportData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "数据导出", notes = "数据导出")
    public void exportData(HttpServletResponse response, HouseholdPvDto dto) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("组织机构信息.xlsx", "UTF-8"));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            ExcelWriter writer = EasyExcelFactory.write(response.getOutputStream(), HouseholdPvImport.class).build();
            WriteSheet sheet = EasyExcelFactory.writerSheet(0, String.valueOf(System.currentTimeMillis())).build();
            List<HouseholdPvImport> list = iHouseholdPvService.selectExportList(dto);
            writer.write(list, sheet);
            writer.finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping(value = "/deleteBatch")
    @ApiOperation(httpMethod = "POST", value = "批量删除", notes = "批量删除")
    public ResponseModel<Object> deleteBatch(@RequestBody List<Long> ids) {
        iHouseholdPvService.deleteBatch(ids);
        return ResponseHelper.buildResponse("ok");
    }
}
