package com.yeejoin.amos.boot.module.jxiop.biz.service.impl;

import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.jxiop.api.dto.*;
import com.yeejoin.amos.boot.module.jxiop.api.entity.*;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.HouseholdPvDistrictMapper;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.UserOrgTreeModel;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.joda.time.LocalDateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.service.BaseService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.api.mapper.HouseholdPvMapper;
import com.yeejoin.amos.boot.module.jxiop.api.service.IHouseholdPvContactService;
import com.yeejoin.amos.boot.module.jxiop.api.service.IHouseholdPvInstallService;
import com.yeejoin.amos.boot.module.jxiop.api.service.IHouseholdPvLeaseService;
import com.yeejoin.amos.boot.module.jxiop.api.service.IHouseholdPvService;

/**
 * 户用光伏表服务实现类
 *
 * @author system_generator
 * @date 2023-03-17
 */
@Service
public class HouseholdPvServiceImpl extends BaseService<HouseholdPvDto, HouseholdPv, HouseholdPvMapper>
		implements IHouseholdPvService {

	@Autowired
	HouseholdPvMapper householdPvMapper;

	@Autowired
	IHouseholdPvContactService iHouseholdPvContactService;

	@Autowired
	IHouseholdPvLeaseService iHouseholdPvLeaseService;

	@Autowired
	IHouseholdPvInstallService iHouseholdPvInstallService;


	@Autowired
	HouseholdPvDistrictMapper householdPvDistrictMapper;

	@Autowired
	RedisUtils redisUtils;

	/**
	 * 分页查询
	 */
	public IPage<HouseholdPvDto> queryForHouseholdPvPage(Page<HouseholdPvDto> page, HouseholdPvDto dto) {
		String bizOrgCode = null;
		if (!ObjectUtils.isEmpty(dto.getPlatformCompanyId())) {
			bizOrgCode = getOrgCode(dto.getPlatformCompanyId());
			if (!ObjectUtils.isEmpty(bizOrgCode)) {
				dto.setBizOrgCode(bizOrgCode);
			}
		}
		Page<HouseholdPvDto> householdPvDtoPage = householdPvMapper.selectPageMessage(page, dto);
		Map<String, Object> map = companyList();
		householdPvDtoPage.getRecords().forEach(data -> {
			data.setPlatformCompanyName(String.valueOf(map.get(data.getPlatformCompanyId().toString())));
		});
		return householdPvDtoPage;
	}

	private Map<String, Object> companyList() {
		HashMap<String, Object> map = new HashMap<>();
		ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
		Long sequenceNbr = reginParams.getCompany().getSequenceNbr();
		FeignClientResult<Collection<UserOrgTreeModel>> collectionFeignClientResult = Privilege.companyClient.queryOrgTree(sequenceNbr);
		List<CompanyTreeDto> list = householdPvDistrictMapper.getList();
		list.forEach(item -> {
			map.put(item.getId(), item.getName());
		});
		if (collectionFeignClientResult != null) {
			Collection<UserOrgTreeModel> result = collectionFeignClientResult.getResult();
			change(result, map);
		}
		return map;
	}

	private void change(Collection<UserOrgTreeModel> data, Map<String, Object> result) {
		data.forEach(item -> {
			result.put(item.getId(), item.getName());
			if (!ObjectUtils.isEmpty(item.getChildren())) {
				change(item.getChildren(), result);
			}
		});
	}

	/**
	 * 列表查询 示例
	 */
	public List<HouseholdPvDto> queryForHouseholdPvList() {
		return this.queryForList("", false);
	}

	@Override
	public void importData(List<HouseholdPvImport> list) {
		ArrayList<HouseholdPv> householdPvs = new ArrayList<>();
		Map<String, Object> map = companyNameList();
		list.forEach(item -> {
			HouseholdPv householdPv = new HouseholdPv();
			BeanUtils.copyProperties(item, householdPv, "platformCompanyId", "expiryTime");
			householdPv.setCreateTime(LocalDateTime.now().toDate());
			if (!ObjectUtils.isEmpty(item.getExpiryTime())) {
				try {
					Date date = DateUtils.dateParse(item.getExpiryTime(), DateUtils.DATE_PATTERN);
					householdPv.setExpiryTime(date);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if (!ObjectUtils.isEmpty(item.getPlatformCompanyId())) {
				if (map.containsKey(item.getPlatformCompanyId())) {
					householdPv.setPlatformCompanyId(Long.parseLong(String.valueOf(map.get(item.getPlatformCompanyId()))));
					householdPv.setBizOrgCode(getOrgCode(householdPv.getPlatformCompanyId()));
				}
			}
			householdPvs.add(householdPv);
		});
		this.saveBatch(householdPvs);
	}

	private Map<String, Object> companyNameList() {
		HashMap<String, Object> map = new HashMap<>();
		ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
		Long sequenceNbr = reginParams.getCompany().getSequenceNbr();
		FeignClientResult<Collection<UserOrgTreeModel>> collectionFeignClientResult = Privilege.companyClient.queryOrgTree(sequenceNbr);
		List<CompanyTreeDto> list = householdPvDistrictMapper.getList();
		list.forEach(item -> {
			map.put(item.getName(), item.getId());
		});
		if (collectionFeignClientResult != null) {
			Collection<UserOrgTreeModel> result = collectionFeignClientResult.getResult();
			changeName(result, map);
		}
		return map;
	}

	private void changeName(Collection<UserOrgTreeModel> data, Map<String, Object> result) {
		data.forEach(item -> {
			result.put(item.getName(), item.getId());
			if (!ObjectUtils.isEmpty(item.getChildren())) {
				changeName(item.getChildren(), result);
			}
		});
	}

	@Override
	public List<HouseholdPvExport> selectExportList(HouseholdPvDto dto, List<Long> ids) {
		Map<String, Object> companyMap = companyList();
		List<HouseholdPvExport> householdPvExports = householdPvMapper.selectExportList(dto, ids);
		householdPvExports.forEach(item -> {
			if (!ObjectUtils.isEmpty(item.getPlatformCompanyId())) {
				if (companyMap.containsKey(item.getPlatformCompanyId())) {
					item.setPlatformCompanyId(companyMap.get(item.getPlatformCompanyId()).toString());
				} else {
					item.setPlatformCompanyId("");
				}
			}
			if (!ObjectUtils.isEmpty(item.getPeriod())) {
				JSONArray objects = JSON.parseArray(item.getPeriod());
				if (!ObjectUtils.isEmpty(objects) && objects.size() >= 2) {
					item.setPeriod(objects.get(0) + "-" + objects.get(1));
				}
			}
			List<HouseholdPvDeviceDto> equipList = householdPvMapper.selectEquipList(item.getId());
			if (!ObjectUtils.isEmpty(equipList)) {
				StringBuilder stringBuilder = equipMessage(equipList);
				item.setEquipmentMessage(stringBuilder.toString());
			}
		});
		return householdPvExports;

	}

	private String getOrgCode(Long platformCompanyId) {
		String bizOrgCode = null;
		HouseholdPvDistrict parentDetail = householdPvDistrictMapper.selectById(platformCompanyId);
		if (ObjectUtils.isEmpty(parentDetail)) {
			FeignClientResult<CompanyModel> companyModelFeignClientResult = Privilege.companyClient.seleteOne(platformCompanyId);
			CompanyModel result = companyModelFeignClientResult.getResult();
			if (!ObjectUtils.isEmpty(result)) {
				bizOrgCode = result.getOrgCode();
			}
		} else {
			bizOrgCode = parentDetail.getBizOrgCode();
		}
		return bizOrgCode;
	}

	private StringBuilder equipMessage(List<HouseholdPvDeviceDto> list) {
		StringBuilder stringBuilder = new StringBuilder();
		list.forEach(item -> {
			stringBuilder.append("类型:").append(ObjectUtils.isEmpty(item.getType()) ? "" : item.getType());
			stringBuilder.append(" 名称:").append(ObjectUtils.isEmpty(item.getName()) ? "" : item.getName());
			stringBuilder.append(" 品牌:").append(ObjectUtils.isEmpty(item.getBrand()) ? "" : item.getBrand());
			stringBuilder.append(" SN编码:").append(ObjectUtils.isEmpty(item.getSNCode()) ? "" : item.getSNCode());
			if (!ObjectUtils.isEmpty(item.getType()) && item.getType().equals("逆变器")) {
				stringBuilder.append(" 序列号:").append(ObjectUtils.isEmpty(item.getSerialNumber()) ? "" : item.getSerialNumber());
				stringBuilder.append(" 功率:").append(ObjectUtils.isEmpty(item.getPower()) ? "" : item.getPower());
			}
			if (!ObjectUtils.isEmpty(item.getType()) && item.getType().equals("其他")) {
				stringBuilder.append(" 描述:").append(ObjectUtils.isEmpty(item.getDescription()) ? "" : item.getDescription());
			}
			stringBuilder.append("\r\n");

		});
		return stringBuilder;
	}




	@Override
	public void deleteBatch(List<Long> ids) {
		householdPvMapper.deleteBatchIds(ids);
	}

	@Override
	public HouseholdPvDto save(HouseholdPvDto householdPvDto) {
		HouseholdPv householdPv = new HouseholdPv();
		BeanUtils.copyProperties(householdPvDto, householdPv);
		householdPv.setBizOrgCode(getOrgCode(householdPv.getPlatformCompanyId()));
		this.save(householdPv);

		HouseholdPvContact householdPvContact = new HouseholdPvContact();
		BeanUtils.copyProperties(householdPvDto.getContactInfo(), householdPvContact);
		householdPvContact.setHouseholdPvId(householdPv.getSequenceNbr());
		iHouseholdPvContactService.save(householdPvContact);

		HouseholdPvLease householdPvLease = new HouseholdPvLease();
		BeanUtils.copyProperties(householdPvDto.getLeaseInfo(), householdPvLease);
		householdPvLease.setHouseholdPvId(householdPv.getSequenceNbr());
		iHouseholdPvLeaseService.save(householdPvLease);

		HouseholdPvInstall householdPvInstall = new HouseholdPvInstall();
		BeanUtils.copyProperties(householdPvDto.getInstallInfo(), householdPvInstall);
		householdPvInstall.setHouseholdPvId(householdPv.getSequenceNbr());
		iHouseholdPvInstallService.save(householdPvInstall);

		return householdPvDto;
	}

	@Override
	public HouseholdPvDto update(HouseholdPvDto householdPvDto) {
		HouseholdPv householdPv = new HouseholdPv();
		BeanUtils.copyProperties(householdPvDto, householdPv);
		householdPv.setBizOrgCode(getOrgCode(householdPv.getPlatformCompanyId()));
		this.updateById(householdPv);

		HouseholdPvContact householdPvContact = new HouseholdPvContact();
		BeanUtils.copyProperties(householdPvDto.getContactInfo(), householdPvContact);
		iHouseholdPvContactService.update(householdPvContact,new LambdaQueryWrapper<HouseholdPvContact>()
				.eq(HouseholdPvContact::getHouseholdPvId, householdPvDto.getSequenceNbr()));

		HouseholdPvLease householdPvLease = new HouseholdPvLease();
		BeanUtils.copyProperties(householdPvDto.getLeaseInfo(), householdPvLease);
		iHouseholdPvLeaseService.update(householdPvLease,new LambdaQueryWrapper<HouseholdPvLease>()
				.eq(HouseholdPvLease::getHouseholdPvId, householdPvDto.getSequenceNbr()));

		HouseholdPvInstall householdPvInstall = new HouseholdPvInstall();
		BeanUtils.copyProperties(householdPvDto.getInstallInfo(), householdPvInstall);
		iHouseholdPvInstallService.update(householdPvInstall,new LambdaQueryWrapper<HouseholdPvInstall>()
				.eq(HouseholdPvInstall::getHouseholdPvId, householdPvDto.getSequenceNbr()));

		return householdPvDto;
	}

	@Override
	public HouseholdPvDto getBySeq(Long id) {
		HouseholdPv householdPv = this.getById(id);
		HouseholdPvDto householdPvDto = new HouseholdPvDto();
		BeanUtils.copyProperties(householdPv, householdPvDto);

		HouseholdPvContact householdPvContact = iHouseholdPvContactService
				.getOne(new LambdaQueryWrapper<HouseholdPvContact>().eq(HouseholdPvContact::getHouseholdPvId, id));
		if (householdPvContact != null) {
			HouseholdPvContactDto householdPvContactDto = new HouseholdPvContactDto();
			BeanUtils.copyProperties(householdPvContact, householdPvContactDto);
			householdPvDto.setContactInfo(householdPvContactDto);
		}

		HouseholdPvLease householdPvLease = iHouseholdPvLeaseService
				.getOne(new LambdaQueryWrapper<HouseholdPvLease>().eq(HouseholdPvLease::getHouseholdPvId, id));
		if (householdPvLease != null) {
			HouseholdPvLeaseDto householdPvLeaseDto = new HouseholdPvLeaseDto();
			BeanUtils.copyProperties(householdPvLease, householdPvLeaseDto);
			householdPvDto.setLeaseInfo(householdPvLeaseDto);
		}

		HouseholdPvInstall householdPvInstall = iHouseholdPvInstallService
				.getOne(new LambdaQueryWrapper<HouseholdPvInstall>().eq(HouseholdPvInstall::getHouseholdPvId, id));
		if (householdPvInstall != null) {
			HouseholdPvInstallDto householdPvInstallDto = new HouseholdPvInstallDto();
			BeanUtils.copyProperties(householdPvInstall, householdPvInstallDto);
			householdPvDto.setInstallInfo(householdPvInstallDto);

		}

		return householdPvDto;
	}
}