package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.nantian.cloud.jljc.dto.AuditorDto;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.*;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * 报表1-3-1可比单位产品综合能耗表
 * @date 2020-01-06
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tReportUnitenergyComp")
@Api(value = "tReportUnitenergyComp", tags = "报表1-3-1可比单位产品综合能耗表")
public class TReportUnitenergyCompController {

	private final TReportService tReportService;
	private final EnergyIndexService energyIndexService;
	private final EnterpriseInfoService enterpriseInfoService;
	private final TReportEnterpriseService tReportEnterpriseService;
	private final TReportUnitenergyCompService tReportUnitenergyCompService;


	/**
	 * 通过年份查询报表1-3-1可比单位产品综合能耗表
	 */
	@GetMapping("/getByYear")
	@SysLog("通过年份查询报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "通过年份查询报表1-3-1可比单位产品综合能耗表", notes = "通过年份查询报表1-3-1可比单位产品综合能耗表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "year", value = "年份", required = true, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "enterpriseCode", value = "企业社会信用编码", required = true, dataType = "json", paramType = "path")
	})
	public R getByYear(String year, String enterpriseCode) {
		if (year == null || "".equals(year)) {
			return R.failed("查询失败，年度不能为空");
		}
		if (enterpriseCode == null || "".equals(enterpriseCode)) {
			return R.failed("查询失败，企业社会信用编码不能为空");
		}
		//ScUser u = SecurityUtils.getUser();
		//获取能源报表信息
		TReport report = tReportService.getInfoByType(enterpriseCode, year, "3-1");
		if (report == null) {
			return R.ok();
		}
		Long reportId = report.getId();
		
		//查询上年报表id
		String prevYear = (Integer.parseInt(year) - 1) + "";
		TReport prevReport = tReportService.getInfoByType(enterpriseCode, prevYear, "3-1");
		Long prevReportId = prevReport == null ? 0 : prevReport.getId();

		//通过根据本年、上年报表id获取获取信息
		List<TReportUnitenergyComp> unitenergyCompList = tReportUnitenergyCompService.getUnitenergyCompByReportId(reportId,prevReportId);
		return R.ok(unitenergyCompList);
	}

	/**
	 * 通过年份查询初始化报表信息
	 */
	@GetMapping("/initialize")
	@SysLog("通过年份查询初始化报表1-3-1信息")
	@ApiOperation(value = "通过年份查询初始化报表信息", notes = "通过年份查询初始化报表信息")
	@ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path")
	public R initialize(String year) {
		if (year == null || "".equals(year)) {
			return R.failed("查询失败，年度不能为空");
		}

		//查询当年报表设置信息
		ScUser u = SecurityUtils.getUser();
		String energyIndexStr = tReportEnterpriseService.getEnergyIndex(u.getEnterpriseCode(), year);
		List<Long> ids = new ArrayList<>();
		if (energyIndexStr != null && !"".equals(energyIndexStr)) {
			List<EnergyIndex> energyIndexList = (List<EnergyIndex>) JSONArray.parseArray(energyIndexStr, EnergyIndex.class);
			for (EnergyIndex energyIndex : energyIndexList) {
				ids.add(energyIndex.getId());
			}
		}

		//查询上年报表id
		String prevYear = (Integer.parseInt(year) - 1) + "";
		TReport report = tReportService.getInfoByType(u.getEnterpriseCode(), prevYear, "3-1");
		Long reportId = report == null ? 0 : report.getId();

		//根据报表设置信息、上年id初始化报表信息
		List<TReportUnitenergyComp> unitenergyCompList = tReportUnitenergyCompService.initialize(ids, reportId);
		return R.ok(unitenergyCompList);
	}

	/**
	 * 批量更新报表1-3-1可比单位产品综合能耗表
	 */
	@Transactional
	@PostMapping("/upUnitenergyComp")
	@SysLog("批量更新报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "批量更新报表1-3-1可比单位产品综合能耗表（参数说明是键值对说明，参数s除外）", notes = "批量更新报表1-3-1可比单位产品综合能耗表（参数说明是键值对说明），参数s除外")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "report", value = "能源报表信息", required = true, dataType = "String"),
			@ApiImplicitParam(name = "data", value = "报表1-3-1可比单位产品综合能耗表", required = true, dataType = "String")
	})
	public R upUnitenergyComp(@RequestBody String s) {

		log.error("批量更新报表1-3-1可比单位产品综合能耗表：" + s);

		JSONObject json = JSONObject.parseObject(s);
		//获取能源报表信息
		TReport report = JSONObject.parseObject(json.getString("report"), TReport.class);
		if (report.getYear() == null || "".equals(report.getYear())) {
			return R.failed("更新报表1-3-1可比单位产品综合能耗表失败，年度不能为空");
		}

		ScUser u = SecurityUtils.getUser();
		String enterpriseCode = StringUtils.isNotEmpty(report.getEnterpriseCode()) ? report.getEnterpriseCode() : u.getEnterpriseCode();
		String data = json.getString("data");
		//获取能源消费表列表
		List<TReportUnitenergyComp> unitenergyCompList = (List<TReportUnitenergyComp>) JSONArray.parseArray(data, TReportUnitenergyComp.class);


		//批量更新报表1-3-1可比单位产品综合能耗表信息
		//获取报表信息id
		long reportId = tReportService.getTReportIdByType(enterpriseCode, report.getYear() + "", "3-1", u);
		//更新报表信息
		report.setId(reportId);
		report.setUserid(u.getId());
		report.setUpdateTime(new Date());
		report.setReportStatus("2");
		//boolean b = tReportService.updateById(report);

		List<TReportUnitenergyComp> newUnitenergyCompList = new ArrayList<TReportUnitenergyComp>();
		for (TReportUnitenergyComp unitenergy : unitenergyCompList) {
			hasOld(u, unitenergy, reportId);
			unitenergy.setReportId(reportId);
			unitenergy.setUserid(u.getId());
			unitenergy.setUpdateTime(new Date());
			//添加指标限额
			EnergyIndex energyIndex = new EnergyIndex();
			if(unitenergy.getQuotaId()!=null){
				energyIndex = energyIndexService.getById(unitenergy.getQuotaId());
			}else{
				EnergyIndex i = new EnergyIndex();
				i.setIndexName(unitenergy.getQuotaName());
				i.setDelFlag("1");
				energyIndex = energyIndexService.getOne(Wrappers.query(i));
			}
			if (energyIndex != null) {
				unitenergy.setQuotaLimit(energyIndex.getLocalLimit() != null ? energyIndex.getLocalLimit() : energyIndex.getGovLimit());
			}
			newUnitenergyCompList.add(unitenergy);
		}

		//return R.ok(tReportUnitenergyCompService.saveOrUpdateBatch(newunitenergyCompList));
		boolean updateBatch = tReportUnitenergyCompService.saveOrUpdateBatch(newUnitenergyCompList);
		if (updateBatch) {
			//产品信息更新成功，报表信息才更新
			return R.ok(tReportService.updateById(report));
		} else {
			return R.failed();
		}
	}

	/**
	 * 判断是否有历史数据
	 */
	private void hasOld(ScUser u, TReportUnitenergyComp unitenergy, long reportId) {
		TReportUnitenergyComp old = new TReportUnitenergyComp();
		old.setReportId(reportId);
		old.setDelFlag("1");
		if(unitenergy.getQuotaId()!=null){
			old.setQuotaId(unitenergy.getQuotaId());
		}else{
			old.setQuotaName(unitenergy.getQuotaName());
		}
		TReportUnitenergyComp o = tReportUnitenergyCompService.getOne(Wrappers.query(old));
		if (o != null) { //有历史数据为修改
			unitenergy.setId(o.getId());
		} else {
			//unitenergy.setDeptId(u.getId());
			EnterpriseInfo info = enterpriseInfoService.getInfoByCode(u.getEnterpriseCode());
			unitenergy.setDeptId(info != null && info.getRegionCode()!=null ? Integer.parseInt(info.getRegionCode()) : u.getDeptId());
			unitenergy.setDelFlag("1");
		}
	}
	
	
	/**
	 * 提交报表1-3-1可比单位产品综合能耗表
	 */
	@PostMapping("/submit")
	@SysLog("提交报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "提交报表1-3-1可比单位产品综合能耗表", notes = "提交报表1-3-1可比单位产品综合能耗表")
	@ApiImplicitParam(name = "TReport", value = "能源报表信息", required = true, dataType = "String")
	public R save(@RequestBody TReport tReport) {
		if (tReport.getYear() == null || "".equals(tReport.getYear())) {
			return R.failed("提交报表1-3-1可比单位产品综合能耗表失败，年度不能为空");
		}
		ScUser u = SecurityUtils.getUser();
		//获取报表信息id
		String enterpriseCode = StringUtils.isEmpty(tReport.getEnterpriseCode()) ? u.getEnterpriseCode() : tReport.getEnterpriseCode();
		TReport oldReport = tReportService.getInfoByType(enterpriseCode, tReport.getYear() + "", "3-1");
		if (oldReport == null) {
			return R.failed("请先保存报表1-3-1可比单位产品综合能耗表，再上报！");
		}

		//通过根据本年、上年报表id获取获取信息
		List<TReportUnitenergyComp> unitenergyCompList = tReportUnitenergyCompService.getUnitenergyCompByReportId(oldReport.getId(),0L);
		if (unitenergyCompList.size() <= 0) {
			return R.failed("请先保存报表1-3-1可比单位产品综合能耗表，再上报！");
		}

		tReport.setId(oldReport.getId());
		tReport.setUpdateTime(new Date());
		tReport.setUserid(u.getId());
		tReport.setReportStatus("3");
		tReport.setAuditStatus("1");
		tReport.setAuditStatus2("1");
		tReport.setAuditStatus3("1");
		return R.ok(tReportService.updateById(tReport));
	}

	/**
	 * 企业端预览报表1-3-1可比单位产品综合能耗表
	 */
	@GetMapping("/preview")
	@SysLog("企业端预览报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "企业端预览报表1-3-1可比单位产品综合能耗表", notes = "企业端预览报表1-3-1可比单位产品综合能耗表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
	})
	public R getByReportId(String year, String enterpriseCode) {
		if (year == null || "".equals(year)) {
			return R.failed("预览报表1-3-1可比单位产品综合能耗表失败，年度不能为空");
		}
		if(StringUtils.isEmpty(enterpriseCode)){
			enterpriseCode = SecurityUtils.getUser().getEnterpriseCode();
		}
		//企业端 flag为false
		return previewReport(year, enterpriseCode, false);
	}

	/**
	 * 政府端预览报表1-3-1可比单位产品综合能耗表
	 */
	@GetMapping("/previewGov")
	@SysLog("政府端预览报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "政府端预览报表1-3-1可比单位产品综合能耗表", notes = "政府端预览报表1-3-1可比单位产品综合能耗表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "json", paramType = "path"),
			@ApiImplicitParam(name = "enterpriseCode", value = "企业编码", required = false, dataType = "json", paramType = "path")
	})
	public R getByReportIdGov(String year, String enterpriseCode) {
		if (year == null || "".equals(year)) {
			return R.failed("预览报表1-3-1可比单位产品综合能耗表失败，年度不能为空");
		}
		if (enterpriseCode == null || "".equals(enterpriseCode)) {
			return R.failed("预览报表1-3-1可比单位产品综合能耗表失败，企业社会信用编码不能为空");
		}
		//政府端 flag为true
		return previewReport(year, enterpriseCode, true);
	}

	/**
	 * 预览报表1-3-1可比单位产品综合能耗表
	 */
	private R previewReport(String year, String enterpriseCode, boolean flag) {

		//获取能源报表信息
		TReport report = tReportService.getInfoByType(enterpriseCode, year, "3-1");
		//查询上年报表id
		String prevYear = (Integer.parseInt(year) - 1) + "";
		TReport prevReport = tReportService.getInfoByType(enterpriseCode, prevYear, "3-1");

		//获取企业信息
		TReportEnterprise enterprise = tReportEnterpriseService.getEnterpriseInfo(enterpriseCode, year);

		//通过根据本年、上年报表id获取获取信息
		long id1 = report != null ? report.getId() : 0;
		long id2 = prevReport != null ? prevReport.getId() : 0;
		List<TReportUnitenergyComp> unitenergyCompList = tReportUnitenergyCompService.getUnitenergyCompByReportId(id1, id2);

		Map<String, Object> map = new HashMap();
		map.put("enterprise", enterprise);
		map.put("report", report);
		map.put("unitenergyComp", unitenergyCompList);
		return R.ok(map);
	}


	/**
	 * 审核报表1-3-1可比单位产品综合能耗表
	 */
	@PostMapping("/auditor")
	@SysLog("审核报表1-3-1可比单位产品综合能耗表")
	@ApiOperation(value = "审核报表1-3-1可比单位产品综合能耗表", notes = "审核报表1-3-1可比单位产品综合能耗表")
	@ApiImplicitParam(name = "auditorDto", value = "报表审核对象", required = true, dataType = "json", paramType = "path")
	public R updateByAuditor(@RequestBody AuditorDto auditorDto) {
		ScUser u = SecurityUtils.getUser();
		if (auditorDto.getId() == null) {
			return R.failed("报表id为空，审核报表1-3-1可比单位产品综合能耗表失败！");
		}
		TReport tReport = new TReport();
		tReport.setId(auditorDto.getId());
		tReport.setUpdateTime(new Date());
		tReport.setUserid(u.getId());
		tReport.setAuditStatus(auditorDto.getAuditStatus());
		tReport.setAuditRemark(auditorDto.getAuditRemark());
		boolean b = tReportService.updateById(tReport);
		return b ? R.ok("2".equals(auditorDto.getAuditStatus()) ? "已审核" : "已退回") : R.failed("审核失败");
	}

}
