package com.yfd.platform.system.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
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.extension.plugins.pagination.Page;
import com.yfd.platform.annotation.Log;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.system.domain.Dictionary;
import com.yfd.platform.system.domain.SysDictionaryItems;
import com.yfd.platform.system.mapper.SysDictionaryItemsMapper;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 数据字典明细 前端控制器
 * </p>
 *
 * @author LiMengNan
 * @since 2023-03-08
 */
@RestController
@RequestMapping("/system/dictionaryItems")
@Api(tags = "数据字典项")
public class SysDictionaryItemsController {

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;

    /**********************************
     * 用途说明: 分页查询字典项信息
     * 参数说明  dictID 字典ID ItemName 字典项名称  pageNum 当前页
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回分页查询结果
     ***********************************/
    @GetMapping("/page")
    @ApiOperation("分页查询字典项信息")
    public ResponseResult getDictItemPage(String dictId, String dictName,
                                          Page<SysDictionaryItems> page) {

        LambdaQueryWrapper<SysDictionaryItems> queryWrapper =
                new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictionaryItems::getDictId, dictId).orderByAsc(SysDictionaryItems::getOrderNo);

        // 查询前将序号初始化
        List<SysDictionaryItems> list =
                sysDictionaryItemsService.list(queryWrapper);
        for (int i = 0; i < list.size(); i++) {
            SysDictionaryItems sysDictionaryItems = list.get(i);
            sysDictionaryItems.setOrderNo(i + 1);
            sysDictionaryItemsService.updateById(sysDictionaryItems);
        }
        Page<SysDictionaryItems> sysDictionaryItemsPage =
                sysDictionaryItemsService.getDictItemPage(dictId, dictName,
                        page);

