package com.unis.base.server.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.unis.base.common.vo.DCfxxsjyVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.github.pagehelper.PageInfo;
import com.unis.common.utils.ResponseWrapper;
import com.unis.base.common.vo.OiltankQueryVO;
import com.unis.base.common.vo.OiltankVO;
import com.unis.base.server.service.OiltankService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author huangxing
 * @version 1.0
 * @Title DYgxxsjyController
 * @ProjectName 油罐信息 Controller
 * @Description
 * @date 2019/07/22 17点26分
 */
@RestController
@Api(value = "油罐信息", tags = "油罐信息维护")
@Slf4j
public class OiltankController {

	@Autowired
	private OiltankService oiltankService;

	/**
	 * @author huangxing
	 * @Description 获取油罐列表
	 * @param oiltankVO 油罐编号，油罐名称，库点编号，库点名称，油罐类型，油罐状态
	 * @return 油罐信息列表
	 */
	@ApiOperation(value = "获取油罐信息列表", notes = "参数：油罐编号，油罐名称，库点编号，库点名称，建设年代开始时间，建设年代结束时间")
	@PostMapping(value = "/oiltankList")
    public ResponseWrapper getOiltankList(@RequestBody OiltankQueryVO oiltankVO){
        try {
        	List<OiltankVO> oiltankVOs = oiltankService.getOiltankList(oiltankVO);
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), oiltankVOs);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * @author huangxing
	 * @Description 获取油罐信息列表
	 * @param oiltankVO 油罐编号，油罐名称，库点编号，库点名称，油罐类型，油罐状态
	 * @return 油罐信息列表
	 */
	@ApiOperation(value = "分页获取油罐信息列表", notes = "参数：油罐编号，油罐名称，库点编号，库点名称，油罐类型，建筑类型，油罐状态")
	@PostMapping(value = "/oiltankPage/{pageNum}/{pageSize}")
	public ResponseWrapper getOiltankPage(@RequestBody OiltankQueryVO oiltankVO,@PathVariable("pageNum")Integer pageNum,@PathVariable("pageSize") Integer pageSize) {
		try {
			PageInfo<OiltankVO> pageInfos = new PageInfo<OiltankVO>(oiltankService.getOiltankPage(oiltankVO,pageNum,pageSize)) ;
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@ApiOperation(value = "分页获取油罐信息列表", notes = "参数：油罐编号，油罐名称，库点编号，库点名称，油罐类型，建筑类型，油罐状态")
	@PostMapping(value = "/oiltankPages/{pageNum}/{pageSize}")
	public ResponseWrapper getOiltankPages(@RequestBody OiltankQueryVO oiltankVO,@PathVariable("pageNum")Integer
			pageNum,@PathVariable("pageSize") Integer pageSize) {
		try {
			PageInfo<OiltankVO> pageInfos = new PageInfo<OiltankVO>(oiltankService.getOiltankPages(oiltankVO,pageNum,pageSize)) ;
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), pageInfos);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}


	/**
	 * @author huangxing
	 * @Description 根据油罐编码获取油罐信息
	 * @return 油罐信息
	 */
	@ApiOperation(value = "根据油罐编码获取油罐信息", notes = "参数：油罐编号")
	@GetMapping(value = "/oiltank/{ygbh}")
	public ResponseWrapper getOiltankInfoByygbh(@PathVariable("ygbh")String ygbh) {
		try {
			OiltankVO oiltankVO = oiltankService.getOiltankInfoByygbh(ygbh);
			if(oiltankVO == null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "获取失败，油罐不存在", null);
			}
            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), oiltankVO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	/**
	 * @author huangxing
	 * @Description 更新油罐信息
	 * @return 更新状态
	 */
	@ApiOperation(value = "更新油罐信息", notes = "参数：油罐编号")
	@PutMapping(value = "/update")
	public ResponseWrapper update(@RequestBody  @Validated OiltankVO oiltankVO, BindingResult bindingResult) {
        log.info("update 油罐 params >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {}", JSONObject.toJSONString(oiltankVO));
		try{
			if (bindingResult.hasFieldErrors()){
				//获取与字段相关的所有错误
				List<FieldError> fieldErrors = bindingResult.getFieldErrors();
				List<String> msgList = new ArrayList<>();
				for (FieldError fieldError : fieldErrors){
					msgList.add(fieldError.getField() + " : " + fieldError.getDefaultMessage());
				}
				return ResponseWrapper.error(msgList.toString());
			}
			if(null == oiltankVO.getSjgr() || oiltankVO.getSjgr()<=0) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "设计罐容必填且不能小于等于0", null);
			}
			if(null == oiltankVO.getYgnzj() || oiltankVO.getYgnzj()<=0){
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "油罐内直径必填且不能小于等于0", null);
			}
			if(null == oiltankVO.getYggd() || oiltankVO.getYggd()<=0){
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "油罐高度必填且不能小于等于0", null);
			}
			if(StringUtils.isEmpty(oiltankVO.getId())) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
			}
			OiltankQueryVO oiltankQueryVO = new OiltankQueryVO();
			oiltankQueryVO.setKddm(oiltankVO.getKddm());
			oiltankQueryVO.setYgbh(oiltankVO.getRealYgbh());
			OiltankVO vo = oiltankService.getOilTankInfo(oiltankQueryVO);
			if (vo!= null && !vo.getId().equals(oiltankVO.getId())) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "油罐编码已存在，不可与其它油罐编码重复！", null);
			}
			int x = oiltankService.update(oiltankVO);
			if(x>0) {
	            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
	            return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "该油罐不存在", null);
            } else if (OiltankVO.UPDATE_RES.INVALID.equalVal(x)) {
                return ResponseWrapper.error(HttpStatus.BAD_REQUEST.value(), DCfxxsjyVO.UPDATE_RES.INVALID.getName(), null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@ApiOperation(value = "批量更新油罐信息")
	@PutMapping(value = "/oiltankBatch")
	public ResponseWrapper oiltankBatch(@RequestBody OiltankVO oiltankVO) {
		try {
			List<String> ids = oiltankVO.getIds();
			for (String id:ids) {
				oiltankVO.setId(id);
				int x = oiltankService.update(oiltankVO);
				if(x>0) {
					return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
				} else if (x==0) {
					return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "该油罐不存在", null);
				}
			}
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(), "服务错误，请联系管理员");
	}

	/**
	 * @author huangxing
	 * @Description 删除油罐信息
	 * @param ygbh 参数：油罐编号
	 * @return 状态
	 */
	@DeleteMapping(value="/oiltank/{id}")
	@ApiOperation(value = "根据油罐编号删除油罐信息", notes = "参数：油罐编号")
	public ResponseWrapper delete(@PathVariable("id")String id) {
		try{
			int x = oiltankService.delete(id);
			if(x>0) {
	            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
	            return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "删除失败", null);
			} else {
				 return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "删除失败,请油罐编号是否正确", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }

	/**
	 * @author huangxing
	 * @Description 新增油罐信息
	 * @param oiltankVO 油罐信息对象
	 * @return 新增状态
	 */
	@PostMapping(value = "/insert")
	@ApiOperation(value = "新增油罐信息", notes = "参数：油罐名称，油罐类型")
    public ResponseWrapper insert(@RequestBody @Validated OiltankVO oiltankVO, BindingResult bindingResult) {
		try{
			if (bindingResult.hasFieldErrors()){
				//获取与字段相关的所有错误
				List<FieldError> fieldErrors = bindingResult.getFieldErrors();
				List<String> msgList = new ArrayList<>();
				for (FieldError fieldError : fieldErrors){
					msgList.add(fieldError.getField() + " : " + fieldError.getDefaultMessage());
				}
				return ResponseWrapper.error(msgList.toString());
			}
			if(null == oiltankVO.getSjgr() || oiltankVO.getSjgr()<=0) {
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "设计罐容必填且不能小于等于0", null);
			}
			if(null == oiltankVO.getYgnzj() || oiltankVO.getYgnzj()<=0){
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "油罐内直径必填且不能小于等于0", null);
			}
			if(null == oiltankVO.getYggd() || oiltankVO.getYggd()<=0){
				return ResponseWrapper.success(HttpStatus.NON_AUTHORITATIVE_INFORMATION.value(), "油罐高度必填且不能小于等于0", null);
			}
			OiltankQueryVO oiltankQueryVO = new OiltankQueryVO();
			oiltankQueryVO.setKddm(oiltankVO.getKddm());
			oiltankQueryVO.setYgbh(oiltankVO.getRealYgbh());
			if ((oiltankService.getOilTankInfo(oiltankQueryVO))!= null) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "油罐编码已存在，不可与其它油罐编码重复！", null);
			}
			OiltankVO vo = oiltankService.insert(oiltankVO);
			if(vo!=null) {
	            return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),vo);
			} else {
	            return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "添加油罐失败,输入正确的库点编号", null);
			}
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
    }
	/**
	 * @author huangxing
	 * @Description 根据油罐编号处理申请状态
	 * @param ygbh 参数：油罐编号
	 * @return 状态
	 */
	@PostMapping(value="/oiltank/updateSqzt")
	@ApiOperation(value = "根据油罐编号处理申请状态（0 可编辑 1 不可编辑【当申请状态不是驳回时】）", notes = "参数：油罐编号,申请状态")
	public ResponseWrapper updateSqzt(@RequestParam(name = "ygbh", required = true)String ygbh, @RequestParam(name = "sqzt", required = true)String sqzt) {
		try{
			if(StringUtils.isEmpty(ygbh)) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "油罐编号：有必传参数为空", null);
			}
			int x = oiltankService.updateSqzt(ygbh,sqzt);
			if(x>0) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else if (x==0) {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "更新状态失败", null);
			} else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "更新状态失败,请油罐编号是否正确", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}
	/**
	 * @author lgd
	 * @Description 初始化油罐信息
	 * @return 新增状态
	 */
	@PostMapping(value = "/oiltank/initData")
	@ApiOperation(value = "初始化油罐信息", notes = "初始化油罐信息")
	public ResponseWrapper initData() {
		try{
			boolean result = oiltankService.initData();
			if(result) {
				return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
			} else {
				return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "初始化油罐信息失败", null);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@PostMapping(value = "/oiltank/getOilTankInfo")
	@ApiOperation(value = "根据参数获取油罐信息", notes = "根据参数获取油罐信息")
	public ResponseWrapper getOilTankInfo(@RequestBody OiltankQueryVO oiltankQueryVO) {
		try {
			OiltankVO oiltankVO = oiltankService.getOilTankInfo(oiltankQueryVO);
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), oiltankVO);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@PostMapping(value = "/oiltank/getOilTankInfoList")
	@ApiOperation(value = "根据参数获取油罐信息集合", notes = "根据参数获取油罐信息集合")
	public ResponseWrapper getOilTankInfoList(@RequestBody OiltankQueryVO oiltankQueryVO) {
		try {
			List<OiltankVO> oilTankInfoList = oiltankService.getOilTankInfoList(oiltankQueryVO);
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(), oilTankInfoList);
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

	@ApiOperation(value = "保存油罐信息下发结果", notes = "参数：油罐编号")
	@PutMapping(value = "/updateSendResult")
	public ResponseWrapper updateSendResult(@RequestBody OiltankVO oiltankVO) {
		int x = oiltankService.update(oiltankVO);
		if(x>0) {
			return ResponseWrapper.success(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase(),null);
		} else if (x==0) {
			return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "该油罐不存在", null);
		}
		return ResponseWrapper.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),"服务错误，请联系管理员");
	}

}
