package com.steerinfo.ems.trmproduct.controller;
import com.steerinfo.auth.utils.JwtUtil;
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 com.steerinfo.ems.trmproduct.model.TRmProduct;
import com.steerinfo.ems.trmproduct.service.ITRmProductService;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

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

    @Autowired
    ITRmProductService tRmProductService;
    private static final Logger logger = LoggerFactory.getLogger(BaseRESTfulController.class);

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmproduct:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmProduct> list = tRmProductService.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("trmproduct:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmProduct> list = tRmProductService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmProduct对象创建")
    @ApiImplicitParam(name = "tRmProduct", value = "详细实体tRmProduct", required = true, dataType = "TRmProduct")
    //@RequiresPermissions("trmproduct:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody TRmProduct model){
        List<TRmProduct> IdAndNames = tRmProductService.getIdAndName();
        for (TRmProduct tRmProducts : IdAndNames) {
            if(tRmProducts.getId().equals(model.getId())){
                return failed(model,"改产品代码已经存在,请勿重复添加");
            }
        }
        String maxId = tRmProductService.getMaxId();
        maxId = String.format("%03d", Integer.parseInt(maxId) + 1);
        model.setId("CP"+maxId);
        model.setSeqno(maxId);
        model.setCreateman(JwtUtil.getUseridByToken());
        TRmProduct tRmProduct = tRmProductService.add(model);
        return success(tRmProduct);
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmProduct信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmProduct", value = "详细实体tRmProduct", required = true, dataType = "TRmProduct")
    })

    //@RequiresPermissions("trmproduct:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmProduct model){
        model.setId(id);
        model.setCreateman(JwtUtil.getUseridByToken());
        TRmProduct tRmProduct = tRmProductService.modify(model);
        return success(tRmProduct);
    }

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmproduct:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id) throws ParseException {
        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(tRmProductService.selectForTrmworkprocproductR(id)>0){
                failnum++;
                failid.add(Ids.get(i));
                failmsg += Ids.get(i) + "在实绩工序与产品关联页面有相关数据维护,请到该页面删除相关数据再进行操作!";
                continue;
            }
            if(tRmProductService.selectForTrmworkprocproductP(id)>0){
                failnum++;
                failid.add(Ids.get(i));
                failmsg += Ids.get(i) + "在计划工序与产品关联页面有相关数据维护,请到该页面删除相关数据再进行操作!";
                continue;
            }
            logger.info("产品信息维护要删除的第" + (i + 1) + "条数据是" + tRmProductService.getById(Ids.get(i)).toString());
            tRmProductService.delete(Ids.get(i));
        }
        if(failnum > 0){
            return success(failid,"51" ,"本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败原因：" + failmsg);
        }
        return success();
    }

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

    @ApiOperation(value="查询", notes="产品下拉框显示")
    @GetMapping("/getIdAndName")
    public RESTfulResult getIdAndName(){
        List<TRmProduct> idAndName = tRmProductService.getIdAndName();
        return success(idAndName);
    }

}