        return ResponseResult.successData(sysDictionaryItemsPage);
    }

    /**********************************
     * 用途说明: 增加字典项
     * 参数说明  sysDictionaryItems 字典项信息
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回增加成功或者失败
     ***********************************/
    @Log(module = "数据字典项", value = "增加字典项")
    @PostMapping("/addDictionaryItem")
    @ApiOperation("增加字典项")
    public ResponseResult addDictionaryItem(@RequestBody SysDictionaryItems sysDictionaryItems) {
        if (sysDictionaryItems == null) {
            return ResponseResult.error("参数为空");
        }
        boolean ok =
                sysDictionaryItemsService.addDictionaryItem(sysDictionaryItems);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /**********************************
     * 用途说明: 修改字典项
     * 参数说明  sysDictionaryItems 字典项信息
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回修改成功或者失败
     ***********************************/
    @Log(module = "数据字典项", value = "修改字典项")
    @PostMapping("/updateDictionaryItem")
    @ApiOperation("修改字典项")
    public ResponseResult updateDictionaryItem(@RequestBody SysDictionaryItems sysDictionaryItems) {
        if (sysDictionaryItems == null) {
            return ResponseResult.error("参数为空");
        }
        boolean ok =
                sysDictionaryItemsService.updateById(sysDictionaryItems);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /**********************************
     * 用途说明: 根据ID查询字典项
     * 参数说明  id 字典项ID
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回字典项信息
     ***********************************/
    @GetMapping("/getDictItemById")
    @ApiOperation("根据ID查询字典项")
    public ResponseResult getDictItemById(String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        SysDictionaryItems sysDictionaryItems =
                sysDictionaryItemsService.getById(id);
        return ResponseResult.successData(sysDictionaryItems);
    }

    /**********************************
     * 用途说明: 根据ID删除字典项
     * 参数说明  id 字典项ID
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回删除成功或者失败
     ***********************************/
    @Log(module = "数据字典项", value = "根据ID删除字典项")
    @PostMapping("/deleteDictItemById")
    @ApiOperation("根据ID删除字典项")
    public ResponseResult deleteDictItemById(@RequestParam String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        boolean ok = sysDictionaryItemsService.removeById(id);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /**********************************
     * 用途说明: 批量删除字典项
     * 参数说明  ids 字典项id数组
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回批量删除成功或失败
     ***********************************/
    @Log(module = "数据字典项", value = "批量删除字典项")
    @PostMapping("/deleteDictItemByIds")
    @ApiOperation("批量删除字典项")
    public ResponseResult deleteDictItemByIds(@RequestParam String id) {
        if (StrUtil.isBlank(id)) {
            return ResponseResult.error("参数为空");
        }
        String[] splitIds = id.split(",");
        // 数组转集合
        List<String> ids = Arrays.asList(splitIds);
        boolean ok = sysDictionaryItemsService.removeByIds(ids);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /**********************************
     * 用途说明: 拖动修改字典项顺序
     * 参数说明  fromID 当前ID  toID 到达ID
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回拖动成功或者失败
     ***********************************/
    @Log(module = "数据字典项", value = "拖动修改字典项顺序")
    @PostMapping("/changeItemOrder")
    @ApiOperation("拖动修改字典项顺序")
    public ResponseResult changeItemOrder(@RequestParam String fromID,
                                          @RequestParam String toID) {
        boolean ok = sysDictionaryItemsService.changeItemOrder(fromID, toID);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    @GetMapping("/getDeviceByType")
    @ApiOperation("获取类型")
    public ResponseResult getDeviceByType(String dictcode) {
        if (StrUtil.isBlank(dictcode)) {
            return ResponseResult.error("参数为空");
        }
        List<Map<String, Object>> itemCode = sysDictionaryItemsService.getDeviceByType(dictcode);
        return ResponseResult.successData(itemCode);
    }


    /**********************************
     * 用途说明: 导出数据字典项数据
     * 参数说明  sysDictionaryItemsList  所需导出的字典项集合
     * 返回值说明: com.yfd.platform.config.ResponseResult 返回导出成功或失败
     ***********************************/
    @Log(module = "数据字典项", value = "导出字典数据到Excel")
    @GetMapping("/exportExcel")
    @ApiOperation("导出数据字典项数据")
    public void exportExcel(String dictID, String itemName,
                            Page<SysDictionaryItems> page,
                            HttpServletResponse response) {
        Page<SysDictionaryItems> sysDictionaryItemsPage =
                sysDictionaryItemsService.getDictItemPage(dictID, itemName,
                        page);
        sysDictionaryItemsService.exportExcel(sysDictionaryItemsPage.getRecords(), response);
    }

    @PostMapping("/importExecl")
    @ApiOperation("导入字典文件")
    public ResponseResult importExecl(String dictid, MultipartFile file) throws Exception {
        ExcelReader excelReader= ExcelUtil.getReader(file.getInputStream());
        List<List<Object>> list=excelReader.read();
        List<List<Object>> newlist= CollUtil.newArrayList();
        for (List<Object> objects : list) {
            if(CollUtil.contains(newlist,objects)){
                continue;
            }else{
                newlist.add(objects);
            }
        }

        List<SysDictionaryItems> dictionaryList=new ArrayList<>();
        for (int i = 1; i < newlist.size(); i++) {
            SysDictionaryItems sysdictionaryitems=new SysDictionaryItems();
            sysdictionaryitems.setDictId(dictid);
            Long longValue = (Long) newlist.get(i).get(0);
            Integer intValue = longValue.intValue();
            sysdictionaryitems.setOrderNo(intValue);
            sysdictionaryitems.setItemCode(newlist.get(i).get(1).toString());
            sysdictionaryitems.setDictName(newlist.get(i).get(2).toString());
            QueryWrapper<SysDictionaryItems> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("itemcode",newlist.get(i).get(1).toString());
            int count=sysDictionaryItemsService.count(queryWrapper);
            if(count==0){
                dictionaryList.add(sysdictionaryitems);
            }
        }

        sysDictionaryItemsService.saveBatch(dictionaryList);
        boolean ok = sysDictionaryItemsService.saveBatch(dictionaryList);
        if (ok) {
            return ResponseResult.success();
        } else {
            return ResponseResult.error();
        }
    }

    /***********************************
     * 用途说明：   根据父项编码查询数据字典项数据
     * 参数说明
     * parentcode  父项编码
     * 返回值说明:  变电站信息
     ***********************************/
    @PostMapping("/list")
    @ApiOperation("根据父项编码查询数据字典项数据")
    @ResponseBody
    public ResponseResult listSysDictionaryItems(@RequestParam String parentcode) {
        QueryWrapper<SysDictionaryItems> queryWrapper = new QueryWrapper<>();
        if(parentcode != null){
            queryWrapper.eq("parentcode",parentcode);
        }
        queryWrapper.orderByAsc("orderno");
        List<Map<String, Object>> maps = sysDictionaryItemsService.listMaps(queryWrapper);
        return ResponseResult.successData(maps);
    }


}
