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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.jxiop.api.dto.HouseholdPvDto;
import com.yeejoin.amos.boot.module.jxiop.api.dto.HouseholdPvExport;
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 com.yeejoin.amos.boot.module.jxiop.biz.service.impl.HouseholdPvServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

/**
 * 户用光伏表
 *
 * @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.save(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.update(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.getBySeq(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(@RequestPart("file") MultipartFile multipartFile) throws Exception {
        try {
            List<HouseholdPvImport> list = ExcelUtil.readFirstSheetExcel(multipartFile, HouseholdPvImport.class, 2);
            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 exportMessage(HttpServletResponse response, HouseholdPvDto dto) throws IOException {
        try {
            ClassPathResource cpr = new ClassPathResource("templates/householdExport.xls");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            //这里作为演示，造几个演示数据，模拟数据库里查数据
            List<HouseholdPvExport> list = iHouseholdPvService.selectExportList(dto);
            //基础信息
            list.forEach(item -> {
                // 当前获取最后一行
                int lastRowNum = sheet.getLastRowNum() + 1;
                Row row = sheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(ObjectUtils.isEmpty(item.getPlatformCompanyId()) ? "" : item.getPlatformCompanyId());
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getNumber()) ? "" : item.getNumber());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getExpiryTime()) ? "" : item.getExpiryTime());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getIssuingAuthority()) ? "" : item.getIssuingAuthority());
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getResidenceAddress()) ? "" : item.getResidenceAddress());
                row.createCell(8).setCellValue(ObjectUtils.isEmpty(item.getPhone()) ? "" : item.getPhone());
                row.createCell(9).setCellValue(ObjectUtils.isEmpty(item.getAddress()) ? "" : item.getAddress());
                row.createCell(10).setCellValue(ObjectUtils.isEmpty(item.getPostcode()) ? "" : item.getPostcode());
                row.createCell(11).setCellValue(ObjectUtils.isEmpty(item.getServiceAddress()) ? "" : item.getServiceAddress());
                row.createCell(12).setCellValue(ObjectUtils.isEmpty(item.getContactNumber()) ? "" : item.getContactNumber());
                row.createCell(13).setCellValue(ObjectUtils.isEmpty(item.getPeriod()) ? "" : item.getPeriod());
                row.createCell(14).setCellValue(ObjectUtils.isEmpty(item.getDescription()) ? "" : item.getDescription());
                row.createCell(15).setCellValue(ObjectUtils.isEmpty(item.getEquipmentMessage()) ? "" : item.getEquipmentMessage());
                row.createCell(16).setCellValue(ObjectUtils.isEmpty(item.getInstallAddress()) ? "" : item.getInstallAddress());
                row.createCell(17).setCellValue(ObjectUtils.isEmpty(item.getInstallDate()) ? "" : item.getInstallDate());
                row.createCell(18).setCellValue(ObjectUtils.isEmpty(item.getEstimatedPower()) ? "" : item.getEstimatedPower());
                row.createCell(19).setCellValue(ObjectUtils.isEmpty(item.getMonolithicPower()) ? "" : item.getMonolithicPower());
                row.createCell(20).setCellValue(ObjectUtils.isEmpty(item.getInstallCount()) ? "" : item.getInstallCount());
                row.createCell(21).setCellValue(ObjectUtils.isEmpty(item.getActualCapacity()) ? "" : item.getActualCapacity());
                row.createCell(22).setCellValue(ObjectUtils.isEmpty(item.getStationType()) ? "" : item.getStationType());
                row.createCell(23).setCellValue(ObjectUtils.isEmpty(item.getModuleType()) ? "" : item.getModuleType());
                row.createCell(24).setCellValue(ObjectUtils.isEmpty(item.getInstallStation()) ? "" : item.getInstallStation());
                row.createCell(25).setCellValue(ObjectUtils.isEmpty(item.getInstallDescription()) ? "" : item.getInstallDescription());

            });
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=\"" + URLEncoder.encode("户用光伏信息.xls", "UTF-8") + "\"");
            workbook.write(response.getOutputStream());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }


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