package org.king.modules.ad.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.king.common.system.base.controller.KingController;
import org.king.common.api.vo.Result;
import org.king.common.system.query.QueryGenerator;
import org.king.common.aspect.annotation.AutoLog;
import org.king.common.system.vo.LoginUser;
import org.king.modules.ad.entity.AdAlternativeMeasure;
import org.king.modules.ad.entity.AdChargingRecord;
import org.king.modules.ad.entity.BaseWharf;
import org.king.modules.ad.entity.Depart;
import org.king.modules.ad.entity.EntCompanyGeom;
import org.king.modules.ad.service.IAdAlternativeMeasureService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.king.modules.ad.service.IBaseWharfService;
import org.king.modules.ad.service.IDepartService;
import org.king.modules.ad.service.IEntCompanyGeomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 替代措施
 * @Author: king-boot
 * @Date: 2021-06-07
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "替代措施")
@RestController
@RequestMapping("/ad/adAlternativeMeasure")
public class AdAlternativeMeasureController extends KingController<AdAlternativeMeasure, IAdAlternativeMeasureService> {

    @Autowired
    private IAdAlternativeMeasureService adAlternativeMeasureService;
    @Autowired
    private IBaseWharfService baseWharfService;
    @Autowired
    private IEntCompanyGeomService entCompanyGeomService;
    @Autowired
    private IDepartService departService;

    /**
     * 分页列表查询
     *
     * @param adAlternativeMeasure
     * @param pageNo               页码
     * @param pageSize             每页条数
     * @param req
     * @return
     */
    @AutoLog(value = "替代措施-分页列表查询")
    @ApiOperation(value = "替代措施-分页列表查询", notes = "替代措施-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AdAlternativeMeasure adAlternativeMeasure,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AdAlternativeMeasure> queryWrapper = QueryGenerator.initQueryWrapper(adAlternativeMeasure, req.getParameterMap());
        Page<AdAlternativeMeasure> page = new Page<>(pageNo, pageSize);
        // 处理部门的数据
        String departId = req.getParameter("departId");
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                return Result.ok(new Page<AdChargingRecord>());
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            List<Object> comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                return Result.ok(new Page<AdChargingRecord>());
            }
            log.info("查询到的comNos：{}", comNos);
            // 非空，查询条件增加设备的id
            queryWrapper.in("com_no", comNos);
        }
        IPage<AdAlternativeMeasure> pageList = adAlternativeMeasureService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    private void checkChildrenExists(String departId, List<String> idList) {
        List<Depart> departList = departService.list(Wrappers.<Depart>lambdaQuery().eq(Depart::getUpdepartNo, departId));
        if (departList != null && departList.size() > 0) {
            for (Depart depart : departList) {
                idList.add(Convert.toStr(depart.getDepartNo()));
                this.checkChildrenExists(Convert.toStr(depart.getDepartNo()), idList);
            }
        }
    }

    /**
     * 通过id查询
     *
     * @param id 主键id
     * @return
     */
    @AutoLog(value = "替代措施-通过id查询")
    @ApiOperation(value = "替代措施-通过id查询", notes = "替代措施-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        AdAlternativeMeasure adAlternativeMeasure = adAlternativeMeasureService.getById(id);
        if (adAlternativeMeasure == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(adAlternativeMeasure);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adAlternativeMeasure
     */
    @AutoLog(value = "替代措施-导出excel")
    @ApiOperation(value = "替代措施-导出excel", notes = "替代措施-导出excel")
    @RequestMapping(value = "/exportXls", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView exportXls(HttpServletRequest request, AdAlternativeMeasure adAlternativeMeasure) {
        QueryWrapper<AdAlternativeMeasure> queryWrapper = QueryGenerator.initQueryWrapper(adAlternativeMeasure, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 处理部门的数据
        String departId = request.getParameter("departId");
        boolean flag = true;
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            List<Object> comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的comNos：{}", comNos);
            // 非空，查询条件增加设备的id
            queryWrapper.in("com_no", comNos);
        }

        // Step.2 获取导出数据
        List<AdAlternativeMeasure> exportList = new ArrayList<>();
        if (flag) {
            exportList = adAlternativeMeasureService.list(queryWrapper);
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "替代措施"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, AdAlternativeMeasure.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("替代措施报表", "导出人:" + sysUser.getRealname(), "替代措施"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

}
