package com.template.controller;


import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.api.SmartWarningControllerAPI;
import com.template.common.result.ResponseStatusEnum;
import com.template.common.utils.*;
import com.template.model.dto.OperationWarningDto;
import com.template.model.dto.WarningSavePushDto;
import com.template.model.pojo.SmartDepartment;
import com.template.model.pojo.SmartUser;
import com.template.model.pojo.SmartWarning;
import com.template.model.result.CommonResult;
import com.template.model.result.PageUtils;
import com.template.model.vo.DepartmentTreeVo;
import com.template.model.vo.UserVo;
import com.template.services.SmartDepartmentService;
import com.template.services.SmartUserService;
import com.template.services.SmartWarningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-12-04
 */
@RestController
public class SmartWarningController implements SmartWarningControllerAPI {

    @Autowired
    private SmartWarningService smartWarningService;

    @Autowired
    private SmartDepartmentService smartDepartmentService;

    @Autowired
    private SmartUserService smartUserService;

    /**
     * 新增预警信息
     *
     * @param smartApply    预警信息数据
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult insertSmartWarning(SmartWarning smartApply, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = smartWarningService.insertSmartWarning(smartApply);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 更新预警信息
     *
     * @param sa            预警信息数据
     * @param bindingResult
     * @return
     */
    @Override
    public CommonResult updateSmartWarningById(SmartWarning sa, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = smartWarningService.updateSmartWarning(sa);
        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 预警信息分页数据查询
     *
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param name        查询名称
     * @return
     */
    @Override
    public CommonResult queryPageSmartWarning(int currentPage, int pageCount, String name, String state) {
        PageUtils<SmartWarning> result = smartWarningService.queryPageSmartWarnings(currentPage, pageCount, name, state);

        return CommonResult.ok(result);
    }


    @Override
    public CommonResult deleteSmartWarningById(int id) {

        SmartWarning data = smartWarningService.getSmartById(id);

        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = smartWarningService.deleteSmartWarningById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    @Override
    public CommonResult operation(OperationWarningDto operationWarningDto) {
        Integer id = operationWarningDto.getId();
        if (ObjectUtils.isEmpty(id)) {
            return CommonResult.fail("缺少id");
        }
        String remark = operationWarningDto.getRemark();

        SmartWarning smartById = smartWarningService.getSmartById(id);

        smartById.setStatu(1);
        smartById.setRemark(remark);

        int result = smartWarningService.updateSmartWarning(smartById);

        return result > 0 ? CommonResult.ok("操作成功") : CommonResult.fail("操作失败");
    }

    @Override
    public void excelSmartWarning(HttpServletResponse response, String location, String state) {
        // 表头数据
//        List<Object> head = Arrays.asList("姓名","事件","地点","时间","备注","状态","图片");
//
//        List<List<Object>> sheetDataList = new ArrayList<>();
//        sheetDataList.add(head);


        String fileName = "预警.xlsx";
        List<WarningEntity> warningEntities = new ArrayList<>();

//        获取数据
        LambdaQueryWrapper<SmartWarning> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(ObjectUtils.isNotEmpty(location), SmartWarning::getLocation, location)
                .eq(ObjectUtils.isNotEmpty(state), SmartWarning::getStatu, state);
        List<SmartWarning> list = smartWarningService.list(queryWrapper);


        for (SmartWarning smartWarning : list) {
            WarningEntity warning = new WarningEntity();
//                if (ObjectUtils.isNotEmpty(smartWarning.getWarningName())) {
            warning.setName(smartWarning.getWarningName());
//                }else {
//                    user.add("无");
//                }

            warning.setType(smartWarning.getType());

            warning.setLocation(smartWarning.getLocation());

            warning.setDateTime(smartWarning.getDateTime());

            warning.setRemark(smartWarning.getRemark());

            Integer statu = smartWarning.getStatu();
            String status = "";
            if (statu == 0) {
                status = "未处理";
            } else if (statu == 1) {
                status = "已处理";
            }
            warning.setState(status);

            warning.setImage(smartWarning.getImage());

            // 将数据汇总
            warningEntities.add(warning);
        }


        try {
            ExcelUtil3.process(fileName, warningEntities, WarningEntity.class, response);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public CommonResult warningType() {
        List<String> typeList = smartWarningService.warningType();
        typeList.add("全部");

        return CommonResult.ok(typeList);
    }

    @Override
    public CommonResult pageWarning(int currentPage, int pageCount, String type, String dateTime) {
        PageUtils<SmartWarning> result = smartWarningService.pageWarning(currentPage, pageCount, type, dateTime);

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult warningDepartmentTree() {
        List<SmartDepartment> result = smartDepartmentService.list(new QueryWrapper<>());

        List<SmartDepartment> zeroResult = result.stream().filter(e -> e.getParentId().intValue() == 0).collect(Collectors.toList());
        List<DepartmentTreeVo> departments = new ArrayList<>();
        for (SmartDepartment data : zeroResult) {
            DepartmentTreeVo newData = DepartmentTreeVo.builder()
                    .id(data.getId())
                    .name(data.getName())
                    .parentId(data.getParentId())
                    .build();

            List<DepartmentTreeVo> departmentTrees = QueryDepartmentTreeRecords(newData.getId(), result);
            newData.setChildren(departmentTrees);
            departments.add(newData);
        }


        return CommonResult.ok(departments);
    }

    @Override
    public CommonResult warningUserList(int currentPage, int pageCount, Integer departmentId, String name) {
        //获取该部门下的所有子级部门ID
        List<Integer> childDepartmentIds = new ArrayList<>();
        List<SmartDepartment> departments = smartDepartmentService.list(null);
        childDepartmentIds.add(departmentId);
        QueryDepartmentTreeRecords(departmentId, departments, childDepartmentIds);

        if (departmentId == null) {
            childDepartmentIds = null;
        }

        PageUtils<UserVo> result = smartUserService.warningUserList(currentPage, pageCount, childDepartmentIds, name);
        return CommonResult.ok(result);
    }

    @Override
    public CommonResult warningPushList() {
        List<SmartUser> names = smartUserService.warningPushList();

        return CommonResult.ok(names);
    }

    @Override
    public CommonResult warningSavePush(WarningSavePushDto warningSavePushDto) {
        List<Integer> ids = warningSavePushDto.getIds();

        if (ObjectUtils.isEmpty(ids) && ids.size() <= 0) {
            return CommonResult.fail(ResponseStatusEnum.PARAM_ERROR);
        }

        List<SmartUser> smartUsers = smartUserService.getSmartUserByIds(ids);

        for (SmartUser smartUser : smartUsers) {
            String gzhOpenId = smartUser.getGzhOpenId();
            if (ObjectUtils.isEmpty(gzhOpenId)) {
                return CommonResult.fail(smartUser.getName()+ "未关联公众号");
            }
            smartUser.setIsPush(1);
            smartUserService.updateSmartUser(smartUser);
        }

        return CommonResult.ok();
    }

    @Override
    public CommonResult warningDeletePush(Integer id) {

        if (ObjectUtils.isEmpty(id)) {
            return CommonResult.fail();
        }

        SmartUser smartById = smartUserService.getSmartById(id);

        if (ObjectUtils.isEmpty(smartById)) {
            return CommonResult.fail();
        }
        smartById.setIsPush(0);
        int result = smartUserService.updateSmartUser(smartById);
        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }


    /**
     * 根据父级ID获取树形数据
     *
     * @param parentID 父级ID
     * @param lists    数据集合
     * @return
     */
    private List<DepartmentTreeVo> QueryDepartmentTreeRecords(Integer parentID, List<SmartDepartment> lists) {
        List<DepartmentTreeVo> newTrees = new ArrayList<>();

        List<SmartDepartment> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());

        for (SmartDepartment data : datas) {
            DepartmentTreeVo item = DepartmentTreeVo.builder()
                    .id(data.getId())
                    .parentId(parentID)
                    .name(data.getName())
                    .build();
            List<DepartmentTreeVo> news = QueryDepartmentTreeRecords(item.getId(), lists);
            if (news == null || news.size() == 0) {
                newTrees.add(item);
                continue;
            } else {
                item.setChildren(news);
                newTrees.add(item);
            }
        }

        return newTrees;
    }

    /**
     * 根据父级ID获取树形数据
     *
     * @param parentID 父级ID
     * @param lists    数据集合
     * @return
     */
    private List<DepartmentTreeVo> QueryDepartmentTreeRecords(Integer parentID, List<SmartDepartment> lists, List<Integer> departmentIds) {
        List<DepartmentTreeVo> newTrees = new ArrayList<>();

        List<SmartDepartment> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());

        for (SmartDepartment data : datas) {
            departmentIds.add(data.getId());
            QueryDepartmentTreeRecords(data.getId(), lists, departmentIds);
        }

        return newTrees;
    }
}

