package com.steerinfo.ems.trmelectricitylocation.controller;

import com.steerinfo.auth.utils.JwtUtil;
import com.steerinfo.framework.controller.BaseRESTfulController;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.utils.collection.ListUtils;
import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.formula.mapper.FormulaMapper;
import com.steerinfo.ems.formula.model.Formula;
import com.steerinfo.ems.formula.service.IFormulaService;
import com.steerinfo.ems.trmcalpoint.mapper.TRmCalpointMapper;
import com.steerinfo.ems.trmcalpoint.model.TRmCalpoint;
import com.steerinfo.ems.trmcalpoint.service.ITRmCalpointService;
import com.steerinfo.ems.trmelectricitylocation.mapper.TRmElectricityLocationMapper;
import com.steerinfo.ems.trmelectricitylocation.model.TRmElectricityLocation;
import com.steerinfo.ems.trmelectricitylocation.service.ITRmElectricityLocationService;
import com.steerinfo.ems.trmtransfereactvalue.mapper.TRmTransfereActValueMapper;
import com.steerinfo.ems.trmtransfereactvalue.model.TRmTransfereActValue;
import com.steerinfo.ems.trmworkproc.mapper.TRmWorkprocMapper;
import com.steerinfo.ems.trmworkproc.model.TRmWorkproc;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.math.BigDecimal;

