package com.steerinfo.ems.tprocessinfor.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.TreeUtils;
import com.steerinfo.ems.tprocessinfor.mapper.TProcessinforMapper;
import com.steerinfo.ems.trmworkproc.controller.TRmWorkprocController;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.tprocessinfor.model.TProcessinfor;
import com.steerinfo.ems.tprocessinfor.service.ITProcessinforService;
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.HashMap;
import java.util.List;
import java.util.ArrayList;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

/**
 * TProcessinfor RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2022-06-09 10:34
 * 类描述
 * 修订历史：
 * 日期：2022-06-09
 * 作者：generator
 * 参考：
 * 描述：TProcessinfor RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/tprocessinfors")
public class TProcessinforController extends BaseRESTfulController {
    private static final Logger LOGGER = LoggerFactory.getLogger(TProcessinforController.class);
    @Autowired
    ITProcessinforService tProcessinforService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("tprocessinfor:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TProcessinfor> list = tProcessinforService.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("tprocessinfor:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TProcessinfor> list = tProcessinforService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    //@RequiresPermissions("tprocessinfor:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TProcessinfor model){
        model.setStatus(model.getStatus() == null ? "1" : model.getStatus());
        if(model.getParentid() == null || "".equals(model.getParentid())){
            return failed(null, "请先选择树节点");
        }
        else if(model.getName() == null || "".equals(model.getName())){
            return failed(null, "name不能为空");
        }
        else if(tProcessinforService.getById(model.getId()) != null){
            return failed(null, "id已存在，不能新增");
        }
        else if(model.getId().length() != 6){
            return failed(null, "id长度应该为6位");
        }else if (model.getSeqno()==0||model.getSeqno()==null){
            Long seqno = new Long(tProcessinforService.getMaxSeqNo()+1);
            model.setSeqno(seqno);
        }
        TProcessinfor tProcessinfor = tProcessinforService.add(model);
        return success(tProcessinfor);

    }

    //@RequiresPermissions("tprocessinfor:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        TProcessinfor tProcessinfor = tProcessinforService.getById(id);
        return success(tProcessinfor);
    }

    @GetMapping(value = "/gettree/")
    public RESTfulResult getTree(@RequestParam HashMap parameters){
        TreeUtils treeUtils = new TreeUtils();
        List<TProcessinfor> list = tProcessinforService.getTree(parameters);
        return success(treeUtils.getTreeData(list));
    }
    @GetMapping(value = "/getparent/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult getParent(){
        List<TProcessinfor> tProcessinfors = tProcessinforService.getParent();
        return success(tProcessinfors);
    }
    @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);
        }
        List<TProcessinforMapper> idAndName = tProcessinforService.getIdAndName(parmas);
        return  success(idAndName);
    }
    //获取下拉框
    @GetMapping("/getmeuns")
    public RESTfulResult getMeuns(@RequestParam String node,String name){
        List<TProcessinfor> menus = tProcessinforService.getMenus(node,name);
        return success(menus);
    }


    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TProcessinfor[] model){
        int failnum = 0;
        String failmsg = "";
        List<String> errorid = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
            try {
                LOGGER.info("工序信息维护修改的第" + (i + 1) + "条数据:");
                LOGGER.info("工序信息维护修改前数据是" + tProcessinforService.getById(model[i].getId()).toString());
                TProcessinfor tProcessinfor = tProcessinforService.modify(model[i]);
                LOGGER.info("工序信息维护修改后数据是" + tProcessinfor.toString());
            }
            catch(Exception e){
                failnum++;
                errorid.add(model[i].getId());
                failmsg += "工序信息维护修改在第" + (i + 1) + "条数据出现错误,错误原因是" + e + ",id是" + model[i].getId();
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
            return success(errorid,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条");
        }
        return success();
    }

    //@RequiresPermissions("trmworkproc:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        int failnum = 0;
        List<String> failid = new ArrayList<>();
        List<String> Ids = Arrays.asList(id.split(","));
        String failmsg = "";
        for(int i = 0;i < Ids.size();i++) {
            LOGGER.info("工序维护表要删除的第" + (i + 1) + "条数据是" + tProcessinforService.getById(Ids.get(i)).toString());
            tProcessinforService.delete(Ids.get(i));
        }
        if(failnum > 0){
            LOGGER.info(JwtUtil.getUseridByToken() + "本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败的数据id:" + failid.toString());
            return success(failid,"51" ,"本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败原因：" + failmsg);
        }
        return success();
    }


    //@RequiresPermissions("trmworkproc:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TProcessinfor model){
        if(model.getParentid() == null){
            return failed(null,"上层节点不能为空！");
        }
        LOGGER.info("工序维护表修改前数据是" + tProcessinforService.getById(id).toString());
        model.setId(id);
        TProcessinfor tProcessinfor = tProcessinforService.modify(model);
        LOGGER.info("工序维护表修改后数据是" + tProcessinfor.toString());
        return success(tProcessinfor);
    }
}
