package com.tofly.feesapi.mxcx.controller;

import com.tofly.common.core.util.StringUtil;
import com.tofly.feesapi.common.Excel.ExcleFileUtil;
import com.tofly.feesapi.common.core.ResultRespone;
import com.tofly.feesapi.common.core.dto.PageDto;
import com.tofly.feesapi.common.core.vo.PageResult;
import com.tofly.feesapi.common.exception.FeesErrorCode;
import com.tofly.feesapi.common.exception.FeesException;
import com.tofly.feesapi.common.util.ToolsUtils;
import com.tofly.feesapi.mxcx.entity.dto.*;
import com.tofly.feesapi.mxcx.entity.vo.*;
import com.tofly.feesapi.sfgl.entity.dto.YffYeSeachFilter;
import com.tofly.feesapi.sfgl.service.YyQfmxService;
import com.tofly.feesapi.sfgl.service.YySspjxxService;
import com.tofly.feesapi.yhgl.service.YhKhjbxxService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mxcx")
@Api(tags = "明细查询接口")
public class MxcxController {

    @Autowired
    private YhKhjbxxService yhKhjbxxService;
    @Autowired
    private YySspjxxService yySspjxxService;
    @Autowired
    private YyQfmxService yyQfmxService;

    @ApiOperation(value = "获取年度阶梯水量信息", tags = {"明细查询"})
    @GetMapping("/getNdjtslxx")
    public ResultRespone<PageResult<YhNdjtslSelect>> getNdjtslxx(@ModelAttribute PageDto pageDto, String yhbh) {
        return ResultRespone.success(yhKhjbxxService.getNdjtslxx(pageDto, yhbh));
    }

