package com.xjrsoft.module.base.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.page.ConventPage;
import com.xjrsoft.common.page.PageOutput;
import com.xjrsoft.module.base.dto.AddWhitelistManagementDto;
import com.xjrsoft.module.base.dto.SetWhitelistEndTimeDto;
import com.xjrsoft.module.base.dto.UpdateWhitelistManagementDto;
import com.xjrsoft.module.base.dto.WhitelistManagementPageDto;
import com.xjrsoft.module.base.entity.TreeNode;
import com.xjrsoft.module.base.entity.WhitelistManagement;
import com.xjrsoft.module.base.service.IWhitelistManagementService;
import com.xjrsoft.module.base.vo.WhitelistManagementPageVo;
import com.xjrsoft.module.base.vo.WhitelistManagementVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
* @title: 白名单管理
* @Author brealinxx
* @Date: 2024-06-24
* @Version 1.0
*/
@RestController
@RequestMapping("/base" + "/whitelistManagement")
@Api(value = "/base"  + "/whitelistManagement",tags = "白名单管理代码")
@AllArgsConstructor
public class WhitelistManagementController {

    private final IWhitelistManagementService whitelistManagementService;

    @GetMapping(value = "/page")
    @ApiOperation(value="白名单管理列表(分页)")
    @SaCheckPermission("whitelistmanagement:detail")
    public RT<PageOutput<WhitelistManagementPageVo>> page(@Valid WhitelistManagementPageDto dto){
        Page<WhitelistManagementPageVo> page = whitelistManagementService.getPage(new Page<>(dto.getLimit(), dto.getSize()), dto);
        PageOutput<WhitelistManagementPageVo> pageOutput = ConventPage.getPageOutput(page, WhitelistManagementPageVo.class);
        return RT.ok(pageOutput);
    }

    @GetMapping(value = "/info")
    @ApiOperation(value="根据id查询白名单管理信息")
    @SaCheckPermission("whitelistmanagement:detail")
    public RT<WhitelistManagementVo> info(@RequestParam Long id){
        WhitelistManagement whitelistManagement = whitelistManagementService.getById(id);
        if (whitelistManagement == null) {
           return RT.error("找不到此数据！");
        }
        return RT.ok(BeanUtil.toBean(whitelistManagement, WhitelistManagementVo.class));
    }


    @PostMapping
    @ApiOperation(value = "新增白名单管理")
    @SaCheckPermission("whitelistmanagement:add")
    public RT<Boolean> add(@Valid @RequestBody AddWhitelistManagementDto dto){
        WhitelistManagement whitelistManagement = BeanUtil.toBean(dto, WhitelistManagement.class);
        boolean isSuccess = whitelistManagementService.save(whitelistManagement);
        if(isSuccess){
            CompletableFuture.runAsync(() -> {
                whitelistManagementService.loadCaches();
            });
        }

        return RT.ok(isSuccess);
    }

    @PostMapping("/set-endtime-batch")
    @ApiOperation(value = "批量设置结束时间")
    @SaCheckPermission("whitelistmanagement:add")
    public RT<Boolean> setEndtimeBatch(@Valid @RequestBody SetWhitelistEndTimeDto dto){
        List<WhitelistManagement> list = whitelistManagementService.listByIds(dto.getIds());
        for (WhitelistManagement whitelistManagement : list) {
            whitelistManagement.setIsTemporary(1);
            whitelistManagement.setEndTime(dto.getEndTime());
        }
        boolean updated = whitelistManagementService.updateBatchById(list);
        return RT.ok(updated);
    }

    @PostMapping("/set-temporary")
    @ApiOperation(value = "设置为永久")
    @SaCheckPermission("whitelistmanagement:add")
    public RT<Boolean> setTemporary(@Valid @RequestBody List<Long> ids){
        List<WhitelistManagement> list = whitelistManagementService.listByIds(ids);
        for (WhitelistManagement el : list) {
            UpdateWrapper<WhitelistManagement> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", el.getId());
            updateWrapper.setSql("end_time = null");
            updateWrapper.setSql("is_temporary = 0");
            whitelistManagementService.update(el, updateWrapper);
        }
        return RT.ok(true);
    }

