package com.steerinfo.ems.trmworkproc.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.TreeUtils;
import com.steerinfo.ems.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmworkproc.mapper.TRmWorkprocMapper;
import com.steerinfo.ems.trmworkproc.model.TRmWorkproc;
import com.steerinfo.ems.trmworkproc.service.ITRmWorkprocService;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * TRmWorkproc RESTful接口：
 * @author 王金涛
 * @version 1.0-SNAPSHORT 2019-10-11
 * 类描述
 * 修订历史：
 * 日期：2019-10-11
 * 作者：王金涛
 * 参考：
 * 描述：TRmWorkproc RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmworkprocs")
public class TRmWorkprocController extends BaseRESTfulController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TRmWorkprocController.class);

    @Autowired
    ITRmWorkprocService tRmWorkprocService;
    @Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;
    @Autowired
    ITRmWorkprocProductService tRmWorkprocProductService;
    @Autowired
    ITRmActItemService tRmActItemService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmworkproc:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmWorkproc> list = tRmWorkprocService.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("trmworkproc:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
    	if(parmas.containsKey("parentid") && parmas.get("parentid") != null && !"".equals(parmas.get("parentid").toString())){
            String parentid = parmas.get("parentid").toString();
            if(parentid.indexOf(",") == -1){
                parmas.put("parentid", "and parentid = '" + parentid + "'");
            } else {
            	parentid = "and parentid in ('" + parentid.replaceAll(",", "','") + "')";
                parmas.put("parentid", parentid);
            }
        }
        PageList<TRmWorkproc> list = tRmWorkprocService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmWorkproc对象创建")
    @ApiImplicitParam(name = "tRmWorkproc", value = "详细实体tRmWorkproc", required = true, dataType = "TRmWorkproc")
    //@RequiresPermissions("trmworkproc:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmWorkproc 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(tRmWorkprocService.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(tRmWorkprocService.getMaxSeqNo()+1);
            model.setSeqno(seqno);
        }
         model.setCreateman(JwtUtil.getUseridByToken());
            TRmWorkproc tRmWorkproc = tRmWorkprocService.add(model);
            return success(tRmWorkproc);

    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmWorkproc信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmWorkproc", value = "详细实体tRmWorkproc", required = true, dataType = "TRmWorkproc")
    })
    //@RequiresPermissions("trmworkproc:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmWorkproc model){
        if(model.getParentid() == null){
            return failed(null,"上层节点不能为空！");
        }
        LOGGER.info("工序维护表修改前数据是" + tRmWorkprocService.getById(id).toString());
        model.setId(id);
        model.setUpdateman(JwtUtil.getUseridByToken());
        TRmWorkproc tRmWorkproc = tRmWorkprocService.modify(model);
        LOGGER.info("工序维护表修改后数据是" + tRmWorkproc.toString());
        return success(tRmWorkproc);
    }

    @ApiOperation(value="删除", notes="根据用户ID来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@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++) {
            if(tRmWorkprocMaterialService.queryByProperty("workprocid", Ids.get(i)).size() != 0){
                LOGGER.error("工序维护表在删除第" + i + "条数据时出现问题，id是" + Ids.get(i) + "原因是在T_RM_WORKPROC_MATERIAL表存在关系。");
                failnum++;
                failid.add(Ids.get(i));
                failmsg += Ids.get(i) + "在工序与原材料关联维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmWorkprocProductService.queryByProperty("workprocid", Ids.get(i)).size() != 0){
                LOGGER.error("工序维护表在删除第" + (i + 1) + "条数据时出现问题，id是" + Ids.get(i) + "原因是在T_RM_WORKPROC_PRODUCT表存在关系。");
                failnum++;
                failid.add(Ids.get(i));
                failmsg += Ids.get(i) + "在工序与产品关联界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmActItemService.queryByProperty("workprocid", Ids.get(i)).size() != 0){
                LOGGER.error("工序维护表在删除第" + (i + 1) + "条数据时出现问题，id是" + Ids.get(i) + "原因是在T_RM_ACT_ITEM表存在关系。");
                failnum++;
                failid.add(Ids.get(i));
                failmsg += Ids.get(i) + "在实绩项目维护界面存在关系，请先删除对应关系！";
                continue;
            }
            LOGGER.info("工序维护表要删除的第" + (i + 1) + "条数据是" + tRmWorkprocService.getById(Ids.get(i)).toString());
            tRmWorkprocService.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();
    }

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

    @ApiOperation(value="获取树状数据", notes="获取TRmWorkproc的树形数据")
    @GetMapping(value = "/gettree/")
    public RESTfulResult getTree(@RequestParam HashMap parameters){
        TreeUtils treeUtils = new TreeUtils();
        List<TRmWorkproc> list = tRmWorkprocService.getTree(parameters);
        return success(treeUtils.getTreeData(list));
    }

    @ApiOperation(value = "查询下拉框的值",notes = "根据 namd 和 id 来显示，可传参数ISSETTLE（列入结算）,ISREAL（列入实绩）,ISPLAN（列入计划）,ISBALANCE（列入平衡表）,HASPRODUCT（是否产出）")
    @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<TRmWorkprocMapper> idAndName = tRmWorkprocService.getIdAndName(parmas);
        return  success(idAndName);
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tRmWorkproc数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmWorkproc", value = "详细实体tRmWorkproc", required = true, dataType = "TRmWorkproc")
    //@RequiresPermissions("trmworkproc:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmWorkproc[] 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("工序信息维护修改前数据是" + tRmWorkprocService.getById(model[i].getId()).toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TRmWorkproc tRmWorkproc = tRmWorkprocService.modify(model[i]);
                LOGGER.info("工序信息维护修改后数据是" + tRmWorkproc.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();
    }
}
