package com.qianhe.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.qianhe.common.core.page.PageDomain;
import com.qianhe.common.core.page.TableSupport;
import com.qianhe.common.utils.StringUtils;
import com.qianhe.domain.WdWdxx;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qianhe.common.annotation.Log;
import com.qianhe.common.core.controller.BaseController;
import com.qianhe.common.core.domain.AjaxResult;
import com.qianhe.common.enums.BusinessType;
import com.qianhe.domain.WdWdwh;
import com.qianhe.service.IWdWdwhService;
import com.qianhe.common.utils.poi.ExcelUtil;
import com.qianhe.common.core.page.TableDataInfo;

/**
 * 文档-文档维护Controller
 *
 * @author qianhe
 * @date 2024-02-28
 */
@RestController
@RequestMapping("/system/wdWdwh")
public class WdWdwhController extends BaseController
{
    @Autowired
    private IWdWdwhService wdWdwhService;

    /**
     * 查询文档-文档维护列表
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:list')")
    @GetMapping("/list")
    public TableDataInfo list(WdWdwh wdWdwh)
    {
        startPage();
        List<WdWdwh> list = wdWdwhService.selectWdWdwhList(wdWdwh);
        return getDataTable(list);
    }

    /**
     * 导出文档-文档维护列表
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:export')")
    @Log(title = "文档-文档维护", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WdWdwh wdWdwh)
    {
        List<WdWdwh> list = wdWdwhService.selectWdWdwhList(wdWdwh);
        ExcelUtil<WdWdwh> util = new ExcelUtil<WdWdwh>(WdWdwh.class);
        util.exportExcel(response, list, "文档-文档维护数据");
    }

    /**
     * 获取文档-文档维护详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(wdWdwhService.selectWdWdwhById(id));
    }

    /**
     * 新增文档-文档维护
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:add')")
    @Log(title = "文档-文档维护", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody WdWdwh wdWdwh)
    {
        return toAjax(wdWdwhService.insertWdWdwh(wdWdwh));
    }

    /**
     * 修改文档-文档维护
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:edit')")
    @Log(title = "文档-文档维护", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody WdWdwh wdWdwh)
    {
        return toAjax(wdWdwhService.updateWdWdwh(wdWdwh));
    }

    /**
     * 删除文档-文档维护
     */
    @PreAuthorize("@ss.hasPermi('system:wdWdwh:remove')")
    @Log(title = "文档-文档维护", businessType = BusinessType.DELETE)
	@PostMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(wdWdwhService.deleteWdWdwhByIds(ids));
    }

    /**
     * 根据三级单位统计---行转列
     */
//    @PreAuthorize("@ss.hasPermi('system:wdWdwh:list')")
    @GetMapping("/getListBySjDw")
    public TableDataInfo getListBySjDw(WdWdwh wdWdwh)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
//        startPage();
        List<WdWdwh> list = wdWdwhService.getListBySjDw(wdWdwh);
        List<Map> typeList = wdWdwhService.getListBySjDwByType(wdWdwh);
        // 结果
        List<Map> mapList = new ArrayList<>();
        // 二重循环 实体转map 并匹配zbcs 设置到map中
        for (WdWdwh wdWdwh1 : list) {
            String deptId = wdWdwh1.getDeptId();
            String year = wdWdwh1.getYear();
            // 1将 实体类 转换为 Map
            Map<String,Object> map = JSON.parseObject(JSON.toJSONString(wdWdwh1), Map.class);
            System.out.println(map);
            // 2取出当期装备编码对应的参数列表
            List<Map> nowZbcsList = typeList.stream().filter(data -> deptId.equals(data.get("deptId")) && year.equals(data.get("year"))).collect(Collectors.toList());
            map = setZbcsTomMap(map, nowZbcsList);
            map = toLowerKey(map);//键key 转小写
            mapList.add(map);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        List<Map> maps = startPage(mapList, pageNum, pageSize);
        rspData.setRows(maps);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 根据二级单位统计---行转列
     */
//    @PreAuthorize("@ss.hasPermi('system:wdWdwh:list')")
    @GetMapping("/getListByEjDw")
    public TableDataInfo getListByEjDw(WdWdwh wdWdwh)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
//        startPage();
        List<WdWdwh> list = wdWdwhService.getListByEjDw(wdWdwh);
        List<Map> typeList = wdWdwhService.getListByEjDwByType(wdWdwh);
        // 结果
        List<Map> mapList = new ArrayList<>();
        // 二重循环 实体转map 并匹配zbcs 设置到map中
        for (WdWdwh wdWdwh1 : list) {
            String deptId = wdWdwh1.getEjdeptId();
            String year = wdWdwh1.getYear();
            // 1将 实体类 转换为 Map
            Map<String,Object> map = JSON.parseObject(JSON.toJSONString(wdWdwh1), Map.class);
            System.out.println(map);
            // 2取出当期装备编码对应的参数列表
            List<Map> nowZbcsList = typeList.stream().filter(data -> deptId.equals(data.get("ejdeptId")) && year.equals(data.get("year"))).collect(Collectors.toList());
            map = setZbcsTomMap(map, nowZbcsList);
            map = toLowerKey(map);//键key 转小写
            mapList.add(map);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        List<Map> maps = startPage(mapList, pageNum, pageSize);
        rspData.setRows(maps);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    /**
     * 查询文件集合
     */
//    @PreAuthorize("@ss.hasPermi('system:wdWdwh:list')")
    @GetMapping("/getFileList")
    public  List<WdWdxx> getFileList(WdWdwh wdWdwh)
    {
        List<WdWdxx> list =wdWdwhService.getFileList(wdWdwh);
        return  list;
    }
    /**
     * 开始分页
     *
     * @param list
     * @param pageNum  页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public   List<Map> startPage( List<Map> list, Integer pageNum, Integer pageSize) {
        if(list == null){
            return null;
        }
        if(list.size() == 0){
            return null;
        }

        Integer count = list.size(); //记录总数
        Integer pageCount = 0; //页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; //开始索引
        int toIndex = 0; //结束索引

        if(pageNum > pageCount){
            pageNum = pageCount;
        }
        if (!pageNum.equals(pageCount)) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List<Map> pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }
    /**
     * 设置装备参数到 装备基础信息Map中
     */
    private Map<String,Object> setZbcsTomMap(Map<String,Object> zb, List<Map> zbcsMapList) {
        for (Map t : zbcsMapList) {
            String csmc = String.valueOf(t.get("typeName"));
            String csz = String.valueOf(t.get("num"));
            String setValue = validateIsNull(csz) ? "" : csz;
            zb.put(csmc, setValue);
        }
        return zb;
    }
    /**
     * @Description 将map中的所有key转化为小写
     */
    public static Map<String,Object> toLowerKey(Map<String, Object> map) {
        Map<String,Object> resultMap = new HashMap<>();
        Set<String> sets = map.keySet();
        for (String key : sets) {
            resultMap.put(key.toLowerCase(), map.get(key).toString());
        }
        return resultMap;
    }

    /**
     * 重新校验空 需要特殊过滤 null 字符串
     * 空值或者null 则返回 true
     */
    private boolean validateIsNull(String v) {
        if (StringUtils.isNotEmpty(v) && !"null".equals(v) && !"".equals(v)) {
            return false;
        }
        return true;
    }


}