/**
 * TRmElectricityLocation RESTful接口：
 * @author generator
 * @version 1.0-SNAPSHORT 2020-10-16 09:49
 * 类描述
 * 修订历史：
 * 日期：2020-10-16
 * 作者：generator
 * 参考：
 * 描述：TRmElectricityLocation RESTful接口
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@RestController
@RequestMapping("/${api.version}/trmelectricitylocations")
public class TRmElectricityLocationController extends BaseRESTfulController {
	private static final Logger LOGGER = LoggerFactory.getLogger(TRmElectricityLocationController.class);
    @Autowired
    ITRmElectricityLocationService tRmElectricityLocationService;
    
    @Autowired
    private TRmElectricityLocationMapper tRmElectricityLocationMapper;
    
    @Autowired
    private TRmTransfereActValueMapper tRmTransfereActValueMapper;
    
    @Autowired
    ITRmCalpointService tRmCalpointService;
    
    @Autowired
    private TRmCalpointMapper tRmCalpointMapper;
    
    @Autowired
    IFormulaService formulaService;
    
    @Autowired
    private FormulaMapper formulaMapper;
    @ApiOperation(value="获取列表", notes="分页模糊查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmelectricitylocation:view")
    @GetMapping(value = "/like/")
    public RESTfulResult listLike(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        PageList<TRmElectricityLocation> list = tRmElectricityLocationService.queryLikeForPage(parmas, pageNum, pageSize);
        return success(list);
    }    
    @ApiOperation(value="获取详细信息", notes="根据url的id来获取详细信息")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmelectricitylocation:view")
    @GetMapping(value = "/{id}")
    public RESTfulResult get(@PathVariable String id){
        TRmElectricityLocation tRmElectricityLocation = tRmElectricityLocationService.getById(id);
        return success(tRmElectricityLocation);
    }

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

    @ApiOperation(value="删除", notes="根据url的id来指定删除对象")
    @ApiImplicitParam(paramType = "path", name = "id", value = "ID", required = true, dataType = "String")
    //@RequiresPermissions("trmelectricitylocation:delete")
    @DeleteMapping(value = "/{id}")//String
    public RESTfulResult delete(@PathVariable String id){
    	List<String> list = Arrays.asList(id.split(","));
    	if(ListUtils.isNotEmpty(list)) {
	    	List<String> ids = ListUtils.convertList(list);
			  tRmElectricityLocationService.delete(ids);
    	}
      return success();
    }
    @ApiOperation(value="根据工序-站所，获取转供电工序列表", notes="")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmelectricitylocation:view")
    @GetMapping(value = "/getWorkprocs")
    public RESTfulResult list(@RequestParam HashMap parmas){
        if(parmas.containsKey("workshop") && parmas.get("workshop") != null && !"".equals(parmas.get("workshop").toString())){
            String workshop = parmas.get("workshop").toString();
            if(workshop.indexOf(",") == -1){
                parmas.put("workshop", "and workshop = '" + workshop + "'");
            }
            else {
            	workshop = "and workshop in ('" + workshop.replaceAll(",", "','") + "')";
                parmas.put("workshop", workshop);
            }
        }
        List<TRmWorkproc> list = tRmElectricityLocationService.queryWorkprocs(parmas);
        return success(list);
    }
    @ApiOperation(value="批量更新详细信息", notes="根据传过来的tRmElectricityLocation数组信息来更新详细信息")
    @ApiImplicitParam(name = "tRmElectricityLocation", value = "详细实体tRmElectricityLocation", required = true, dataType = "TRmElectricityLocation")
    //@RequiresPermissions("trmelectricitylocation:update")
    @PutMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult batchupdate(@RequestBody TRmElectricityLocation[] model){
        int failnum = 0;
        String failmsg = "";
        List<TRmElectricityLocation> errorid = new ArrayList<>();
        for(int i = 0;i < model.length;i++){
        	if(model[i].getItemid() == null || model[i].getItemid().isEmpty()){
        		return failed(null, "请传入计量点编号");
        	}
        	if(model[i].getWorkshop() == null || model[i].getWorkshop().isEmpty()){
        		return failed(null, "请填写工序-站所");
        	}
        	if(model[i].getWorkprocid() == null || model[i].getWorkprocid().isEmpty()){
        		return failed(null, "请填写工序");
        	}
        	if(model[i].getLocation() == null || model[i].getLocation().isEmpty()){
        		return failed(null, "请填写位置");
        	}
        	if(model[i].getItemname() == null || model[i].getItemname().isEmpty()){
        		return failed(null, "请填写计量点名称");
        	}
        	TRmCalpoint old = tRmCalpointService.getById(model[i].getItemid());
        	// 修改电表编号
        	if(old.getTagid()==null || (!old.getTagid().equalsIgnoreCase(model[i].getBcode()) && model[i].getBcode()!=null)){
        		HashMap<String, Object> m = new HashMap<String, Object>();
            	m.put("bcode2", model[i].getBcode());
            	m.put("state", "1");
            	List<TRmElectricityLocation> l = tRmElectricityLocationMapper.selectByParameters(m);
            	if(l!=null && l.size()> 0){
            		return failed(null, "电度表编号已存在");
            	}
        	}
        }
        for(int i = 0;i < model.length;i++){
            try {
                LOGGER.info("用电地点维护修改的第" + (i + 1) + "条数据:");
                LOGGER.info("用电地点维护修改前数据是" + model[i].toString());
                model[i].setUpdateman(JwtUtil.getUseridByToken());
                TRmElectricityLocation tRmElectricityLocation = tRmElectricityLocationService.updateByUkey(model[i]);
                TRmCalpoint tc = tRmCalpointService.getById(model[i].getItemid());
                if(tc!=null){
                	tc.setItemdesc(model[i].getItemname() + "-转供电");
                    tc.setItemname(model[i].getItemname());
                    tc.setTagAlias(model[i].getItemname() + "-转供电");
                    tc.setLocateid(model[i].getLocation());
                    tc.setNetworkid(model[i].getWorkshop());
                    tc.setTagModulus(new BigDecimal(Integer.toString(model[i].getMods())));
                    tc.setCostid(model[i].getWorkprocid());
                    tc.setTagid(model[i].getBcode());
                    tRmCalpointService.modify(tc);
                    // 修改公式描述
                    Map<String, Object> pm = new HashMap<>();
                    pm.put("code", model[i].getItemid());
                    pm.put("description", model[i].getItemname() + "-转供电");
                    formulaMapper.updateDesBycode(pm);
                }
                LOGGER.info("用电地点维护修改后数据是" + tRmElectricityLocation.toString());
            } catch(Exception e){
            	e.printStackTrace();
                failnum++;
                errorid.add(model[i]);
                failmsg += "修改第" + (i + 1) + "条数据出现错误";
            }
        }
        if(failnum > 0){
            LOGGER.info("本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
            return success(errorid,"51","本次共修改" + model.length + "条数据,其中成功" + (model.length - failnum) + "条,失败" + failnum + "条,失败原因:" + failmsg);
        }
        return success();
    }

    @ApiOperation(value="批量删除", notes="根据传过来的tRmElectricityLocation数组信息来删除")
    @ApiImplicitParam(name = "tRmElectricityLocation", value = "详细实体tRmElectricityLocation", required = true, dataType = "TRmElectricityLocation")
    //@RequiresPermissions("trmelectricitylocation:delete")
    @DeleteMapping(value = "/", produces  = "application/json;charset=UTF-8")
    public RESTfulResult delete(@RequestBody TRmElectricityLocation[] model){
        if(model.length >= 1) {
            int failnum = 0;
            String failmsg = "";
            for (int i = 0; i < model.length; i++) {
            	HashMap<String, Object> m = new HashMap<String, Object>();
            	m.put("locationid", model[i].getId());
            	List<TRmTransfereActValue> l = tRmTransfereActValueMapper.selectByParameters(m);
            	List<Formula> list = formulaService.getFormulaByCode(model[i].getItemid());
            	if(list!=null && list.size()>0){
            		failnum++;
            		String item="";
            		for(Formula fa:list){
            			item += "[" + fa.getClock() +"版本，项目编号"+ fa.getCode() + "],";
            		}
            		item = item.substring(0,item.length()-1);
            		failmsg += item + " 公式中包含计量点(" + model[i].getItemid() + ")，请先处理";
            	}else if(l!=null && l.size()>0){
            		failnum++;
            		failmsg += "(计量点:" + model[i].getItemid()+ ")已有编辑或审核的数据.";
            	}else{
            		LOGGER.info(JwtUtil.getUseridByToken() + "用电地点维护要删除的第" + (i + 1) + "条数据是:" + model[i].toString());
                    tRmElectricityLocationService.delete(model[i].getId());
                    tRmCalpointMapper.deleteByPrimaryKey(model[i].getItemid());
                    formulaMapper.deleteBycode(model[i].getItemid());
            	}
            }
            if(failnum > 0){
                return success(null, "51","本次删除失败" + failnum + "条,失败原因:" + failmsg);
            }
            return success();
        } else {
            return failed(null, "请输入要删除的id");
        }
    }
    @ApiOperation(value="获取列表", notes="分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "查询页数", required = false, dataType = "Integer"),
        @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = false, dataType = "Integer")
    })
    //@RequiresPermissions("trmelectricitylocation:view")
    @GetMapping(value = "/")
    public RESTfulResult list(@RequestParam HashMap parmas,Integer pageNum, Integer pageSize){
        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("workshop") && parmas.get("workshop") != null && !"".equals(parmas.get("workshop").toString())){
            String workshop = parmas.get("workshop").toString();
            if(workshop.indexOf(",") == -1){
                parmas.put("workshop", "and workshop = '" + workshop + "'");
            }
            else {
            	workshop = "and workshop in ('" + workshop.replaceAll(",", "','") + "')";
                parmas.put("workshop", workshop);
            }
        }
        if(parmas.containsKey("location") && parmas.get("location") != null && !"".equals(parmas.get("location").toString())) {
            String locations = parmas.get("location").toString();
            if(locations.indexOf(",") == -1){
                parmas.put("location", "and LOCATION = '" + locations + "'");
            }
            else {
                locations = "and LOCATION in ('" + locations.replaceAll(",", "','") + "')";
                parmas.put("location", locations);
            }
        }
        if(parmas.containsKey("type") && parmas.get("type") != null && !"".equals(parmas.get("type").toString())){
            String types = parmas.get("type").toString();
            if(types.indexOf(",") == -1){
                parmas.put("type", "and TYPE = '" + types + "'");
            }
            else {
                types = "and TYPE in ('" + types.replaceAll(",", "','") + "')";
                parmas.put("type", types);
            }
        }
        if(parmas.containsKey("itemname") && parmas.get("itemname") != null && !"".equals(parmas.get("itemname").toString())){
            String itemname = parmas.get("itemname").toString();
            if(itemname.indexOf(",") == -1){
                parmas.put("itemname", "and ITEMNAME LIKE '%" + itemname + "%'");
            } else {
            	itemname = "and (ITEMNAME LIKE '%" + itemname.replaceAll(",", "%' OR ITEMNAME LIKE '%") + "%')";
                parmas.put("itemname", itemname);
            }
        }
        if(parmas.get("itemid") != null && !parmas.get("itemid").toString().isEmpty()){
            String itemid = parmas.get("itemid").toString();
            if(!itemid.startsWith("'")){
            	itemid = "'" + itemid.replaceAll(",", "','").replaceAll("，", "','") + "'";
            }
            parmas.put("itemid", itemid); 
        }
        if(parmas.containsKey("bcode") && parmas.get("bcode") != null && !"".equals(parmas.get("bcode").toString())){
            String bcode = parmas.get("bcode").toString().trim();
            parmas.put("bcode", "and BCODE like '%" + bcode + "%'");
        }
        if(parmas.containsKey("mods") && parmas.get("mods") != null && !"".equals(parmas.get("mods").toString())){
            String mods = parmas.get("mods").toString();
            if(mods.indexOf(",") == -1){
                parmas.put("itemname", "and MODS = '" + mods + "'");
            } else {
            	mods = "and MODS in ('" + mods.replaceAll(",", "','") + "')";
                parmas.put("itemname", mods);
            }
        }
        PageList<TRmElectricityLocation> list = tRmElectricityLocationService.queryForPage(parmas, pageNum, pageSize);
        return success(list);
    }

    @ApiOperation(value="创建", notes="根据TRmElectricityLocation对象创建")
    @ApiImplicitParam(name = "tRmElectricityLocation", value = "详细实体tRmElectricityLocation", required = true, dataType = "TRmElectricityLocation")
    //@RequiresPermissions("trmelectricitylocation:create")
    @PostMapping(value = "/")
    public RESTfulResult add(@ModelAttribute TRmElectricityLocation model){
    	if(model.getWorkshop() == null || model.getWorkshop().isEmpty()){
    		return failed(null, "请填写工序-站所");
    	}
    	if(model.getWorkprocid() == null || model.getWorkprocid().isEmpty()){
    		return failed(null, "请填写用电地点-工序");
    	}
    	if(model.getLocation() == null || model.getLocation().isEmpty()){
    		return failed(null, "请传入位置");
    	}
    	if(model.getItemname() == null || model.getItemname().isEmpty()){
    		return failed(null, "请填写计量点名称");
    	}
    	if(model.getBcode() == null || model.getBcode().isEmpty()){
    		return failed(null, "请填写电度表编号");
    	}
    	if(model.getFourgitem()==null ||model.getFourgitem().isEmpty()) {
    		return failed(null,"请填写4G计量点编号"); 
    				 
    	}
    	if(model.getMods()==null){
    		model.setMods(1);
    	}
    	HashMap<String, Object> m = new HashMap<String, Object>();
    	m.put("bcode2", model.getBcode());
    	m.put("state", "1");
    	List<TRmElectricityLocation> l = tRmElectricityLocationMapper.selectByParameters(m);
    	if(l!=null && l.size()> 0){
    		return failed(null, "电度表编号已存在");
    	}
        model.setCreateman(JwtUtil.getUseridByToken());
        String mid = tRmElectricityLocationMapper.getMaxId();
        int maxid = 0;
        maxid = mid == null ? 1 : Integer.parseInt(mid) + 1;
        model.setId(maxid + "");
        String ls = maxid < 1000 ? String.format("%04d", maxid) : maxid + "";
        model.setItemid("ZG00E0011" + ls);
        model.setCreateman(model.getCreateman());
        Date date=new Date();
        model.setCreatetime(date);
        TRmElectricityLocation tRmElectricityLocation = tRmElectricityLocationService.add(model);
        // 增加计量点
        TRmCalpoint tc = new TRmCalpoint();
        tc.setItemid("ZG00E0011" + ls);
        tc.setItemdesc(model.getItemname() + "-转供电");
        tc.setItemname(model.getItemname());
        tc.setTagAlias(model.getItemname() + "-转供电");
        tc.setLocateid(model.getLocation());
        tc.setEnergyid("E001");
        tc.setEnergytypeid("E");	
        tc.setPropertyid("1");
        tc.setDigits((short)0);
        tc.setUseflag("1");
        tc.setItemtype("MANUAL");
        tc.setNetworkid(model.getWorkshop());
        tc.setUnitid("006");
        tc.setTagModulus(new BigDecimal(Integer.toString(model.getMods())));
        tc.setCostid(model.getWorkprocid());
        tc.setMintimegranid("DAY");
        tc.setTagid(model.getBcode());
        int upSize = tRmCalpointMapper.updateByPrimaryKey(tc);
        if (upSize == 0) {
        	tRmCalpointMapper.insert(tc);
        }
        // 添加公式
        Formula formula = new Formula();
        formula.setCode(model.getItemid());
        formula.setDescription(model.getItemname() + "-转供电");
        formula.setClock("202001");
        formula.setIsavailable("1");
        formula.setRevisetime(DateUtils.getCurrentTime("yyyy-MM-dd HH:mm:ss"));
        formula.setTablename("T_RM_CALPOINT_VALUE");
        formula.setSourcecode("R(T_RM_CALPOINT_VALUE," + model.getItemid() + ")");
        formula.setRevisor(JwtUtil.getUseridByToken());
        formulaService.add(formula);
        return success(tRmElectricityLocation);
    }
}