    @PutMapping
    @ApiOperation(value = "修改白名单管理")
    @SaCheckPermission("whitelistmanagement:edit")
    public RT<Boolean> update(@Valid @RequestBody UpdateWhitelistManagementDto dto){

        WhitelistManagement whitelistManagement = BeanUtil.toBean(dto, WhitelistManagement.class);
        return RT.ok(whitelistManagementService.updateById(whitelistManagement));

    }

    @DeleteMapping
    @ApiOperation(value = "删除白名单管理")
    @SaCheckPermission("whitelistmanagement:delete")
    public RT<Boolean> delete(@Valid @RequestBody List<Long> ids){
        boolean b = whitelistManagementService.removeBatchByIds(ids);
        if(b){
            CompletableFuture.runAsync(() -> {
                whitelistManagementService.loadCaches();
            });
        }

        return RT.ok(b);

    }

    @GetMapping("/structure")
    @ApiOperation(value = "获取年级班级树结构")
    public ResponseEntity<List<TreeNode>> getTreeStructure() {
        List<TreeNode> treeStructure = whitelistManagementService.getTreeStructure();
        return ResponseEntity.ok(treeStructure);
    }

    @PostMapping("/import")
    @ApiOperation(value = "导入")
    public RT<List<Map<String, String>>> importData(@RequestParam MultipartFile file) throws IOException {
        List<Map<Integer, Object>> excelDataList = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(3).doReadSync();
        List<Map<Integer, Object>> errorList = whitelistManagementService.importData(excelDataList);
        List<Map<String, String>> result = new ArrayList<>();

        for (Map<Integer, Object> objectMap : errorList) {
            Map<String, String> object = new LinkedHashMap<>();
            List<String> errorMsg = new ArrayList<>();
            if(objectMap.get(0) == null){
                errorMsg.add("姓名未填写");
            }
            if(objectMap.get(1) == null){
                errorMsg.add("身份证未填写");
            }
            if(objectMap.get(2) == null){
                errorMsg.add("手机号未填写");
            }
            object.put("姓名", objectMap.get(0)==null?"":objectMap.get(0).toString());
            object.put("身份证", objectMap.get(1)==null?"":objectMap.get(1).toString());
            object.put("手机号", objectMap.get(13)==null?"":objectMap.get(13).toString());
            object.put("错误信息", errorMsg.toString().replace("[","").replace("]", ""));
            result.add(object);
        }
        return RT.ok(result);
    }

    @PostMapping("/activate-import")
    @ApiOperation(value = "新生账号激活导入")
    public RT<List<Map<String, String>>> activateImport(@RequestParam MultipartFile file) throws IOException {
        List<Map<Integer, Object>> excelDataList = EasyExcel.read(file.getInputStream()).sheet().headRowNumber(3).doReadSync();
        List<Map<Integer, Object>> errorList = whitelistManagementService.activateImport(excelDataList);
        List<Map<String, String>> result = new ArrayList<>();

        for (Map<Integer, Object> objectMap : errorList) {
            Map<String, String> object = new LinkedHashMap<>();
            object.put("学生姓名", objectMap.get(0)==null?"":objectMap.get(0).toString());
            object.put("学生身份证", objectMap.get(1)==null?"":objectMap.get(1).toString());
            object.put("智慧校园卡号", objectMap.get(2)==null?"":objectMap.get(2).toString());
            object.put("家长姓名", objectMap.get(3)==null?"":objectMap.get(3).toString());
            object.put("家长手机号", objectMap.get(4)==null?"":objectMap.get(4).toString());
            object.put("错误信息", objectMap.get(5)==null?"":objectMap.get(5).toString());
            result.add(object);
        }
        return RT.ok(result);
    }

}