package com.steerinfo.ems.trmenergy.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.trmactitem.service.ITRmActItemService;
import com.steerinfo.ems.trmcalpoint.service.ITRmCalpointService;
import com.steerinfo.ems.trmenergy.model.TRmEnergy;
import com.steerinfo.ems.trmenergy.service.ITRmEnergyService;
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 java.util.*;

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

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

    @Autowired
    ITRmEnergyService tRmEnergyService;
    @Autowired
    ITRmCalpointService tRmCalpointService;
    @Autowired
    ITRmActItemService tRmActItemService;
    @Autowired
    IFormulaService formulaService;

    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmenergy:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmEnergy> list = tRmEnergyService.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("trmenergy:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmEnergy> list = tRmEnergyService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }
    
    @ApiOperation(value="创建", notes="根据TRmEnergy对象创建")
    @ApiImplicitParam(name = "tRmEnergy", value = "详细实体tRmEnergy", required = true, dataType = "TRmEnergy")
    //@RequiresPermissions("trmenergy:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmEnergy model){
        model.setState(model.getState() == null ? "1" : model.getState());
        if(model.getName() == null || "".equals(model.getName())){
            return failed(null, "能介名称不能为空");
        }
        else if(model.getEnergytypeid() == null || "".equals(model.getEnergytypeid())){
            return failed(null, "能介类型不能为空");
        }
        else{
            int maxid = tRmEnergyService.getMaxId(model) == null ? 1 : Integer.parseInt(tRmEnergyService.getMaxId(model)) + 1;
            model.setId(model.getEnergytypeid() + String.format("%03d", maxid));
            model.setSeqno(tRmEnergyService.getMaxSeqno());
            model.setCreateman(JwtUtil.getUseridByToken());
            TRmEnergy tRmEnergy = tRmEnergyService.add(model);
            Formula formula = new Formula();
            formula.setCode(model.getId());
            formula.setClock(DateUtils.getCurrentTime("yyyyMM"));
            formula.setDescription(model.getName() + "_折标系数");
            formula.setIsavailable("1");
            formula.setRevisor(model.getCreateman());
            formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
            formula.setTablename("T_RM_ENERGY");
            formula.setSourcecode("1");
            formulaService.add(formula);
            return success(tRmEnergy);
        }
    }

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

    @ApiOperation(value="更新详细信息", notes="根据url的id来指定更新对象，并根据传过来的tRmEnergy信息来更新详细信息")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String"),
        @ApiImplicitParam(name = "tRmEnergy", value = "详细实体tRmEnergy", required = true, dataType = "TRmEnergy")
    })
    //@RequiresPermissions("trmenergy:update")
    @PutMapping(value = "/{id}", produces  = "application/json;charset=UTF-8")
    public RESTfulResult update(@PathVariable String id, @RequestBody TRmEnergy model){
        LOGGER.info("能介信息维护表修改前数据是" + tRmEnergyService.getById(id).toString());
        model.setId(id);
        model.setUpdateman(JwtUtil.getUseridByToken());
        TRmEnergy tRmEnergy = tRmEnergyService.modify(model);
        LOGGER.info("能介信息维护表修改后数据是" + tRmEnergy.toString());
        return success(tRmEnergy);
    }

    @ApiOperation(value="删除", notes="根据用户ID来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmenergy:delete")
    @DeleteMapping(value = "/{id}")
    public RESTfulResult delete(@PathVariable String id){
        int failnum = 0;
        String failmsg = "";
        List<String> Ids = Arrays.asList(id.split(","));
        for(int i = 0;i < Ids.size();i++) {
            if(tRmCalpointService.queryByProperty("energyid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在计量点信息维护界面存在关系，请先删除对应关系！";
                continue;
            }
            if(tRmActItemService.queryByProperty("energyid", Ids.get(i)).size() != 0){
                failnum++;
                failmsg += Ids.get(i) + "在实绩项目维护界面存在关系，请先删除对应关系！";
                continue;
            }
            List<Formula> list = formulaService.getByCode(Ids.get(i));
               LOGGER.info("需要删除数据所对应的公式共" + list.size() + "条：");
            for (int j = 0;j < list.size();j++){
                LOGGER.info("该能介所对应的第" + (j + 1) + "条公式内容：" + list.get(i).toString());
            }
            formulaService.deleteBycode(Ids.get(i));
            LOGGER.info("能介信息维护表要删除的第" + (i + 1) + "条数据是" + tRmEnergyService.getById(Ids.get(i)).toString());
            tRmEnergyService.delete(Ids.get(i));
        }
        if(failnum > 0){
            return failed(null, "本次共删除" + Ids.size() + "条数据,其中成功" + (Ids.size() - failnum) + "条,失败" + failnum + "条,失败原因：" + failmsg);
        }
        return success();
    }

    @ApiOperation(value="获取能源层级", notes="查询能源上层节点名字和id")
    //@RequiresPermissions("trmenergy:view")
    @GetMapping(value = "/getparent/")
    public RESTfulResult getParent(){
        List<TRmEnergy> tRmEnergy = tRmEnergyService.getParent();
        return success(tRmEnergy);
    }
    @ApiOperation(value="能介信息下拉框", notes="获取名称跟id，可传参数isreal（是否实绩介质）,isbalance（是否平衡表介质）")
    @GetMapping("/selectNameAndId/")
    public RESTfulResult selectNameAndId(@RequestParam HashMap parameters){
        List<TRmEnergy> tRmEnergy = tRmEnergyService.selectNameAndId(parameters);
        return success(tRmEnergy);
    }

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