package cn.com.countrygarden.bi.main.service.mediaResource.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageRowBounds;

import cn.com.countrygarden.bi.main.constant.mediaResource.MediaResourceConstant;
import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.dao.mediaResource.BasicInfoMapper;
import cn.com.countrygarden.bi.main.dao.mediaResource.ScheduleBasicInfoMapper;
import cn.com.countrygarden.bi.main.dto.BasicInfoDto;
import cn.com.countrygarden.bi.main.dto.mediaResource.AreaDto;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.mediaResource.BasicInfo;
import cn.com.countrygarden.bi.main.model.mediaResource.Customer;
import cn.com.countrygarden.bi.main.model.mediaResource.ErpBasicInfo;
import cn.com.countrygarden.bi.main.model.mediaResource.Projects;
import cn.com.countrygarden.bi.main.model.mediaResource.Regional;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.UserRoleService;
import cn.com.countrygarden.bi.main.service.mediaResource.BasicInfoService;
import cn.com.countrygarden.bi.main.service.mediaResource.MediaCommonService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.ExcelUtil;
import cn.com.countrygarden.bi.main.util.PageUtil;

@Service
@Transactional
public class BasicInfoServiceImpl extends AbstractService<BasicInfo> implements BasicInfoService{

	@Autowired
	private BasicInfoMapper basicInfoMapper;
	
	@Autowired
	private ScheduleBasicInfoMapper scheduleBasicInfoMapper;
	
	@Autowired
    private TbSysUserService tbSysUserService;
	
	@Autowired
	private AccessTokenService accessTokenService;
	
	@Autowired
	private MediaCommonService mediaCommonService;
	
	public int saveBasicInfo(List<BasicInfo> list) {
		int count = scheduleBasicInfoMapper.insertList(list);
		return count;
	}

	@Override
	public List<String> findDbbasicInfoId() {
		List<String> list = scheduleBasicInfoMapper.findBasicId();
		return list;
	}

	@Override
	public PageData finBasicByPage(String accessToken,BasicInfoDto dto) {
		dto.setPageIndex(dto.getPageIndex()==null?1:dto.getPageIndex());
		dto.setPageSize(dto.getPageSize()==null?10:dto.getPageSize());
		int pageOffset = PageUtil.getPageOffset(dto.getPageIndex(),dto.getPageSize());
		dto.setPageOffset(pageOffset);
		/*TbSysUser user = findErpUser(accessToken);
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(),MediaResourceConstant.roleCode);
		if (count==0) {
			String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
			dto.setOrganCode(organCode);
		}*/
		List<Map<String,Object>> list = scheduleBasicInfoMapper.selectBasicInfo(dto);
		long total = scheduleBasicInfoMapper.selectBasicInfoCount(dto);
		
		
		PageRowBounds pageRowBounds = new PageRowBounds(dto.getPageIndex(), dto.getPageSize());
	    pageRowBounds.setTotal(total);
	    pageRowBounds.setCount(true);
        PageData pageData = new PageData(list, pageRowBounds);
        return pageData;
	}

