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.EquipMessageExport;
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.service.IHouseholdPvService;
import com.yeejoin.amos.boot.module.jxiop.api.util.CommonResponse;
import com.yeejoin.amos.boot.module.jxiop.api.util.CommonResponseUtil;
import com.yeejoin.amos.boot.module.jxiop.api.util.FileUtil;
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.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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 CommonResponse save(@RequestBody HouseholdPvDto model) {
        Integer count = householdPvServiceImpl.countRepeat(model, "add");
        if (count > 0){
            return CommonResponseUtil.failure("户号已经存在");
        }
        model = householdPvServiceImpl.save(model);
        return CommonResponseUtil.success(model);
    }

    /**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PutMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新户用光伏表", notes = "根据sequenceNbr更新户用光伏表")
    public CommonResponse updateBySequenceNbrHouseholdPv(@RequestBody HouseholdPvDto model, @PathVariable(value = "sequenceNbr") Long sequenceNbr) {
        model.setSequenceNbr(sequenceNbr);
        Integer count = householdPvServiceImpl.countRepeat(model, "upd");
        if (count > 0){
            return CommonResponseUtil.failure("户号已经存在");
        }
        return CommonResponseUtil.success(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<HouseholdPvDto>> queryForPage(@RequestParam(value = "current") String current,
                                                          @RequestParam(value = "size") String size,
                                                          HouseholdPvDto dto) {
        Page<HouseholdPvDto> 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) {
        FileUtil.downloadResource("户用光伏导入模板.xlsx", "templates/householdTemplates.xls", response);
    }


    @PostMapping(value = "/importData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST", value = "基础数据导入", notes = "基础数据导入")
    public CommonResponse importData(@RequestPart("file") MultipartFile multipartFile) throws Exception {
        CommonResponse commonResponse = new CommonResponse();
        try {
            List<HouseholdPvImport> list = ExcelUtil.readFirstSheetExcel(multipartFile, HouseholdPvImport.class, 2);
            commonResponse =  iHouseholdPvService.importData(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return commonResponse;
    }



    @GetMapping(value = "/exportDataOld")
    @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, dto.getIds());
            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.getDistrictId()) ? "" : item.getDistrictId());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getNumber()) ? "" : item.getNumber());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getSex()) ? "" : item.getSex());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getExpiryTime()) ? "" : item.getExpiryTime());
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getIssuingAuthority()) ? "" : item.getIssuingAuthority());
                row.createCell(8).setCellValue(ObjectUtils.isEmpty(item.getResidenceAddress()) ? "" : item.getResidenceAddress());
                row.createCell(9).setCellValue(ObjectUtils.isEmpty(item.getPhone()) ? "" : item.getPhone());
                row.createCell(10).setCellValue(ObjectUtils.isEmpty(item.getAddress()) ? "" : item.getAddress());
                row.createCell(11).setCellValue(ObjectUtils.isEmpty(item.getPostcode()) ? "" : item.getPostcode());
                row.createCell(12).setCellValue(ObjectUtils.isEmpty(item.getServiceAddress()) ? "" : item.getServiceAddress());
                row.createCell(13).setCellValue(ObjectUtils.isEmpty(item.getContactNumber()) ? "" : item.getContactNumber());
                row.createCell(14).setCellValue(ObjectUtils.isEmpty(item.getPeriod()) ? "" : item.getPeriod());
                row.createCell(15).setCellValue(ObjectUtils.isEmpty(item.getDescription()) ? "" : item.getDescription());
                row.createCell(16).setCellValue(ObjectUtils.isEmpty(item.getGenerationNumber()) ? "" : item.getGenerationNumber());
                row.createCell(17).setCellValue(ObjectUtils.isEmpty(item.getEquipmentMessage()) ? "" : item.getEquipmentMessage());
                row.createCell(18).setCellValue(ObjectUtils.isEmpty(item.getInstallAddress()) ? "" : item.getInstallAddress());
                row.createCell(19).setCellValue(ObjectUtils.isEmpty(item.getInstallDate()) ? "" : item.getInstallDate());
                row.createCell(20).setCellValue(ObjectUtils.isEmpty(item.getEstimatedPower()) ? "" : item.getEstimatedPower());
                row.createCell(21).setCellValue(ObjectUtils.isEmpty(item.getMonolithicPower()) ? "" : item.getMonolithicPower());
                row.createCell(22).setCellValue(ObjectUtils.isEmpty(item.getInstallCount()) ? "" : item.getInstallCount());
                row.createCell(23).setCellValue(ObjectUtils.isEmpty(item.getActualCapacity()) ? "" : item.getActualCapacity());
                row.createCell(24).setCellValue(ObjectUtils.isEmpty(item.getStationType()) ? "" : item.getStationType());
                row.createCell(25).setCellValue(ObjectUtils.isEmpty(item.getModuleType()) ? "" : item.getModuleType());
                row.createCell(26).setCellValue(ObjectUtils.isEmpty(item.getInverterSerialNumber()) ? "" : item.getInverterSerialNumber());
                row.createCell(27).setCellValue(ObjectUtils.isEmpty(item.getInstallStation()) ? "" : item.getInstallStation());
                row.createCell(28).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();
        }
    }

    /**
     * 验收信息
     * @param response
     * @param dto
     * @throws IOException
     */
    @GetMapping(value = "/exportData")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "数据导出", notes = "数据导出")
    public void exportMessageNew(HttpServletResponse response, HouseholdPvDto dto) throws IOException {
        try {
            ClassPathResource cpr = new ClassPathResource("templates/householdExportNew.xls");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            Sheet sheet = workbook.getSheetAt(0);
            List<HouseholdPvExport> list = iHouseholdPvService.selectExportList(dto, dto.getIds());
            // 序号
            int num = 1;
            for (HouseholdPvExport item : list) {
                // 获取当前插入数据行号
                int lastRowNum = sheet.getLastRowNum() + 1;
                Row row = sheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(num);
                num++;
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getNumber()) ? "" : item.getNumber());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getPhone()) ? "" : item.getPhone());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getInstallAddress()) ? "" : item.getInstallAddress());
                // 安装总功率
                //updateTime: 2023年9月22日 14点26分
                //desc：客户提出导出时该值由原来的 预计功率*安装数量 修改为 组件单片功率 * 安装数量
                //changer: 曹涛
