package com.steerinfo.ems.formula.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.StrUtils;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.ems.formula.mapper.FormulaMapper;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
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.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Formula RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2019-11-13 09:38
 * 类描述
 * 修订历史：
 * 日期：2019-11-13
 * 作者：generator
 * 参考：
 * 描述：Formula RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/formulas")
public class FormulaController extends BaseRESTfulController { 
	private static final Logger logger = LoggerFactory.getLogger(FormulaController.class);

    @Autowired
    IFormulaService formulaService;
    
    @Autowired
    private FormulaMapper formulaMapper;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("formula:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        if(parmas.get("clock").toString() == null || "".equals(parmas.get("clock"))){
            parmas.put("clock", DateUtils.getCurrentTime("yyyyMM"));
        }
        String code = "";
        if(parmas.get("code")!=null && !parmas.get("code").toString().isEmpty()){
			code = parmas.get("code").toString().trim().replaceAll("，", ",");
			parmas.put("code", code);
		}
        if(parmas.containsKey("energyName") && parmas.get("energyName") != null && !"".equals(parmas.get("energyName").toString())){
            String energyName = parmas.get("energyName").toString();
            String sql = "select ID from T_RM_ENERGY where name  in ('" + energyName.replaceAll(",", "','") + "')";
	        List<String> codeRet = jdbcTemplate.queryForList(sql, String.class);
	        
	        if(codeRet != null && codeRet.size() > 0) {
		        for(int i = 0; i < codeRet.size(); i++){
		        	if(code != "") {
			        	code += ",";
			        }
		        	code += codeRet.get(i);
		        }
	        }
	        parmas.put("code", code);
        }
        PageList<Formula> list = formulaService.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("formula:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        if(parmas.get("clock").toString() == null || "".equals(parmas.get("clock"))){
            parmas.put("clock", DateUtils.getCurrentTime("yyyyMM"));
        }
        PageList<Formula> list = formulaService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的formula信息来更新详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "formula", value = "详细实体formula", required = true, dataType = "Formula")
    })
    @PutMapping(value = "/updateMula/")
    public RESTfulResult updateMula(@RequestBody Formula model, String oclock, String nclock){
    	if(nclock == null || nclock.trim().isEmpty() || !StrUtils.isClock(nclock)) {
    		return failed(null,"请填写要保存的版本");
    	}
        if(model.getTablename().equals("T_RM_ENERGY")){
            if(model.getSourcecode() == null || model.getSourcecode().isEmpty()){
                return failed(null,"公式内容不能为空！");
            }
            if(!StrUtils.isNumeric(model.getSourcecode())){
                return failed(null,"能介的折标系数公式只能输入正数！");
            }
            if(Double.parseDouble(model.getSourcecode()) == 0){
                return failed(null,"能介的折标系数公式不能为零！");
            }
        }
        model.setClock(nclock);
        if(formulaService.checkFormula(model) !=""){
            return failed(500,formulaService.checkFormula(model));
        }
        Formula formula = null;
        if (oclock!=null && !oclock.trim().isEmpty()){
        	formula = formulaService.updateFormula(model);
        }else{
        	formula = formulaService.addFormula(model);
        }
        if(formula == null){
        	return failed(500, "执行顺序错误，请联系管理员");
        }
        return success(formula);
    }
    
    @ApiOperation(value="折算系数修改", notes="折算系数修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formula", value = "详细实体formula", required = true, dataType = "Formula")
    })
    @PutMapping(value = "/batchupdate")
    public RESTfulResult batchupdate(@RequestBody Formula[] models){
    	int failnum = 0;
        ArrayList<String> failmsgs = new ArrayList<String>();
        for (int i = 0; i< models.length; i++) {
        	Formula model = models[i];
        	try {
	        	if(model.getTablename().equals("T_RM_ENERGY")){
	                if(model.getSourcecode() == null || model.getSourcecode().isEmpty()){
	                    //return failed(null,"公式内容不能为空！");
	                	throw new Exception("公式内容不能为空！");
	                }
	                if(!StrUtils.isNumeric(model.getSourcecode())){
	                    //return failed(null,"能介的折标系数公式只能输入正数！");
	                	 throw new Exception("能介的折标系数公式只能输入正数！");
	                }
	                if(Double.parseDouble(model.getSourcecode()) == 0){
	                    //return failed(null,"能介的折标系数公式不能为零！");
	                	 throw new Exception("能介的折标系数公式不能为零！");
	                }
	            }
	            if(formulaService.checkFormula(model) !=""){
	                //return failed(500,formulaService.checkFormula(model));
	            	 throw new Exception("公式内容不合法！");
	            }
	            Formula formula = formulaService.updateFormula(model);
	            if(formula == null){
	            	//return failed(500, "执行顺序错误，请联系管理员");
	            	 throw new Exception("执行顺序错误，请联系管理员！");
	            }
        	} catch(Exception e){
                failnum++;
                failmsgs.add(model.getCode());
                logger.error("数据修改出现错误,错误原因是" + e + ",能介编码是" + model.getCode());
            }
    	}
        if(failnum > 0){
            logger.info("本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条");
            return success(failmsgs, "99","本次共修改" + models.length + "条数据,其中成功" + (models.length - failnum) + "条,失败" + failnum + "条,失败的数据能介编码:" + failmsgs.toString());
        }
        return success();
    }
    
    @ApiOperation(value="解析公式", notes="解析公式为中文描述")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formula", value = "公式内容", required = true, dataType = "string")
    })
    @PostMapping(value = "/analysis/")
    public RESTfulResult analysis(@RequestBody Formula model){
        return success(formulaService.anaFormula(model));
    }
    
    @ApiOperation(value="保存公式为唯一版本", notes="保存公式为唯一版本")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formula", value = "详细实体formula", required = true, dataType = "Formula")
    })
    @PutMapping(value = "/saveOnly")
    public RESTfulResult saveOnly(@RequestBody Formula model){
    	if(model.getSourcecode() == null || model.getSourcecode().isEmpty()){
            return failed(null,"公式内容不能为空！");
        }
    	if(model.getCode() == null || model.getCode().isEmpty()){
            return failed(null,"公式code不能为空！");
        }
    	if(model.getTablename() == null || model.getTablename().isEmpty()){
            return failed(null,"公式表名不能为空！");
        }
    	if(model.getDescription() == null || model.getDescription().isEmpty()){
            return failed(null,"公式描述不能为空！");
        }
    	if(model.getIsavailable() == null || model.getIsavailable().isEmpty()){
            return failed(null,"公式是否可用不能为空！");
        }
        if(model.getTablename().equals("T_RM_ENERGY")){
            if(!StrUtils.isNumeric(model.getSourcecode())){
                return failed(null,"能介的折标系数公式只能输入正数！");
            }
            if(Double.parseDouble(model.getSourcecode()) == 0){
                return failed(null,"能介的折标系数公式不能为零！");
            }
        }
        model.setClock(DateUtils.getCurrentTime("yyyyMM"));
        if(formulaService.checkFormula(model) !=""){
            return failed(500,formulaService.checkFormula(model));
        }
        Formula formula = formulaService.saveOnly(model);
        if(formula == null){
        	return failed(500, "执行顺序错误，请联系管理员");
        }
        return success(formula);
    }

    @ApiOperation(value="根据项目编号、时间获取公式，clock之前最近的公式", notes="根据项目编号、时间获取公式，clock之前最近的公式")
    @GetMapping("/getByCodeClock")
    public RESTfulResult getFormulaCodeClock(@RequestParam HashMap<String, Object> parmas){
    	if(parmas.get("clock") == null || parmas.get("clock").toString().isEmpty()){
    		return failed(null, "请传入版本");
    	}
    	if(parmas.get("code") == null || parmas.get("code").toString().isEmpty()){
    		return failed(null, "请传入项目编号");
    	}
    	String code = parmas.get("code").toString();
    	String clock = parmas.get("clock").toString();
    	Formula formula = formulaService.getFormulaCodeClock(parmas);
    	if (formula == null) {
    		formula = new Formula();
    		Formula last = formulaService.getFormulaLatest(code);
    		if (last!=null) {
    			formula.setCode(code);
    			formula.setClock(clock);
    			formula.setDescription(last.getDescription());
    			formula.setTablename(last.getTablename());
    			formula.setUnitid(last.getUnitid());
    		}
    	}
    	List<String> clocks = formulaService.getClockByCode(parmas);
    	Map<String, Object> m = new HashMap<String, Object>();
    	m.put("result1", formula);
    	m.put("result2", clocks);
        return success(m);
    }
    
    @GetMapping("/aaa")
    public RESTfulResult aaa(){
    	Map<String, Object> mt = formulaService.getFormulaAndTbname("ZYA100W0011R", "201011");
    	String formula = mt.get("SOURCECODE").toString();
		String tbname = mt.get("TABLENAME").toString();
		return success(formula + "-" + tbname);
    }
    
    @ApiOperation(value="计算过程", notes="解析计算值为公式组成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "formula", value = "公式内容", required = true, dataType = "string")
    })
    @GetMapping(value = "/getAnaByVal/")
    public RESTfulResult getAnaByVal(@RequestParam HashMap<String, Object> parmas){
    	if(parmas.get("clock") == null || parmas.get("clock").toString().isEmpty()){
    		return failed(null, "请传入日期");
    	}
    	if(parmas.get("itemid") == null || parmas.get("itemid").toString().isEmpty()){
    		return failed(null, "请传入项目编号");
    	}
    	if(parmas.get("timegranid") == null || parmas.get("timegranid").toString().isEmpty()){
    		return failed(null, "请传入时间粒度");
    	}
    	String itemid = parmas.get("itemid").toString();
    	String timegranid = parmas.get("timegranid").toString();
    	String clock = parmas.get("clock").toString();
    	String clock_gs = clock.split("-")[0] + clock.split("-")[1];
        HashMap<String, Object> prm = new HashMap<String, Object>();
        prm.put("code", itemid);
        prm.put("clock", clock_gs);
        Formula formula = formulaService.getFormulaCodeClock(prm);
        String wzjx = formulaService.anaFormula(formula)+ "<br/>";
        String jx2 = formulaService.getAnaByVal(itemid,timegranid,clock);
        return success(wzjx + jx2);
    }
    @ApiOperation(value="获取公式", notes="根据项目编号获取公式")
    @GetMapping("/getByData")
    public RESTfulResult getFormulaData(@RequestParam HashMap<String, Object> parmas,Integer pageNum, Integer pageSize){
        if(parmas.get("tablename") != null && !parmas.get("tablename").toString().isEmpty()){
            String tablename = parmas.get("tablename").toString();
            if(!tablename.startsWith("'")){
                tablename = "'" + tablename.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("tablename", tablename);
        }
        PageList<Map<String, Object>> list = formulaService.getDateForPage(parmas, pageNum, pageSize);
        return success(list);
    }
}
