package com.steerinfo.ftp.securitytype.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.TreeUtils;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.ftp.securitytype.model.SecurityType;
import com.steerinfo.ftp.securitytype.service.ISecurityTypeService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * SecurityType RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-07-27 04:21
 * 类描述
 * 修订历史：
 * 日期：2021-07-27
 * 作者：generator
 * 参考：
 * 描述：SecurityType RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/securitytypes")
public class SecurityTypeController extends BaseRESTfulController {

    @Autowired
    ISecurityTypeService securityTypeService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("securitytype:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<SecurityType> list = securityTypeService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("securitytype:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize,String[] Info){
        String securityInfo = parmas.get("securityInfo").toString().replace(",","|");
        parmas.put("securityInfo",securityInfo);
        PageList<SecurityType> list = securityTypeService.queryLikeForPage(parmas, pageNum, pageSize);
        //在前端已经判断过权限，后端保险，后期服务器压力大可以注释
        //List<String> infoList = Arrays.asList(Info);
        //List<SecurityType> securityTypeList= new ArrayList<>();
        //Integer total = 0;
        //if(infoList.size()!=0){
        //for (int i = 0;i < list.getList().size();i++){
        //    SecurityType securityInfo = (SecurityType) list.getList().get(i);
        //    if (securityInfo.getSecurityInfo() != null && !"".equals(securityInfo.getSecurityInfo())) {
        //        List<String> infoList2= Arrays.asList(securityInfo.getSecurityInfo().split(",")
        //        ).stream().map(s -> (s.trim())).collect(Collectors.toList());
        //        infoList2.retainAll(infoList);
        //        if (infoList2.size()>0){
        //            securityTypeList.add(securityInfo);
        //        }else{
        //            total++;
        //        }
        //        continue;
        //    }
        //    securityTypeList.add(securityInfo);
        //    continue;
        //}
        //list.setList(securityTypeList);
        //list.setTotal(list.getTotal()-total);
        //}
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据SecurityType对象创建")
    @ApiImplicitParam(name = "securityType", value = "详细实体securityType", required = true, dataType = "SecurityType")
    //@RequiresPermissions("securitytype:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute SecurityType model){

        if(model.getSecurityName() == null || "".equals(model.getSecurityName())){
            return failed(null, "名称不能为空");
        }
        else if (model.getSeqno()==0||model.getSeqno()==null){
            Long seqno = new Long(securityTypeService.getMaxSeqNo()+1);
            model.setSeqno(seqno);
        }
        String url = "";
        if(model.getSecurityParentid() != null && !"".equals(model.getSecurityParentid())){
            url=securityTypeService.getURL(model.getParentId());
        }
        model.setCreateMan(JwtUtil.getUseridByToken());
        model.setCreateTime(new Date());
        model.setSecurityUploadUrl(url+"/"+model.getSecurityName());
        SecurityType securityType = securityTypeService.add(model);
        return success(securityType);
    }

    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("securitytype:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        SecurityType securityType = securityTypeService.getById(id);
        return success(securityType);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的securityType信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "securityType", value = "详细实体securityType", required = true, dataType = "SecurityType")
    })
    //@RequiresPermissions("securitytype:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody SecurityType model){
        model.setId(id);
        SecurityType securityType = securityTypeService.modify(model);
        return success(securityType);
    }
    @PutMapping(value = "/batchupdate", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody SecurityType[] models) {
        String userId = JwtUtil.getUseridByToken();
        for (int i = 0; i < models.length; i++) {
            SecurityType model = models[i];
            if (model.getId() == null || model.getId().equals("")) {
                return failed(null, "id为空");
            }
            if (model.getSecurityName() == null || model.getSecurityName().equals("")) {
                return failed(null, "名称为空");
            }
            String url = "";
            if(model.getSecurityParentid() != null && !"".equals(model.getSecurityParentid())){
                url=securityTypeService.getURL(model.getParentId());
            }
            model.setSecurityUploadUrl(url+"/"+model.getSecurityName());
            model.setUpdateMan(userId);
            model.setUpdateTime(new Date());
            securityTypeService.modify(model);
        }
        return success();
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("securitytype:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
            for (int i = 0; i < ids.size(); i++) {
                if(securityTypeService.getParentNum(ids.get(i))>0)
                {
                    return failed(null, "所选分类存在子级，请先删除子级分类");
                }
            }
			  securityTypeService.delete(ids);
    	}
      return success();
    }

    @ApiOperation(value="获取上层节点", notes="查询上层节点名字和id")
    @GetMapping(value = "/getparent/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult getParent(){
        List<SecurityType> tRmWorkproc = securityTypeService.getParent();
        return success(tRmWorkproc);
    }

    @ApiOperation(value="获取树状数据", notes="获取TRmWorkproc的树形数据")
    @GetMapping(value = "/gettree/")
    public RESTfulResult getTree(@RequestParam HashMap parameters){
        TreeUtils treeUtils = new TreeUtils();
        String securityInfo = parameters.get("securityInfo").toString().replaceAll(",","|");
        //String[] securityInfo =parameters.get("securityInfo").toString().split(",");
        List<SecurityType> lists = securityTypeService.getTreeByInfo("("+securityInfo+")");
        //for (int i = 0; i <securityInfo.length; i++) {
        //List<SecurityType> list = securityTypeService.getTreeByInfo(securityInfo[i]);
        //lists.removeAll(list);
        //lists.addAll(list);
        //}
        return success(treeUtils.getTreeData(lists));
    }

    @ApiOperation(value = "查询下拉框的值",notes = "根据 namd 和 id 来显示")
    @GetMapping("/getIdAndName")
    public RESTfulResult getIdAndName(@RequestParam HashMap<String, Object> parmas){
        if(parmas.get("id") != null && !parmas.get("id").toString().isEmpty()){
            String id = parmas.get("id").toString();
            if(!id.startsWith("'")){
                id = "'" + id.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("id", id);
        }
        String securityInfo = parmas.get("securityInfo").toString().replace(",","|");
        parmas.put("securityInfo","("+securityInfo+")");
        List<SecurityType> idAndName = securityTypeService.getIdAndName(parmas);
        return  success(idAndName);
    }
}
