package com.unis.base.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.unis.base.app.service.PushService;
import com.unis.base.client.OiltankFeign;
import com.unis.base.common.vo.CompanyVO;
import com.unis.base.common.vo.OiltankImportVO;
import com.unis.base.common.vo.OiltankQueryVO;
import com.unis.base.common.vo.OiltankVO;
import com.unis.common.utils.JsonUtils;
import com.unis.common.utils.POI4Util;
import com.unis.common.utils.ResponseWrapper;
import com.unis.common.vo.poi.Column;
import com.unis.common.vo.poi.Line;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.GsonJsonParser;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @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 OiltankFeign oiltankFeign;

	@Autowired
	private PushService pushService;

	@ApiOperation(value = "获取油罐信息列表", notes = "参数：油罐编号，油罐名称，库点编号，库点名称，建设年代开始时间，建设年代结束时间")
	@PostMapping(value = "/oiltankList")
    public ResponseWrapper getOiltankList(@RequestBody OiltankQueryVO oiltankVO){
        return oiltankFeign.getOiltankList(oiltankVO);
    }

	@ApiOperation(value = "分页获取油罐信息列表", notes = "参数：油罐编号，油罐名称，库点编号，库点名称，油罐类型，建筑类型，油罐状态")
	@PostMapping(value = "/oiltankPage/{pageNum}/{pageSize}")
	public ResponseWrapper getOiltankPage(@RequestBody OiltankQueryVO oiltankVO, @PathVariable("pageNum") Integer pageNum, @PathVariable("pageSize") Integer pageSize) {
		return oiltankFeign.getOiltankPage(oiltankVO,pageNum,pageSize) ;
	}


	@ApiOperation(value = "根据油罐编码获取油罐信息", notes = "参数：油罐编号")
	@GetMapping(value = "/oiltank/{ygbh}")
	public ResponseWrapper getOiltankInfoByygbh(@PathVariable("ygbh") String ygbh) {
        return oiltankFeign.getOiltankInfoByygbh(ygbh);
	}

	@PostMapping(value = "/oiltank")
	@ApiOperation(value = "新增油罐信息", notes = "参数：油罐名称，油罐类型")
	public ResponseWrapper insert(@RequestBody OiltankVO oiltankVO) {
		oiltankVO.buildInsertData();
		return oiltankFeign.insert(oiltankVO);
	}

	@ApiOperation(value = "更新油罐信息", notes = "参数：油罐编号")
	@PutMapping(value = "/oiltank")
	public ResponseWrapper update(@RequestBody OiltankVO oiltankVO) {
		oiltankVO.buildUpdateData();
		ResponseWrapper responseWrapper = oiltankFeign.update(oiltankVO);
		if(responseWrapper.isSuccess()) {
			if(5 == oiltankVO.getSfba()) { // 审核通过，下发库级
				ResponseWrapper result = oiltankFeign.getOiltankInfoByygbh(oiltankVO.getId());
				OiltankVO oiltankInfo = JsonUtils.parse(JsonUtils.serialize(result.getData()),OiltankVO.class);
				JSONObject obj = (JSONObject) JSONObject.toJSON(oiltankInfo);
				String sendResult = pushService.push(obj,"oilTankApi");
				if(StringUtils.isNotEmpty(sendResult)) {
					oiltankVO = new OiltankVO();
					oiltankVO.setId(oiltankInfo.getId());
					oiltankVO.setSendResult(sendResult);
					oiltankFeign.updateSendResult(oiltankVO);
				}
			}
		}
		return responseWrapper;
	}

	@ApiOperation(value = "批量更新油罐信息")
	@PutMapping(value = "/oiltankBatch")
	public ResponseWrapper oiltankBatch(@RequestBody OiltankVO oiltankVO) {
		if (oiltankVO.getIds() == null || oiltankVO.getIds().isEmpty() || oiltankVO.getIds().containsAll(Collections.singleton(null))) {
			return ResponseWrapper.success(HttpStatus.BAD_REQUEST.value(), "有必传参数为空", null);
		}
		oiltankVO.buildUpdateData();
		ResponseWrapper responseWrapper = oiltankFeign.oiltankBatch(oiltankVO);
		if(responseWrapper.isSuccess()) {
			if(5 == oiltankVO.getSfba()) { // 审核通过，下发库级
				List<String> ids = oiltankVO.getIds();
				for (String id:ids) {
					ResponseWrapper result = oiltankFeign.getOiltankInfoByygbh(id);
					OiltankVO oiltankInfo = JsonUtils.parse(JsonUtils.serialize(result.getData()),OiltankVO.class);
					JSONObject obj = (JSONObject) JSONObject.toJSON(oiltankInfo);
					String sendResult = pushService.push(obj,"oilTankApi");
					if(StringUtils.isNotEmpty(sendResult)) {
						oiltankVO = new OiltankVO();
						oiltankVO.setId(oiltankInfo.getId());
						oiltankVO.setSendResult(sendResult);
						oiltankFeign.updateSendResult(oiltankVO);
					}
				}

			}
		}
		return responseWrapper;
	}

	@ApiOperation(value = "油罐信息删除")
	@PostMapping(value = "/oiltank/delete")
	public ResponseWrapper deleteOiltank(@RequestParam(value = "id",required = true) String id) {
		return oiltankFeign.delete(id);
	}

	@ApiOperation(value = "油罐信息导入")
	@PostMapping(value = "/impOiltank")
	public ResponseWrapper impContract(@RequestPart(value = "file") MultipartFile file) {
		Map<String, Object> map;
		int success = 0;
		int fail = 0;
		List<String> msgList = new ArrayList<>();
		try {
			List<String> columns = new ArrayList<String>();
			Field[] declaredFields = OiltankImportVO.class.getDeclaredFields();
			for (Field field : declaredFields) {
				columns.add(field.getName());
			}
			map = POI4Util.uploadExcel(file, columns);
			Integer state = Integer.valueOf(map.get("state")+"");
			if(state == 1) {
				List<Line> lines = (List<Line>) map.get("lines");
				for (int i = 0; i < lines.size(); i++) {
					Line line = lines.get(i);
					List<Column> columnsL = line.getColumns();
					OiltankVO vo = new OiltankVO();
					if (!ObjectUtils.isEmpty(columnsL.get(0).getValue())) {
						vo.setTyshxydm(columnsL.get(0).getValue().toString());
						vo.setKddm(columnsL.get(0).getValue().toString()+"001");
					} else {
						return ResponseWrapper.error("统一社会信用代码不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(1).getValue())) {
						String ygbm = columnsL.get(1).getValue().toString();
						if(ygbm.matches("YG+[0-9]{3}")) {
							vo.setRealYgbh(ygbm);
						} else {
							return ResponseWrapper.error("请正确填写油罐编码");
						}
					} else {
						return ResponseWrapper.error("油罐编码不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(2).getValue())) {
						vo.setYgmc(columnsL.get(2).getValue().toString());
					} else {
						return ResponseWrapper.error("油罐名称不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(3).getValue())) {
						vo.setSjgr(Double.parseDouble(columnsL.get(3).getValue().toString()));
					} else {
						return ResponseWrapper.error("设计罐容不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(4).getValue())) {
						vo.setYggd(Double.parseDouble(columnsL.get(4).getValue().toString()));
					} else {
						return ResponseWrapper.error("高度不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(5).getValue())) {
						vo.setYgjfssssfwh(columnsL.get(5).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("油罐及附属设施是否完好不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(6).getValue())) {
						vo.setYglx(columnsL.get(6).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("油罐类型不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(7).getValue())) {
						vo.setYwjrzz(columnsL.get(7).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("有无加热装置不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(8).getValue())) {
						vo.setYgdmj(Double.parseDouble(columnsL.get(8).getValue().toString()));
					} else {
						return ResponseWrapper.error("底面积不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(9).getValue())) {
						vo.setYgnzj(Double.parseDouble(columnsL.get(9).getValue().toString()));
					} else {
						return ResponseWrapper.error("单罐内直径不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(10).getValue())) {
						vo.setZygd(Double.parseDouble(columnsL.get(10).getValue().toString()));
					} else {
						return ResponseWrapper.error("设计储油高度不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(11).getValue())) {
						vo.setYgcykgd(Double.parseDouble(columnsL.get(11).getValue().toString()));
					}
					if (!ObjectUtils.isEmpty(columnsL.get(12).getValue())) {
						vo.setYgjckgd(Double.parseDouble(columnsL.get(12).getValue().toString()));
					}
					if (!ObjectUtils.isEmpty(columnsL.get(13).getValue())) {
						vo.setJdfs(columnsL.get(13).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("检定方式不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(14).getValue())) {
						vo.setHjfs(columnsL.get(14).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("焊接方式不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(15).getValue())) {
						vo.setYgzt(columnsL.get(15).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("油罐状态不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(16).getValue())) {
						SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
						vo.setSjnd(df.parse(columnsL.get(16).getValue().toString()));
					} else {
						return ResponseWrapper.error("建造日期不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(17).getValue())) {
						vo.setJsdw(columnsL.get(17).getValue().toString());
					}
					if (!ObjectUtils.isEmpty(columnsL.get(18).getValue())) {
						vo.setSjdw(columnsL.get(18).getValue().toString());
					}
					if (!ObjectUtils.isEmpty(columnsL.get(19).getValue())) {
						vo.setJldw(columnsL.get(19).getValue().toString());
					}
					if (!ObjectUtils.isEmpty(columnsL.get(20).getValue())) {
						vo.setCrkStatus(columnsL.get(20).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("出入库状态不能为空");
					}
					if (!ObjectUtils.isEmpty(columnsL.get(21).getValue())) {
						vo.setLylx(columnsL.get(21).getValue().toString().split("：")[0]);
					}
					if (!ObjectUtils.isEmpty(columnsL.get(22).getValue())) {
						vo.setYgsyzt(columnsL.get(22).getValue().toString().split("：")[0]);
					} else {
						return ResponseWrapper.error("使用状态不能为空");
					}
					vo.buildInsertData();
					ResponseWrapper result = oiltankFeign.insert(vo);
					if(result.getInfoCode()!=200) {
						fail ++ ;
						msgList.add(result.getMsg());
					} else {
						success++;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			fail ++ ;
		}
		msgList.stream().collect(Collectors.joining("\n"));
		return ResponseWrapper.success(success == 0 ? 500 : 200, "成功：" + success + ",失败：" + fail, msgList);
	}


}