//                if (!ObjectUtils.isEmpty(item)&& !ObjectUtils.isEmpty(item.getActualCapacity()) && !ObjectUtils.isEmpty(item.getInstallCount())) {
//                    long multiplyExact = Math.multiplyExact(Long.parseLong(item.getActualCapacity()), Long.parseLong(item.getInstallCount()));
//                    row.createCell(6).setCellValue(String.valueOf(multiplyExact));
                if (!ObjectUtils.isEmpty(item)&& !ObjectUtils.isEmpty(item.getMonolithicPower()) && !ObjectUtils.isEmpty(item.getInstallCount())) {
                    long multiplyExact = Math.multiplyExact(Long.parseLong(item.getMonolithicPower()), Long.parseLong(item.getInstallCount()));
                    row.createCell(6).setCellValue(String.valueOf(multiplyExact));
                } else {
                    row.createCell(6).setCellValue(0);
                }
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getContactNumber()) ? "" : item.getContactNumber());
                row.createCell(8).setCellValue(ObjectUtils.isEmpty(item.getGenerationNumber()) ? "" : item.getGenerationNumber());
                row.createCell(9).setCellValue(ObjectUtils.isEmpty(item.getInverterSerialNumber()) ? "" : item.getInverterSerialNumber());
            }
            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();
        }
    }


    /**
     * 导出户用光伏运维信息（基本信息、合同信息、设备信息、租赁物信息）
     * @param response
     * @param dto
     * @throws IOException
     */
    @GetMapping(value = "/exportDataAll")
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET", value = "数据导出", notes = "数据导出")
    public void exportMessageAll(HttpServletResponse response, HouseholdPvDto dto) throws IOException {
        try {
            ClassPathResource cpr = new ClassPathResource("templates/householdExportAll.xls");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new XSSFWorkbook(is);
            // 基础信息
            Sheet sheet = workbook.getSheetAt(0);
            Sheet contactSheet = workbook.getSheetAt(1);
            Sheet equipSheet = workbook.getSheetAt(2);
            Sheet leaseSheet = workbook.getSheetAt(3);
            List<HouseholdPvExport> list = iHouseholdPvService.selectExportList(dto, dto.getIds());
            // 序号
            int num = 1;
            for (HouseholdPvExport item : list) {
                // 获取当前插入数据行号
                int lastRowNum = sheet.getLastRowNum() + 1;
                Row row = sheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(num);
                num++;
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getPlatformCompanyId()) ? "" : item.getPlatformCompanyId());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getDistrictId()) ? "" : item.getDistrictId());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getNumber()) ? "" : item.getNumber());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getSex()) ? "" : item.getSex());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getIsPermanently()) ? "" : item.getIsPermanently());
                row.createCell(8).setCellValue(ObjectUtils.isEmpty(item.getExpiryTime()) ? "" : item.getExpiryTime());
                row.createCell(9).setCellValue(ObjectUtils.isEmpty(item.getIssuingAuthority()) ? "" : item.getIssuingAuthority());
                row.createCell(10).setCellValue(ObjectUtils.isEmpty(item.getResidenceAddress()) ? "" : item.getResidenceAddress());
                row.createCell(11).setCellValue(ObjectUtils.isEmpty(item.getPhone()) ? "" : item.getPhone());
                row.createCell(12).setCellValue(ObjectUtils.isEmpty(item.getAddress()) ? "" : item.getAddress());
                row.createCell(13).setCellValue(ObjectUtils.isEmpty(item.getPostcode()) ? "" : item.getPostcode());
            }
            // 合同信息
            num = 1;
            for (HouseholdPvExport item : list) {
                // 获取当前插入数据行号
                int lastRowNum = contactSheet.getLastRowNum() + 1;
                Row row = contactSheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(num);
                num++;
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getContactNumber()) ? "" : item.getContactNumber());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getPeriod()) ? "" : item.getPeriod());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getDescription()) ? "" : item.getDescription());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getGenerationNumber()) ? "" : item.getGenerationNumber());
            }
            // 设备信息
            List<EquipMessageExport> equipMessage = iHouseholdPvService.selectExportEquipMessage(dto, dto.getIds());
            for (EquipMessageExport item : equipMessage) {
                // 获取当前插入数据行号
                int lastRowNum = equipSheet.getLastRowNum() + 1;
                Row row = equipSheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(item.getNumSort());
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getType()) ? "" : item.getType());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getEquipName()) ? "" : item.getEquipName());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getBrand()) ? "" : item.getBrand());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getSnCode()) ? "" : item.getSnCode());
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getDescription()) ? "" : item.getDescription());
            }
            // 租赁物信息
            num = 1;
            for (HouseholdPvExport item : list) {
                // 获取当前插入数据行号
                int lastRowNum = leaseSheet.getLastRowNum() + 1;
                Row row = leaseSheet.createRow((short) (lastRowNum));
                row.createCell(0).setCellValue(num);
                num++;
                row.createCell(1).setCellValue(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
                row.createCell(2).setCellValue(ObjectUtils.isEmpty(item.getIdNumber()) ? "" : item.getIdNumber());
                row.createCell(3).setCellValue(ObjectUtils.isEmpty(item.getInstallAddress()) ? "" : item.getInstallAddress());
                row.createCell(4).setCellValue(ObjectUtils.isEmpty(item.getInstallDate()) ? "" : item.getInstallDate());
                row.createCell(5).setCellValue(ObjectUtils.isEmpty(item.getEstimatedPower()) ? "" : item.getEstimatedPower());
                row.createCell(6).setCellValue(ObjectUtils.isEmpty(item.getMonolithicPower()) ? "" : item.getMonolithicPower());
                row.createCell(7).setCellValue(ObjectUtils.isEmpty(item.getInstallCount()) ? "" : item.getInstallCount());
                row.createCell(8).setCellValue(ObjectUtils.isEmpty(item.getActualCapacity()) ? "" : item.getActualCapacity());
                row.createCell(9).setCellValue(ObjectUtils.isEmpty(item.getStationType()) ? "" : item.getStationType());
                row.createCell(10).setCellValue(ObjectUtils.isEmpty(item.getModuleType()) ? "" : item.getModuleType());
                row.createCell(11).setCellValue(ObjectUtils.isEmpty(item.getInverterSerialNumber()) ? "" : item.getInverterSerialNumber());

            }
            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");
    }


}