    @GetMapping("/exportNdjtslxx")
    @ApiOperation(value = "导出年度阶梯水量信息", tags = {"明细查询"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "exportFields", value = "Excel导出字段", dataType = "String", example = "yhbh,yhxm")
    })
    public void exportNdjtslxx(HttpServletResponse response, @ModelAttribute String yhbh
            , @ModelAttribute String exportFields) throws IOException {
        List<YhNdjtslSelect> list = yhKhjbxxService.getNdjtslxxlist(yhbh);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YhNdjtslSelect.class, "年度阶梯水量信息.xlsx", exportFields);
        }
    }

    @ApiOperation(value = "预付费预存明细查询", tags = {"明细查询"})
    @GetMapping("/yffycmxcx")
    public ResultRespone<PageResult<YffycmxcxSelect>> yffycmxcx(PageDto pageDto, @ModelAttribute YffYeSeachFilter filter) {
        return ResultRespone.success(yySspjxxService.yffycmxcx(pageDto, filter));
    }

    @GetMapping("/exporYffycmxcx")
    @ApiOperation(value = "导出预付费预存明细", tags = {"明细查询"})
    public void exporYffycmxcx(HttpServletResponse response, @ModelAttribute YffYeSeachFilter filter) throws IOException {
        List<YffycmxcxSelect> list = yySspjxxService.yffycmxcxlist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YffycmxcxSelect.class, "预付费预存明细.xlsx", filter.getExportFields());
        }
    }

    @ApiOperation(value = "预付费扣减明细查询", tags = {"明细查询"})
    @GetMapping("/yffkjmxcx")
    public ResultRespone<PageResult<YffkjmxcxSelect>> yffkjmxcx(PageDto pageDto, @ModelAttribute YffYeSeachFilter filter) {
        return ResultRespone.success(yySspjxxService.yffkjmxcx(pageDto, filter));
    }

    @GetMapping("/exportYffkjmxcx")
    @ApiOperation(value = "导出预付费扣减明细", tags = {"明细查询"})
    public void exportYffkjmxcx(HttpServletResponse response, @ModelAttribute YffYeSeachFilter filter) throws IOException {
        List<YffkjmxcxSelect> list = yySspjxxService.yffkjmxcxlist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YffkjmxcxSelect.class, "预付费扣减明细.xlsx", filter.getExportFields());
        }
    }

    @ApiOperation(value = "欠费统计按笔数[原]")
    @GetMapping("/qftjabs")
    public ResultRespone<QftjabsSelectCount> qftjabs(@ModelAttribute PageDto pageDto, @ModelAttribute QftjSeachFilter filter) {
        return ResultRespone.success(yyQfmxService.qftjabs(pageDto, filter));
    }

    @GetMapping("/exportQftjabs")
    @ApiOperation(value = "导出欠费统计（按笔数）", tags = {"明细查询"})
    public void exportQftjabs(HttpServletResponse response, @ModelAttribute QftjSeachFilter filter) throws IOException {
        List<QftjabsSelect> list = yyQfmxService.qftjabslist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, QftjabsSelect.class, "欠费统计（按笔数）.xlsx", filter.getExportFields());
        }
    }

    @ApiOperation(value = "欠费统计", tags = {"明细查询"})
    @GetMapping("/qftj")
    public ResultRespone<QftjSelectCount> qftj(@ModelAttribute PageDto pageDto, @ModelAttribute QftjSeachFilter filter) {
        return ResultRespone.success(yyQfmxService.qftj(pageDto, filter));
    }

    @ApiOperation(value = "欠费统计合计", tags = {"明细查询"})
    @GetMapping("/qftjhj")
    public ResultRespone qftjhj(@ModelAttribute QftjSeachFilter filter) {
        return ResultRespone.success(yyQfmxService.qftjhj(filter));
    }

    @GetMapping("/exportQftj")
    @ApiOperation(value = "导出欠费统计", tags = {"明细查询"})
    public void exportQftj(HttpServletResponse response, @ModelAttribute QftjSeachFilter filter) throws IOException {
        List<QftjSelect> list = yyQfmxService.qftjlist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, QftjSelect.class, "欠费统计.xlsx", filter.getExportFields());
        }
    }

    @ApiOperation(value = "用水清单", tags = {"明细查询"})
    @GetMapping("/ysqd")
    public ResultRespone<PageResult<YsqdSelect>> ysqd(@ModelAttribute PageDto pageDto, @ModelAttribute QftjSeachFilter filter) {
        return ResultRespone.success(yyQfmxService.ysqd(pageDto, filter));
    }

    @ApiOperation(value = "水量抄表统计")
    @GetMapping("/slcbtj")
    public ResultRespone<Sltjzj> slcbtj(@ModelAttribute PageDto pageDto, @ModelAttribute QftjSeachFilter filter) {
        return ResultRespone.success(yyQfmxService.slcbtj(pageDto, filter));
    }

    @GetMapping("/exportYsqd")
    @ApiOperation(value = "导出用水清单", tags = {"明细查询"})
    public void exportYsqd(HttpServletResponse response, @ModelAttribute QftjSeachFilter filter) throws IOException {
        List<YsqdSelect> list = yyQfmxService.ysqdlist(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YsqdSelect.class, "用水清单.xlsx", filter.getExportFields());
        }
    }

    @ApiOperation(value = "应收垃圾费统计", response = LjftjSelect.class, responseContainer = "List", tags = {"垃圾费统计"})
    @GetMapping("/ljftj")
    public ResultRespone<List<LjftjSelect>> ysljf(@ModelAttribute LjftjFilter filter) {
        if (StringUtil.isEmpty(filter.getStartcwrq())) {
            throw new FeesException("开始财务日期不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(filter.getEndcwrq())) {
            throw new FeesException("结束财务日期不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        List<LjftjSelect> list = new ArrayList<>();
        if (filter.getCxlx().equals("0")) {
            list = yyQfmxService.wsljf(filter);
        }
        if (filter.getCxlx().equals("1")) {
            list = yyQfmxService.ysljf(filter);
        }
        if (filter.getCxlx().equals("2")) {
            list = yyQfmxService.yisljf(filter);
        }
        return ResultRespone.success(list);
    }

    @GetMapping("/exportljftj")
    @ApiOperation(value = "导出应收垃圾费统计", tags = {"垃圾费统计"})
    public void exportYsljf(HttpServletResponse response, @ModelAttribute LjftjFilter filter) throws IOException {
        if (StringUtil.isEmpty(filter.getStartcwrq())) {
            throw new FeesException("开始财务日期不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isEmpty(filter.getEndcwrq())) {
            throw new FeesException("结束财务日期不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (filter.getCxlx().equals("0")) {
            List<LjftjSelect> list = yyQfmxService.wsljf(filter);
            if (!list.isEmpty()) {
                ExcleFileUtil.exportExcel(response, list, LjftjSelect.class, "未收垃圾费统计.xlsx", filter.getExportFields());
            }
        }
        if (filter.getCxlx().equals("1")) {
            List<LjftjSelect> list = yyQfmxService.ysljf(filter);
            if (!list.isEmpty()) {
                ExcleFileUtil.exportExcel(response, list, LjftjSelect.class, "应收垃圾费统计.xlsx", filter.getExportFields());
            }
        }
        if (filter.getCxlx().equals("2")) {
            List<LjftjSelect> list = yyQfmxService.yisljf(filter);
            if (!list.isEmpty()) {
                ExcleFileUtil.exportExcel(response, list, LjftjSelect.class, "已收垃圾费统计.xlsx", filter.getExportFields());
            }
        }
    }

    @GetMapping("/getwjPage")
    @ApiOperation(value = "附件信息查询", tags = {"明细查询"})
    public ResultRespone<PageResult<YhwjSelect>> getwjPage(@ModelAttribute PageDto pageDto, @ModelAttribute YhwjFilter filter) {
        return ResultRespone.success(yhKhjbxxService.getwjPage(pageDto, filter));
    }

    @GetMapping("/getYcfpmxtj")
    @ApiOperation(value = "获取预开发票明细统计", tags = {"明细查询"})
    public ResultRespone getYcfpmxtj(@ModelAttribute PageDto pageDto, @ModelAttribute YkfpmxtjFilter filter) {
        return ResultRespone.success(yyQfmxService.getYcfpmxtj(pageDto, filter));
    }

    @GetMapping("/exportYcfpmxtj")
    @ApiOperation(value = "导出预开发票明细统计", tags = {"明细查询"})
    public void exportYcfpmxtj(HttpServletResponse response, @ModelAttribute YkfpmxtjFilter filter) throws IOException {
        List<YkfpmxtjSelect> list = yyQfmxService.exportYcfpmxtj(filter);
        if (!list.isEmpty()) {
            ExcleFileUtil.exportExcel(response, list, YkfpmxtjSelect.class, "预开发票明细统计.xlsx", filter.getExportFields());
        }
    }


    @GetMapping("/getYstj")
    @ApiOperation(value = "获取营收统计", tags = {"营收统计图表"})
    public ResultRespone<YstjSelect> getYstj() {
        YstjSelect ystjSelect = new YstjSelect();
        BigDecimal yszje = yySspjxxService.getYszje();
        Map map = yySspjxxService.getDrystj();
        long qfyhs = yyQfmxService.getQfyhs();
        BigDecimal drysje = StringUtil.isNotEmpty(map.get("ssje").toString()) ? new BigDecimal(map.get("ssje").toString()) : BigDecimal.ZERO;
        long drysbs = StringUtil.isNotEmpty(map.get("ssbs").toString()) ? Long.parseLong(map.get("ssbs").toString()) : 0L;
        ystjSelect.setYszje(yszje);
        ystjSelect.setDrysje(drysje);
        ystjSelect.setDrysbs(drysbs);
        ystjSelect.setQfyhs(qfyhs);
        return ResultRespone.success(ystjSelect);
    }

    @GetMapping("/getYsartj")
    @ApiOperation(value = "获取营收按日统计", tags = {"营收统计图表"})
    public ResultRespone<List<YsartjSelect>> getYsartj(@ModelAttribute YsartjFilter filter) {
        if (StringUtil.isNull(filter.getStartDate())) {
            throw new FeesException("开始时间不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isNull(filter.getEndDate())) {
            throw new FeesException("结束时间不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        List<YsartjSelect> list = yySspjxxService.getYsartj(filter);
        List<String> rqlist = ToolsUtils.getRqList(filter.getStartDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate(),
                filter.getEndDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        if (list.size() != rqlist.size()) {
            for (String rq : rqlist) {
                boolean flag = true;
                for (YsartjSelect item : list) {
                    if (item.getRq().equals(rq)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    YsartjSelect ysartjSelect = new YsartjSelect();
                    ysartjSelect.setRq(rq);
                    ysartjSelect.setYsje(BigDecimal.ZERO);
                    list.add(ysartjSelect);
                }
            }
        }
        list = list.stream().sorted(Comparator.comparing(YsartjSelect::getRq)).collect(Collectors.toList());
        return ResultRespone.success(list);
    }

    @GetMapping("/getYssfzb")
    @ApiOperation(value = "获取营收收费占比", tags = {"营收统计图表"})
    public ResultRespone<List<Map>> getYssfzb(@ModelAttribute YsartjFilter filter) {
        if (StringUtil.isNull(filter.getStartDate())) {
            throw new FeesException("开始时间不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        if (StringUtil.isNull(filter.getEndDate())) {
            throw new FeesException("结束时间不能为空", FeesErrorCode.BUSINESS_ERROR);
        }
        List<Map> list = yySspjxxService.getYssfzb(filter);
        BigDecimal total = list.stream().map(item -> new BigDecimal(item.get("ysje").toString())).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (total.compareTo(BigDecimal.ZERO) > 0) {
            list.forEach(item -> {
                BigDecimal ysje = new BigDecimal(item.get("ysje").toString());
                item.put("yszb", ysje.divide(total, 2, RoundingMode.HALF_UP).multiply(new BigDecimal(100)));
            });
        }
        return ResultRespone.success(list);
    }

    @GetMapping("/getYsaytj")
    @ApiOperation(value = "获取营收按月统计（统计近十二月数据）", tags = {"营收统计图表"})
    public ResultRespone<List<YsartjSelect>> getYsaytj() {
        List<YsartjSelect> list = yySspjxxService.getYsaytj();
        List<String> rqlist = ToolsUtils.getRqList();
        if (list.size() != rqlist.size()) {
            for (String rq : rqlist) {
                boolean flag = true;
                for (YsartjSelect item : list) {
                    if (item.getRq().equals(rq)) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    YsartjSelect ysartjSelect = new YsartjSelect();
                    ysartjSelect.setRq(rq);
                    ysartjSelect.setYsje(BigDecimal.ZERO);
                    list.add(ysartjSelect);
                }
            }
        }
        list = list.stream().sorted(Comparator.comparing(YsartjSelect::getRq)).collect(Collectors.toList());
        return ResultRespone.success(list);
    }
}
