package com.steerinfo.ems.trmmaterial.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.trmmaterial.mapper.TRmMaterialMapper;
import com.steerinfo.ems.trmworkproc.model.TRmWorkproc;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmmaterial.model.TRmMaterial;
import com.steerinfo.ems.trmmaterial.service.ITRmMaterialService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

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

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

    @Autowired
    ITRmMaterialService tRmMaterialService;
    @Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmmaterial:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmMaterial> list = tRmMaterialService.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("trmmaterial:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmMaterial> list = tRmMaterialService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmMaterial对象创建")
    @ApiImplicitParam(name = "tRmMaterial", value = "详细实体tRmMaterial", required = true, dataType = "TRmMaterial")
    //@RequiresPermissions("trmmaterial:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody TRmMaterial model){
        List<TRmMaterial> tRmMaterials = tRmMaterialService.getIdAndName();
        for (TRmMaterial tRmMaterial : tRmMaterials) {
             if(model.getId().equals(tRmMaterial.getId())){
                 return  failed(model,"该原材料代码已存在");
             }
        }
        String maxId = tRmMaterialService.getMaxId();
        maxId = String.format("%03d", Integer.parseInt(maxId) + 1);
        model.setId("Y"+maxId);
        model.setSeqno(maxId);
        model.setCreateman(JwtUtil.getUseridByToken());
        TRmMaterial tRmMaterial = tRmMaterialService.add(model);
        return success(tRmMaterial);
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmMaterial信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmMaterial", value = "详细实体tRmMaterial", required = true, dataType = "TRmMaterial")
    })
    //@RequiresPermissions("trmmaterial:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmMaterial model){
        model.setId(id);
        TRmMaterial tRmMaterial = tRmMaterialService.modify(model);
        return success(tRmMaterial);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmmaterial: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;
            }
            LOGGER.info("原材料信息维护要删除的第" + (i + 1) + "条数据是" + tRmMaterialService.getById(Ids.get(i)).toString());
            tRmMaterialService.delete(Ids.get(0));
        }
        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 = "根据name 和 id 来显示")
   @GetMapping("/getIdAndName")
    public  RESTfulResult getNameAndId(){
       List<TRmMaterial> idAndName = tRmMaterialService.getIdAndName();
       return success(idAndName);
   }


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