package com.steerinfo.ems.trmworkprocproduct.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.trmproduct.service.ITRmProductService;
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.trmworkprocproduct.model.TRmWorkprocProduct;
import com.steerinfo.ems.trmworkprocproduct.service.ITRmWorkprocProductService;
import com.steerinfo.ems.trmworkprocproductvalue.model.TRmWorkprocProductValue;
import com.steerinfo.ems.trmworkprocproductvalue.service.ITRmWorkprocProductValueService;

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.*;

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

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

    @Autowired
    ITRmWorkprocMaterialService tRmWorkprocMaterialService;
    @Autowired
    ITRmWorkprocProductService tRmWorkprocProductService;
    @Autowired
    ITRmProductService tRmProductService;
    @Autowired
    IFormulaService formulaService;
    @Autowired
    ITRmWorkprocProductValueService tRmWorkprocProductValueService;

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

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

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmworkprocproduct: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] + "，请先处理");
            	}
            	HashMap<String, Object> parmas = new HashMap<String, Object>();
            	parmas.put("itemid", array[i]);
            	List<TRmWorkprocProductValue> l = tRmWorkprocProductValueService.query(parmas);
            	if(l!=null && l.size()>0){
            		return failed(null, "[" + array[i] + "]已有数据，不能删除");
            	}
            }
            for (int i = 0; i < array.length; i++) {
            	tRmWorkprocProductService.delete(array[i]);
            	formulaService.deleteBycode(array[i]);
            }
            return success();
        }
        else {
            return failed(null, "请输入要删除的id");
        }
    }

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