	@Override
	public List<String> propertyAreaData(String accessToken,BasicInfoDto dto) {
		/*List<String> organList = new ArrayList<>();
		List<Regional> company = mediaCommonService.findCompany(user.getUserCode());
		for (Regional regional : company) {
			organList.add(regional.getOrganCode());
		}*/
		TbSysUser user = findErpUser(accessToken);
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(), MediaResourceConstant.roleCode);
		if (count==0) {
			String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
			dto.setOrganCode(organCode);
		}
		return scheduleBasicInfoMapper.selectPropertyData(dto);
	}
	
	@Override
	public List<String> propertyProjectData(BasicInfoDto dto) {
		//List<String> commList = new ArrayList<>();
		return scheduleBasicInfoMapper.propertyProjectData(dto);
	}

	@Override
	public List<Map<String, Object>> provinceData(BasicInfoDto dto) {
		return basicInfoMapper.provinceData(dto);
	}

	@Override
	public List<Map<String, Object>> cityData(BasicInfoDto dto) {
		return basicInfoMapper.cityData(dto);
	}

	@Override
	public Map<String,String> findOne(BasicInfo po) {
		Map<String,String> map = scheduleBasicInfoMapper.findOne(po);
		return map;
	}

	@Override
	public Result saveOne(String accessToken,BasicInfoDto dto) {
		TbSysUser user = findErpUser(accessToken);
		int count = scheduleBasicInfoMapper.findUserRole(user.getUserCode(),MediaResourceConstant.roleCode);
		if(count==0) {
			String organCode = basicInfoMapper.findErpUserOrgan(user.getUserCode()).get("organCode");
			if (!dto.getOrganCode().equals(organCode)) {
				return ResultGenerator.genFailResult("不能跨区域修改！");
			}
		}
		
		String zero = "0";
		dto.setUpCarPark(StringUtils.isEmpty(dto.getUpCarPark())?zero:dto.getUpCarPark());
		dto.setDownCarPark(StringUtils.isEmpty(dto.getDownCarPark())?zero:dto.getDownCarPark());
		dto.setElevatorDoorNumber(StringUtils.isEmpty(dto.getElevatorDoorNumber())?zero:dto.getElevatorDoorNumber());
		dto.setElevatorRoomNumber(StringUtils.isEmpty(dto.getElevatorRoomNumber())?zero:dto.getElevatorRoomNumber());
		dto.setElevatorAmount(StringUtils.isEmpty(dto.getElevatorAmount())?zero:dto.getElevatorAmount());
		dto.setStairsRoomNumber(StringUtils.isEmpty(dto.getStairsRoomNumber())?zero:dto.getStairsRoomNumber());
		dto.setStairsDoorNumber(StringUtils.isEmpty(dto.getStairsDoorNumber())?zero:dto.getStairsDoorNumber());
		dto.setVillaAmount(StringUtils.isEmpty(dto.getVillaAmount())?zero:dto.getVillaAmount());
		/*dto.setTakeRoomNumber(StringUtils.isEmpty(dto.getTakeRoomNumber())?zero:dto.getTakeRoomNumber());
		dto.setOftenNumber(StringUtils.isEmpty(dto.getOftenNumber())?zero:dto.getOftenNumber());*/
		dto.setPassengerElevatorNumber(StringUtils.isEmpty(dto.getPassengerElevatorNumber())?zero:dto.getPassengerElevatorNumber());
		dto.setFreightElevatorNumber(StringUtils.isEmpty(dto.getFreightElevatorNumber())?zero:dto.getFreightElevatorNumber());
		dto.setApartment(StringUtils.isEmpty(dto.getApartment())?zero:dto.getApartment());
		
		dto.setVersion(dto.getVersion()+1);
		dto.setModBy(user.getUserCode());
		dto.setModByName(user.getUserName());
		dto.setModTime(new Date());
		return ResultGenerator.genSuccessResult(scheduleBasicInfoMapper.saveOne(dto));
	}

	@Override
	public List<Map<String,Object>> findBasic(String accessToken,BasicInfoDto dto) {
		return scheduleBasicInfoMapper.findBasic(dto);
	}

	@Override
	public List<ErpBasicInfo> findErpBasicInfo() {
		return basicInfoMapper.findErpBasicInfo();
	}

	@Override
	public List<BasicInfo> finddbBasicInfo() {
		return scheduleBasicInfoMapper.finddbBasicInfo();
	}

	@Override
	public void updateBasicInfo(List<BasicInfo> updateList) {
		for (BasicInfo basicInfo : updateList) {
			scheduleBasicInfoMapper.updateMatchingBasic(basicInfo);
		}
	}

	@Override
	public List<Map<String, Object>> provinces(AreaDto dto) {
		return scheduleBasicInfoMapper.provinces(dto);
	}

	@Override
	public TbSysUser findErpUser(String accessToken) {
		TbSysUser user = tbSysUserService.getCurrentSysUser();
		if (null==user) {
			if (null == accessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
			if (null == userAccessToken) {
				throw new ServiceException("获取用户信息失败");
			}
			user = tbSysUserService.findByUserCode(userAccessToken.getUserCode());
			if (null==user) {
				throw new ServiceException("获取用户信息失败");
			}
		}
		return user;
	}

	@Override
	public Result exportIn(String accessToken, Result rt, MultipartFile file) throws IOException {
		
		List<ArrayList<String>> data = ExcelUtil.importData(file,0);//这里还未定
		if (data.isEmpty()) {
			return rt.setResultCode(ResultCode.FAIL).setResultMsg("文件为空").setData(false);
		}
		String[] title = {"[物业区域","区域编号","物业项目","项目编号","项目开发主体","省份","市/自治州","区/县","首次收楼日期","计划开盘时间","实际开盘时间",
				"合同收楼时间","实际进驻时间","项目营业执照的物业公司全称","开发主体(房产核算全称)","物业业态","项目开发状态","接管状态","收楼状态","建筑面积(接管住宅建筑面积)",
				"实际交付面积(已收楼住宅建筑面积)","收楼户数","常住户数","规划户数","接管户数","入住率","地上车位数","地下车位数","载人电梯数量(部)","货物电梯数量(部)",
				"公寓","电梯门洞数","电梯房数量(栋)","电梯总数(部)","步梯楼数量(栋)","步梯楼门洞数(个)","别墅数量(栋)]"};
		String[] split = data.get(0).toString().split(",");
		for (int i = 0; i < title.length; i++) {
			if (!title[i].equals(split[i].trim())) {
				return rt.setResultCode(ResultCode.FAIL).setResultMsg("标题错误，请下载模板文件。").setData(false);
			}
		}
		data.remove(0);
		if (data.isEmpty()) {
			return rt.setResultCode(ResultCode.FAIL).setResultMsg("文件为空").setData(false);
		}
		
		List<BasicInfoDto> dtoList = scheduleBasicInfoMapper.findAllCommId();
		List<String> commInfoIdList = dtoList.stream().map(BasicInfoDto::getCommId).collect(Collectors.toList());
		
		TbSysUser user = findErpUser(accessToken);
		StringBuffer overAllStr = new StringBuffer();
		
		Map<Integer, String> errorMsgMap = new LinkedHashMap<>();
		
		List<BasicInfo> successList = new ArrayList<>();
		
		for (int i = 0; i < data.size(); i++) {
			ArrayList<String> rows = data.get(i);
			String commId = rows.get(3);
			
			//String takeRoomNumber = rows.get(21);//收楼
			//String oftenNumber = rows.get(22);//常住
			String passengerElevatorNumber= rows.get(28);//载人电梯
			String freightElevatorNumber= rows.get(29);//货梯
			String apartment = rows.get(30);//公寓
			String upCarPark = rows.get(26);//地上
			String downCarPark = rows.get(27);//地下
			String elevatorDoorNumber = rows.get(31);//电梯门洞数
			String elevatorRoomNumber = rows.get(32);//电梯房
			String elevatorAmount = rows.get(33);//电梯总数
			String stairsRoomNumber = rows.get(34);//步梯房
			String stairsDoorNumber = rows.get(35);//步梯门洞
			String villaAmount = rows.get(36);//别墅
			
			boolean contains = commInfoIdList.contains(commId);
			overAllStr.append(contains?"":"项目id不存在，");
			Integer mal = null;
			
			
			try {
				mal = Integer.parseInt(commId);
			} catch (Exception e) {
				overAllStr.append("项目id只能是数字且最大值:2147483647，请检查，");
			}

			/*try {
				mal = Integer.parseInt(takeRoomNumber);
			} catch (Exception e) {
				overAllStr.append("收楼户数只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(oftenNumber);
			} catch (Exception e) {
				overAllStr.append("常住户数只能是数字且最大值:2147483647，请检查，");
			}*/
			
			try {
				mal = Integer.parseInt(passengerElevatorNumber);
			} catch (Exception e) {
				overAllStr.append("载人电梯数量只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(freightElevatorNumber);
			} catch (Exception e) {
				overAllStr.append("货物电梯数量只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(apartment);
			} catch (Exception e) {
				overAllStr.append("公寓只能是数字且最大值:2147483647，请检查，");
			}
			
			//---------------------------
			
			try {
				mal = Integer.parseInt(upCarPark);
			} catch (Exception e) {
				overAllStr.append("地上车位只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(downCarPark);
			} catch (Exception e) {
				overAllStr.append("地下车位只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(elevatorDoorNumber);
			} catch (Exception e) {
				overAllStr.append("电梯门洞数只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(elevatorRoomNumber);
			} catch (Exception e) {
				overAllStr.append("电梯房数量只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(elevatorAmount);
			} catch (Exception e) {
				overAllStr.append("电梯总数只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(stairsRoomNumber);
			} catch (Exception e) {
				overAllStr.append("步梯房数量只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(stairsDoorNumber);
			} catch (Exception e) {
				overAllStr.append("步梯门洞数只能是数字且最大值:2147483647，请检查，");
			}
			
			try {
				mal = Integer.parseInt(villaAmount);
			} catch (Exception e) {
				overAllStr.append("别墅数量只能是数字且最大值:2147483647，请检查，");
			}
			
			if (StringUtils.isNotBlank(overAllStr)) {
				errorMsgMap.put(i+2, overAllStr.toString());
				overAllStr.setLength(0);
				continue;
			}
			
			BasicInfo po = new BasicInfo();

			/*po.setTakeRoomNumber(Integer.parseInt(takeRoomNumber));
			po.setOftenNumber(Integer.parseInt(oftenNumber));*/
			po.setPassengerElevatorNumber(Integer.parseInt(passengerElevatorNumber));
			po.setFreightElevatorNumber(Integer.parseInt(freightElevatorNumber));
			po.setApartment(Integer.parseInt(apartment));
			
			po.setCommId(commId);
			po.setUpCarPark(Integer.parseInt(upCarPark));
			po.setDownCarPark(Integer.parseInt(downCarPark));
			po.setElevatorDoorNumber(Integer.parseInt(elevatorDoorNumber));
			po.setElevatorRoomNumber(Integer.parseInt(elevatorRoomNumber));
			po.setElevatorAmount(Integer.parseInt(elevatorAmount));
			po.setStairsRoomNumber(Integer.parseInt(stairsRoomNumber));
			po.setStairsDoorNumber(Integer.parseInt(stairsDoorNumber));
			po.setVillaAmount(mal);
			po.setModBy(user.getUserCode());
			po.setModByName(user.getUserName());
			po.setModTime(new Date());
			successList.add(po);
			
		}
		
		overAllStr.setLength(0);
		overAllStr.append("第");
		
		if (!CollectionUtils.isEmpty(errorMsgMap)) {
			List<String> resultErrorMsg = new ArrayList<>();
			errorMsgMap.forEach((i,v)->{
				resultErrorMsg.add(overAllStr.append(i+"行：").append(v.substring(0, v.length()-1)).toString());
				overAllStr.setLength(1);
			});
			return rt.setResultCode(ResultCode.FAIL).setResultMsg("导入失败").setData(resultErrorMsg);
		}
		
		List<String> insertFailList = new ArrayList<>();
		int accumulative = 1;
		try {
			for (int j = 0; j < successList.size(); j++) {
				accumulative++;
				scheduleBasicInfoMapper.updateOne(successList.get(j));
			}
		} catch (Exception e) {
			insertFailList.add(overAllStr.append(accumulative).append("行新增失败").toString());
			overAllStr.setLength(1);
			e.printStackTrace();
		}
		
		return rt.setResultCode(ResultCode.OK).setResultMsg("导入"+(successList.size() - insertFailList.size())+"个数据成功")
				.setData(CollectionUtils.isEmpty(insertFailList)?null:insertFailList);
	
	}

	@Override
	public Result regional(String accessToken) {
		return ResultGenerator.genSuccessResult(basicInfoMapper.findRegionalProject());
	}

	
}
