package com.steerinfo.ems.ifemsmesactitem.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.ifemsmesactitem.model.IfEmsMesActitem;
import com.steerinfo.ems.ifemsmesactitem.service.IIfEmsMesActitemService;
import com.steerinfo.ems.trmactvalue.service.ITRmActValueService;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.util.Base64.Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(IfEmsMesActitemController.class);
    @Autowired
    IIfEmsMesActitemService ifEmsMesActitemService;
    @Autowired
    ITRmActValueService tRmActValueService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("ifemsmesactitem:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        //根据时间粒度动态查询时间段
        if(parmas.containsKey("timegranid") && parmas.get("timegranid") != null && !"".equals(parmas.get("timegranid").toString())){
            String[] timegranarray = parmas.get("timegranid").toString().split(",");
            String format = "";
            String condition = "and (";
            for (int i = 0;i< timegranarray.length;i++){
                if(i > 0){
                    condition += " or";
                }
                if("YEAR".equalsIgnoreCase(timegranarray[i])){
                    format = "', 1, 4)";
                    condition += " TIMEGRANID = 'YEAR'";
                }
                if("MONTH".equalsIgnoreCase(timegranarray[i])){
                    format = "', 1, 7)";
                    condition += " TIMEGRANID = 'MONTH'";
                }
                if("DAY".equalsIgnoreCase(timegranarray[i])){
                    format = "', 1, 10)";
                    condition += " TIMEGRANID = 'DAY'";
                }
                if(parmas.containsKey("clock") && parmas.get("clock") != null && !"".equals(parmas.get("clock").toString())){
                    condition += " and CLOCK >= SUBSTR('" + parmas.get("clock").toString() + format;
                }
                if(parmas.containsKey("clocke") && parmas.get("clocke") != null && !"".equals(parmas.get("clocke").toString())){
                    condition += " and CLOCK <= SUBSTR('" + parmas.get("clocke").toString() + format;
                }
            }
            parmas.put("condition", condition + ")");
        }
        if(parmas.containsKey("state") && parmas.get("state") != null && !"".equals(parmas.get("state").toString())){
            String states = parmas.get("state").toString();
            if(states.indexOf(",") == -1){
                parmas.put("state", "and STATE = '" + states + "'");
            }
            else {
                states = "and STATE in ('" + states.replaceAll(",", "','") + "')";
                parmas.put("state", states);
            }
        }
        if(parmas.containsKey("propertyid") && parmas.get("propertyid") != null && !"".equals(parmas.get("propertyid").toString())){
            String propertyids = parmas.get("propertyid").toString();
            if(propertyids.indexOf(",") == -1){
                parmas.put("propertyid", "and PROPERTYID = '" + propertyids + "'");
            }
            else {
                propertyids = "and PROPERTYID in ('" + propertyids.replaceAll(",", "','") + "')";
                parmas.put("propertyid", propertyids);
            }
        }
        if(parmas.containsKey("unitid") && parmas.get("unitid") != null && !"".equals(parmas.get("unitid").toString())){
            String unitids = parmas.get("unitid").toString();
            if(unitids.indexOf(",") == -1){
                parmas.put("unitid", "and UNITID = '" + unitids + "'");
            }
            else {
                unitids = "and UNITID in ('" + unitids.replaceAll(",", "','") + "')";
                parmas.put("unitid", unitids);
            }
        }
        if(parmas.containsKey("workprocid") && parmas.get("workprocid") != null && !"".equals(parmas.get("workprocid").toString())){
            String workprocids = parmas.get("workprocid").toString();
            if(workprocids.indexOf(",") == -1){
                parmas.put("workprocid", "and WORKPROCID = '" + workprocids + "'");
            }
            else {
                workprocids = "and WORKPROCID in ('" + workprocids.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocids);
            }
        }
        if(parmas.containsKey("itemid") && parmas.get("itemid") != null && !"".equals(parmas.get("itemid").toString())) {
            String itemids = parmas.get("itemid").toString();
            if(itemids.indexOf(",") == -1){
                parmas.put("itemid", "and ITEMID LIKE '%" + itemids + "%'");
            }
            else {
                itemids = "and (ITEMID LIKE '%" + itemids.replaceAll(",", "%' OR ITEMID LIKE '%") + "%')";
                parmas.put("itemid", itemids);
            }
        }
        if(parmas.containsKey("itemname") && parmas.get("itemname") != null && !"".equals(parmas.get("itemname").toString())) {
            String itemnames = parmas.get("itemname").toString();
            if(itemnames.indexOf(",") == -1){
                parmas.put("itemname", "and ITEMNAME LIKE '%" + itemnames + "%'");
            }
            else {
                itemnames = "and (ITEMNAME LIKE '%" + itemnames.replaceAll(",", "%' OR ITEMNAME LIKE '%") + "%')";
                parmas.put("itemname", itemnames);
            }
        }
        if(parmas.containsKey("itemdesc") && parmas.get("itemdesc") != null && !"".equals(parmas.get("itemdesc").toString())) {
            String itemdescs = parmas.get("itemdesc").toString();
            if(itemdescs.indexOf(",") == -1){
                parmas.put("itemdesc", "and ITEMDESC LIKE '%" + itemdescs + "%'");
            }
            else {
                itemdescs = "and (ITEMDESC LIKE '%" + itemdescs.replaceAll(",", "%' OR ITEMDESC LIKE '%") + "%')";
                parmas.put("itemdesc", itemdescs);
            }
        }
        if(parmas.containsKey("energyid") && parmas.get("energyid") != null && !"".equals(parmas.get("energyid").toString())){
            String energyids = parmas.get("energyid").toString();
            if(energyids.indexOf(",") == -1){
                parmas.put("energyid", "and ENERGYID = '" + energyids + "'");
            }
            else {
                energyids = "and ENERGYID in ('" + energyids.replaceAll(",", "','") + "')";
                parmas.put("energyid", energyids);
            }
        }
        PageList<IfEmsMesActitem> list = ifEmsMesActitemService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="获取数据到能耗实绩确认表", notes="根据状态来获取数据")
    @GetMapping(value = "/getdatafromems/")
    public RESTfulResult getdatafromems(){
        return success(ifEmsMesActitemService.getUploadData());
    }

    @ApiOperation(value="批量更新详细信息", notes="根据传过来的IfEmsMesActitem数组信息来更新详细信息")
    @ApiImplicitParam(name = "ifEmsMesActitem", value = "详细实体IfEmsMesActitem", required = true, dataType = "IfEmsMesActitem")
    //@RequiresPermissions("trmunit:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody IfEmsMesActitem[] model){
        int failnum = 0;
        List<Long> errorid = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
            if (tRmActValueService.getByFid(model[i].getId()).size() > 0){
                LOGGER.info("能耗数据管理修改的第" + (i + 1) + "条数据:");
                LOGGER.info("能耗数据管理修改前数据是" + ifEmsMesActitemService.getById(model[i].getId()).toString());
                model[i].setOperatorDate(DateUtils.getCurrentTimetoDate("yyyy-MM-dd HH:mm:ss"));
                model[i].setOperatorMan(JwtUtil.getUseridByToken());
                IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.modify(model[i]);
                LOGGER.info("能耗数据管理修改后数据是" + ifEmsMesActitem.toString());
            }
            else {
                errorid.add(model[i].getId());
                failnum++;
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败的数据id:" + errorid.toString());
            return success(errorid,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,由于实绩项目数据已被修改而失败" + failnum + "条,失败id：" + errorid.toString());
        }
        return success();
    }
    
    /**
     * 查询EMS能介数据，把小于等于500条状态为1的数据显示返回
     * 
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/getemsdata/")
    public RESTfulResult get() throws IOException{
    	ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
		//String sessionAuth = (String) request.getSession().getAttribute("auth");
		if (!checkHeaderAuth(request, response)) {
			response.setStatus(401);
			response.setHeader("Cache-Control", "no-store");
			response.setDateHeader("Expires", 0);
			response.setHeader("WWW-authenticate", "Basic Realm=\"ems auth\"");
			return failed(null, "验证出错了！");
		} else {
			response.setHeader("Cache-Control", "no-store");
			response.setDateHeader("Expires", 0);
			List<IfEmsMesActitem> list = ifEmsMesActitemService.getDatatoMes();
			return success(list);
		}
    }
    
    /**
     * 反写信息，改写状态为2：已上传
     * 
     * @param id
     * 	能耗实绩确认表主键：id
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/updatestate/")
    public RESTfulResult post(@RequestBody IfEmsMesActitem[] model) throws IOException{
    	ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
		if (!checkHeaderAuth(request, response)) {
			response.setStatus(401);
			response.setHeader("Cache-Control", "no-store");
			response.setDateHeader("Expires", 0);
			response.setHeader("WWW-authenticate", "Basic Realm=\"ems auth\"");
			return failed(null, "验证出错了！");
		} else {
			response.setHeader("Cache-Control", "no-store");
			response.setDateHeader("Expires", 0);
			for (int i = 0;i <model.length;i++) {
                ifEmsMesActitemService.updateState(model[i]);
            }
			return success();
		}
    }
    
	private boolean checkHeaderAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String auth = request.getHeader("Authorization");
		System.out.println("auth is:" + auth);
		if ((auth != null) && (auth.length() > 6)) {
			auth = auth.substring(6, auth.length());
			System.out.println("auth encoded in base64 is " + getFromBASE64(auth));
			String decodedAuth = getFromBASE64(auth);
			// 账号密码zgems:steering
			if(decodedAuth.equals("zgems:steering")){
				return true;
			}
			return false;
		} else {
			return false;
		}
	}
    
	private String getFromBASE64(String s) {
		if (s == null) {
			return null;
		}
		Decoder decoder = Base64.getDecoder();
		try {
			byte[] b = decoder.decode(s);
			return new String(b);
		} catch (Exception e) {
			return null;
		}
	}

    @ApiOperation(value="修改自动上传状态", notes="根据状态来获取数据")
    @PostMapping(value = "/uploadstate/")
    public RESTfulResult setuploadstate(@RequestParam String uploadstate){
        //PropUtils.saveConf("EMS_AUTO_UPLOAD", uploadstate);
        Map<String, Object> params = new HashMap<>();
        params.put("paramkey", "ems_auto_upload");
        params.put("paramvalue", uploadstate);
        if(ifEmsMesActitemService.updateParam(params) == 0){
            params.put("keyconmment", "EMS能耗数据管理，是否自动上传，0手动，1自动");
            ifEmsMesActitemService.insertParam(params);
        }
        return success();
    }

    @ApiOperation(value="获取自动上传状态", notes="获取自动上传状态")
    @GetMapping(value = "/uploadstate/")
    public RESTfulResult getuploadstate(){
        Map<String, Object> params = new HashMap<>();
        params.put("paramkey", "ems_auto_upload");
        List<Map<String, Object>> list = ifEmsMesActitemService.selectParam(params);
        if(list.size() == 0){
            params.put("paramvalue", "0");
            params.put("keyconmment", "EMS能耗数据管理，是否自动上传，0手动，1自动");
            ifEmsMesActitemService.insertParam(params);
            return success("0");
        }
        else {
            return success(list.get(0).get("PARAM_VALUE").toString());
        }
    }

/**
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("ifemsmesactitem:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        if(parmas.containsKey("workprocid")){
            String workprocids = parmas.get("workprocid").toString();
            if("".equals(workprocids)){
                parmas.put("workprocid", "");
            }
            else if(workprocids.indexOf(",") == -1){
                parmas.put("workprocid", "and T.WORKPROCID = " + workprocids);
            }
            else {
                workprocids = "and T.WORKPROCID in ('" + workprocids.replaceAll(",", "','") + "')";
                parmas.put("workprocid", workprocids);
            }
        }
        if(parmas.containsKey("itemid")) {
            String itemids = parmas.get("itemid").toString();
            if("".equals(itemids)){
                parmas.put("itemid", "");
            }
            else if(itemids.indexOf(",") == -1){
                parmas.put("itemid", "and T.ITEMID LIKE '%" + itemids + "%'");
            }
            else {
                itemids = "and (T.ITEMID LIKE '%" + itemids.replaceAll(",", "%' OR ITEMID LIKE '%") + "%')";
                parmas.put("itemid", itemids);
            }
        }
        if(parmas.containsKey("itemname")) {
            String itemnames = parmas.get("itemname").toString();
            if("".equals(itemnames)){
                parmas.put("itemname", "");
            }
            else if(itemnames.indexOf(",") == -1){
                parmas.put("itemname", "and T.ITEMNAME LIKE '%" + itemnames + "%'");
            }
            else {
                itemnames = "and (T.ITEMNAME LIKE '%" + itemnames.replaceAll(",", "%' OR ITEMNAME LIKE '%") + "%')";
                parmas.put("itemname", itemnames);
            }
        }
        PageList<IfEmsMesActitem> list = ifEmsMesActitemService.queryPage(parmas, pageNum, pageSize);
        return success(list);
    }

 @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
 @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "Long")
 //@RequiresPermissions("ifemsmesactitem:view")
 @GetMapping(value = "/{id}")
 public RESTfulResult get(@PathVariable Long id){
 IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.getById(id);
 return success(ifEmsMesActitem);
 }
 @ApiOperation(value="获取列表", notes="分页模糊查询")
 @ApiImplicitParams({
 @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
 @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
 })
 //@RequiresPermissions("ifemsmesactitem:view")
 @GetMapping(value = "/like/")
 public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
 PageList<IfEmsMesActitem> list = ifEmsMesActitemService.queryLikeForPage(parmas, pageNum, pageSize);
 return success(list);
 }

 @ApiOperation(value="创建", notes="根据IfEmsMesActitem对象创建")
 @ApiImplicitParam(name = "ifEmsMesActitem", value = "详细实体ifEmsMesActitem", required = true, dataType = "IfEmsMesActitem")
 //@RequiresPermissions("ifemsmesactitem:create")
 @PostMapping(value = "/")
 public RESTfulResult add(@ModelAttribute IfEmsMesActitem model){
 IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.add(model);
 return success(ifEmsMesActitem);
 }
 @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的ifEmsMesActitem信息来更新详细信息")
 @ApiImplicitParams({
 @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "Long"),
 @ApiImplicitParam(name = "ifEmsMesActitem", value = "详细实体ifEmsMesActitem", required = true, dataType = "IfEmsMesActitem")
 })
 //@RequiresPermissions("ifemsmesactitem:update")
 @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
 public RESTfulResult update(@PathVariable Long id, @RequestBody IfEmsMesActitem model){
 model.setId(id);
 IfEmsMesActitem ifEmsMesActitem = ifEmsMesActitemService.modify(model);
 return success(ifEmsMesActitem);
 }
    */
}
