package com.steerinfo.ems.trmworkprocmaterial.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmmaterial.service.ITRmMaterialService;
import com.steerinfo.ems.trmworkprocmaterialvalue.service.ITRmWorkprocMaterialValueService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.trmworkprocmaterial.model.TRmWorkprocMaterial;
import com.steerinfo.ems.trmworkprocmaterial.service.ITRmWorkprocMaterialService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

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

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

    @Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;
    @Autowired
    private ITRmMaterialService tRmMaterialService;
    @Autowired
    IFormulaService formulaService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmworkprocmaterial:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmWorkprocMaterial> list = tRmWorkprocMaterialService.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("trmworkprocmaterial:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmWorkprocMaterial> list = tRmWorkprocMaterialService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="获取财务物料列表")
    //@RequiresPermissions("trmworkprocmaterial:view")
    @GetMapping(value = "/listFinanceData/")
    public RESTfulResult listFinancedata(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
    	List<Map<String, Object>> list = tRmWorkprocMaterialService.queryFinanceData();
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmWorkprocMaterial对象创建")
    @ApiImplicitParam(name = "tRmWorkprocMaterial", value = "详细实体tRmWorkprocMaterial", required = true, dataType = "TRmWorkprocMaterial")
    //@RequiresPermissions("trmworkprocmaterial:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@RequestBody TRmWorkprocMaterial model){
        String itemid = model.getWorkprocid() +model.getMaterialid() + "R";
        Set<String> getitemid = tRmWorkprocMaterialService.getitemid();
        for (String s : getitemid) {
            if(s.equals(itemid)){
                return  failed(model,"原材料和工序值在数据库中已存在重复数据");
            }
        }
        model.setId(itemid);
        model.setMesMaterialcode(tRmMaterialService.getById(model.getMaterialid()).getBcode());
        model.setUseflag("1");
        if (model.getSeqno() ==null || model.getSeqno().isEmpty()){
        	model.setSeqno("10");
        }
        if (model.getDigits() ==null){
        	model.setDigits(Short.valueOf("2"));
        }
        model.setItemtype("R");
        model.setCreateman(JwtUtil.getUseridByToken());
        model.setCreatetime(new Date());
        TRmWorkprocMaterial tRmWorkprocMaterial = tRmWorkprocMaterialService.add(model);
        Formula formula = new Formula();
        formula.setClock("202001");
        formula.setCode(itemid);
        String name = tRmWorkprocMaterialService.getName(itemid);
        formula.setDescription(name);
        formula.setIsavailable("1");
        formula.setRevisor(JwtUtil.getUseridByToken());
        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        formula.setSourcecode("R(T_RM_WORKPROC_MATERIAL_VALUE," + itemid + ")");
        formula.setTablename("T_RM_WORKPROC_MATERIAL_VALUE");
        formulaService.add(formula);
        return success(tRmWorkprocMaterial);
    }

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

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


    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmworkprocmaterial:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        String[] array = id.split(",");
        if(array.length >= 1) {
        	for (int i = 0; i < array.length; i++) {
            	List<Formula> list = formulaService.getFormulaByCode(array[i]);
            	if(list!=null && list.size()>0){
            		String item="";
            		for(Formula fa:list){
            			item += "[" + fa.getClock() +"版本，项目编号"+ fa.getCode() + "],";
            		}
            		item = item.substring(0,item.length()-1);
            		return failed(null, item + " 公式中包含点 " + array[i] + "，请先处理");
            	}
            }
        	try {
	            for (int i = 0; i < array.length; i++) {
	            	tRmWorkprocMaterialService.delete(array[i]);
	            	formulaService.deleteBycode(array[i]);
	            }
        	} catch(Exception e){
        		return failed(null, "项目已有数据，不允许删除");
            }
            return success();
        }
        else {
            return failed(null, "请输入要删除的id");
        }
    }

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