package com.tofly.base.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.base.entity.Code;
import com.tofly.base.service.CodeService;
import com.tofly.common.core.constant.CommonConstants;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.SpringContextHolder;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.log.annotation.ToFlyAppLog;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/code")
@Api(tags="系统码表接口")
public class CodeController {

    private final CodeService codeService;

    @GetMapping("/page" )
    @ApiOperation(value = "分页查询")
    public ResultRespone getCodePage(Page page, @ModelAttribute Code code) {
      return ResultRespone.success(codeService.page(page, Wrappers.query(code)));
    }

    @ToFlyAppLog(title="通过key和ulevel查询系统码表" )
    @ApiOperation(value = "通过key和ulevel查询系统码表")
    @GetMapping("/getByKeys" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keys", value = "key", required = true, dataType = "String"),
            @ApiImplicitParam(name = "ulevel", value = "级别  1字典类级别，2系统类级别", required = true, dataType = "String")
    })
    public ResultRespone selectByKeyAndUlevel( String keys, String ulevel) {
            String[] keyss = keys.split(",");
            List<Code> list = codeService.list(Wrappers.<Code>lambdaQuery().in(Code::getKey, Arrays.asList(keyss)));
        if ("".equals(ulevel)) {
            Map<String, List<Code>> map = list.stream().collect(Collectors.toMap(Code::getKey, c -> new ArrayList<Code>() {{
                add(c);
            }}, (List<Code> c1, List<Code> c2) -> {
                c1.addAll(c2);
                return c1;
            }));
//        Map map=new HashMap();
//        for(String key:keyss){
//           map.put(key,codeService.list(Wrappers.<Code>lambdaQuery().eq(Code::getKey,key)));
//        }
            return ResultRespone.success(map);
        }
        Map<String,List<Code>> listMap = list.stream().collect(Collectors.groupingBy(Code::getUlevel));
        return ResultRespone.success(listMap);
    }



    /**
     * 通过id查询系统码表
     * @param id id
     * @return ResultRespone
     */
    @GetMapping("/{id}" )
    @ApiOperation(value = "通过ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    public ResultRespone getById(@PathVariable("id" ) Long id) {
      return ResultRespone.success(codeService.getById(id));
    }

    /**
     * 新增系统码表
     * @param code 系统码表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="新增系统码表" )
    @ApiOperation(value = "新增系统码表")
    @PostMapping
    public ResultRespone save(@RequestBody Code code) {
        String ulevel = code.getUlevel();
        Wrapper<Code> wrapper=Wrappers.<Code>lambdaQuery()
                .eq(Code::getUlevel,code.getUlevel())
                .eq(Code::getKey,code.getKey());
        String msg=null;

        if("1".equals(ulevel)){
            Code c=codeService.getOne(wrapper);
            if(c!=null){
                msg="抱歉，已存在相同字典值："+code.getKey();
            }
        }else if("2".equals(ulevel)){
            Code c= codeService.getOne(((LambdaQueryWrapper<Code>) wrapper).eq(Code::getValue,code.getValue()));
            if(c!=null){
                msg="抱歉，已存在相同字典值："+code.getValue()+"（"+c.getNotes()+")";
            }
        }
        if(StringUtil.isEmpty(msg)){
            boolean b=codeService.save(code);
            //推送到工作流
            if(b&& CommonConstants.POSTIONKEY.equals(code.getKey()) &&
             "2".equals(ulevel)){
                Map map = new HashMap();
                map.put("value",code.getValue());
                map.put("notes",code.getNotes());
//                SpringContextHolder.publishEvent(new FlowableAddUserGroupEvent(map));
            }

            return ResultRespone.success(true);
        }else{
            return ResultRespone.failed(msg);
        }

    }

    /**
     * 修改系统码表
     * @param code 系统码表
     * @return ResultRespone
     */
    @ToFlyAppLog(title="修改系统码表" )
    @ApiOperation(value = "修改系统码表")
    @PutMapping
    public ResultRespone updateById(@RequestBody Code code) {
        boolean b = codeService.updateById(code);
        if(b && CommonConstants.POSTIONKEY.equals(code.getKey()) &&
                "2".equals(code.getUlevel()) && !StringUtil.isEmpty(code.getNotes())){
            Map map = new HashMap();
            map.put("value",code.getValue());
            map.put("notes",code.getNotes());
//            SpringContextHolder.publishEvent(new FlowableUpdateGroupEvent(map));
        }
      return ResultRespone.success(true);
    }

    /**
     * 通过id删除系统码表
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除系统码表" )
    @ApiOperation(value = "通过ID删除系统码表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone removeById(@PathVariable Long id) {
      return ResultRespone.success(codeService.removeById(id));
    }


    /**
     * 通过id删除系统码表
     * @param ids id数组
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除系统码表" )
    @ApiOperation(value = "通过ID删除系统码表")
    @DeleteMapping("/removeByIds" )
    public ResultRespone removeByIds(@ApiParam(value = "通过ID拼接的字符串,以逗号隔开.如,'1,2,3,4,5,6,7",name = "ids",required = true) String ids,
                                     @ApiParam(value = "对应级别",name = "ulevel",required = true) String ulevel) {
        if(StringUtil.isEmpty(ulevel)){
            return ResultRespone.failed("字典级别不能为空");
        }

        String[] idss=ids.split(",");
        List<Long> list=new ArrayList();
        boolean flag=true;
        StringBuffer sb=new StringBuffer(),values=new StringBuffer();
        for(String id:idss){
            //查询是否存在二级ID
            Code code=codeService.getById(id);
            if("1".equals(ulevel)){

                List<Code> codeList=codeService.list(Wrappers.<Code>lambdaQuery()
                .eq(Code::getUlevel,"2").eq(Code::getKey,code.getKey()));
                if(codeList.size()>0){
                    flag=false;
                    sb.append("key:").append(code.getKey()).append(",对应二级目录还存在").append(codeList.size())
                            .append("条数据;");
                }


            }
            //判断是否推送flowable
            if(CommonConstants.POSTIONKEY.equals(code.getKey())){
                values.append(",").append(code.getValue());
            }
            list.add(Long.valueOf(id));
        }
        if(flag){
            boolean b = codeService.removeByIds(list);
            if(b && values.length()>0){
                //推送到flowable
//                SpringContextHolder.publishEvent(new FlowableDeleteGroupEvent(values.toString().substring(1)));
            }
            return ResultRespone.success();
        }else {
            return ResultRespone.failed("字典存在子集信息，不能删除："+sb.toString());
        }

    }

}
