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

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.com.countrygarden.bi.main.util.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageRowBounds;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.dao.common.OrganMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectJointPlanMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectSignItemMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectSignMapper;
import cn.com.countrygarden.bi.main.exception.ServiceCodeException;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.common.Organ;
import cn.com.countrygarden.bi.main.model.mediaResource.AdvertisingFileDirectory;
import cn.com.countrygarden.bi.main.model.project.ProjectJointPlan;
import cn.com.countrygarden.bi.main.model.project.ProjectSign;
import cn.com.countrygarden.bi.main.model.project.ProjectSignItem;
import cn.com.countrygarden.bi.main.model.project.ProjectTarget;
import cn.com.countrygarden.bi.main.service.project.ProjectSignItemServer;
import cn.com.countrygarden.bi.main.service.project.impl.vo.ProjectSignItemQuery;
import cn.com.countrygarden.bi.main.service.project.impl.vo.ProjectSignItemVO;
@Slf4j
@Service
@Transactional
public class ProjectSignItemServerImpl implements ProjectSignItemServer{
	@Autowired
	  private  ProjectSignItemMapper mapper;
	@Autowired
	  private  ProjectSignMapper projectSignmapper;
	 @Autowired
		private OrganMapper organMapper;
	 @Autowired
	 private ProjectJointPlanMapper projectJointPlanMapper;
	@Override
	public PageData search(ProjectSignItemQuery p,Integer page,Integer size) {
		 PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		List<ProjectSignItemVO> plist = mapper.search(p, pageRowBounds);
		return new PageData( plist,pageRowBounds);
	}

	@Override
	public Integer save(ProjectSignItem p, String userCode) {
		if(null == p.getId()) {
			p.setGmtCreate(new Date());
			p.setCreateBy(userCode);
			return mapper.insert(p);
		}else{
			ProjectSignItem old = mapper.selectByPrimaryKey(p.getId());
			old.setBusinessType(p.getBusinessType());
			old.setCountProportion(p.getCountProportion());
			old.setId(p.getId());
			old.setRatesArea(p.getRatesArea());
			old.setRemark(p.getRemark());
			old.setMonthIncome(p.getMonthIncome());
			old.setBusinessTypeName(p.getBusinessTypeName());
			old.setMonthNumber(p.getMonthNumber());
			old.setPrice(p.getPrice());
		//	old.setProjectSignId(p.getProjectSignId());
			old.setYearIncome(p.getYearIncome());
			return mapper.updateByPrimaryKey(old);
		}
	}

	@Override
	public Integer delete(Integer id) {
		ProjectSignItem p = new ProjectSignItem();
		p.setId(id);
		return mapper.delete(p);
	}

	@Override
	public ProjectSignItem findOne(Integer id) {
		return mapper.selectByPrimaryKey(id);
	}
	@Override
	public Result excelToObject(MultipartFile mf,String fileName,String OperatorId,String month) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Workbook xwb = null;
        BufferedInputStream bf=null;
        Sheet sheet0 = null;
       // Sheet sheet1 = null;
		Boolean flag=true;
		List<String> mList=new ArrayList<>();
		try {
			    xwb=getWorkBook(mf);
			//sheet1 = xwb.getSheetAt(1);
			    sheet0 = xwb.getSheetAt(0);
				flag = checkOrganName(sheet0, mList, flag);
				List<List<String>> transferBasicInfoList = UploadUtil.readOneSheetForList(sheet0, 4, -1, 0, -1);

				if (flag) {
					int length = transferBasicInfoList.size();
					for (int rowNum = 0; rowNum < length; rowNum++) {
						int rowErrorNum = rowNum + 4;
						System.out.println("第" + rowErrorNum + "行");

						List<String> transferBasicInfo = transferBasicInfoList.get(rowNum);

						ProjectSign projectSign = new ProjectSign();

						String organName = transferBasicInfo.get(1);
						projectSign.setOrganName(organName);
/*				 Organ organ = new Organ();
				 organ.setName(organName);
				 List<Organ> organList = organMapper.select(organ);
				 if(organList.size() < 1) {
					 projectSign.setOrganId(orgMap(organName));

				 }else {
					 organ = organList.get(0);
					 projectSign.setOrganId(organ.getOrganCode());
				 }*/

						organName = transferBasicInfo.get(2);
						Organ organj = new Organ();
						organj.setName(organName);
						List<Organ> organList = organMapper.select(organj);
						if (organList.isEmpty() || organList.size() == 0) {
							try {
								String orgMap = orgMap(organName);
								projectSign.setProposalOrganId(orgMap);
							} catch (ServiceCodeException e) {
								e.printStackTrace();
							}

						} else {
							organj = organList.get(0);
							projectSign.setProposalOrganId(organj.getOrganCode());

						}

						String projectName = transferBasicInfo.get(3);
						projectSign.setProjectName(projectName);
						List<ProjectSign> pList = projectSignmapper.select(projectSign);


//              ProjectJointPlan pj = new ProjectJointPlan();
//              pj.setName(row.getCell(4).getStringCellValue());
//              List<ProjectJointPlan> pjList = projectJointPlanMapper.select(pj);
//              Integer pId = 0;
//              if(pjList.size()>0) {
//                  pId = pjList.get(0).getId();
//              }

						String projectNatureName = transferBasicInfo.get(4);
						String projectTypeName = transferBasicInfo.get(5);
						String contractArea = transferBasicInfo.get(6);
						String signTime = transferBasicInfo.get(7);
						String endTimeStr = transferBasicInfo.get(8);


						if (pList.size() > 0) {
							projectSign.setInMonth(month);
							projectSign = pList.get(0);
							projectSign.setProjectName(projectName);
							projectSign.setProjectNatureName(projectNatureName);
							projectSign.setProjectTypeName(projectTypeName);
							//projectSign.setProjectTypeName(row.getCell(5).getStringCellValue());
							if (("新项目").equals(projectTypeName)) {
								projectSign.setIsNew(1);
							} else if (("业委会项目").equals(projectTypeName)) {
								projectSign.setIsNew(3);
							} else {
								projectSign.setIsNew(2);
							}
							projectSign.setContractArea(new BigDecimal(contractArea));
							if (("长期").equals(signTime)) {
								projectSign.setSignTime(sdf.parse("9999-12-31"));
							} else if (("暂无").equals(signTime) ||
									("交付之日起五年").equals(signTime) ||
									("待定").equals(signTime) || !StringUtils.hasText(signTime)) {

							} else {
								projectSign.setSignTime(sdf.parse(signTime));
							}
							projectSign.setSingTimeStr(signTime);
							if (("长期").equals(endTimeStr)) {
								projectSign.setEndTime(sdf.parse("9999-12-31"));
							} else if (("暂无").equals(endTimeStr) ||
									("交付之日起五年").equals(endTimeStr) ||
									("待定").equals(endTimeStr) || !StringUtils.hasText(endTimeStr)) {

							} else {
								projectSign.setEndTime(sdf.parse(endTimeStr));
							}
							projectSign.setEndTimeStr(endTimeStr);
							projectSignmapper.updateByPrimaryKey(projectSign);
						} else {
							projectSign.setInMonth(month);
							projectSign.setProjectName(projectName);
							projectSign.setProjectNatureName(projectNatureName);
							projectSign.setProjectTypeName(projectTypeName);

							if (("新项目").equals(projectTypeName)) {
								projectSign.setIsNew(1);
							} else {
								projectSign.setIsNew(2);
							}
							projectSign.setContractArea(new BigDecimal(contractArea));

							if (("长期").equals(signTime)) {
								projectSign.setSignTime(sdf.parse("9999-12-31"));
							} else if (("暂无").equals(signTime) ||
									("交付之日起五年").equals(signTime) ||
									("待定").equals(signTime) || !StringUtils.hasText(signTime)) {

							} else {
								projectSign.setSignTime(sdf.parse(signTime));
							}
							projectSign.setSingTimeStr(signTime);

							if (("长期").equals(endTimeStr)) {
								projectSign.setEndTime(sdf.parse("9999-12-31"));
							} else if (("暂无").equals(endTimeStr) ||
									("交付之日起五年").equals(endTimeStr) ||
									("待定").equals(endTimeStr) || !StringUtils.hasText(endTimeStr)) {

							} else {
								projectSign.setEndTime(sdf.parse(endTimeStr));
							}

							projectSign.setEndTimeStr(endTimeStr);
							projectSignmapper.insertSelective(projectSign);
						}
						ProjectSignItem projectSignItem = new ProjectSignItem();
						projectSignItem.setProjectSignId(projectSign.getId());

//              ProjectJointPlan yt = new ProjectJointPlan();
//              yt.setName(row.getCell(9).getStringCellValue());
//              List<ProjectJointPlan> ytList = projectJointPlanMapper.select(yt);
//              Integer ytId = 0;
//              if(ytList.size()>0) {
//                  ytId = ytList.get(0).getId();
//              }
//              if(ytId == 0) {
//                  yt = new ProjectJointPlan();
//                  yt.setName("其他类型物业");
//                  ytList = projectJointPlanMapper.select(yt);
//                  if(ytList.size()>0) {
//                      ytId =  ytList.get(0).getId();
//                  }
//
//                  //throw new ServiceException(row.getCell(9).getStringCellValue()+ "行业态不存在。");
//              }


						String businessTypeName = transferBasicInfo.get(9);

						String ratesArea = transferBasicInfo.get(10);
						String price = transferBasicInfo.get(11);
						String monthIncome = transferBasicInfo.get(12);
						String yearIncome = transferBasicInfo.get(13);

						String monthNumber = transferBasicInfo.get(14);

						String countProportion = transferBasicInfo.get(15);

						String remark = transferBasicInfo.get(16);

						projectSignItem.setBusinessTypeName(businessTypeName);
						// projectSignItem.setBusinessType(ytId);
						projectSignItem.setIsDelete(0);
						List<ProjectSignItem> pjiList = mapper.select(projectSignItem);
						if (pjiList.size() > 0) {
							projectSignItem.setId(pjiList.get(0).getId());
							projectSignItem.setRatesArea(new BigDecimal(ratesArea));
							projectSignItem.setPrice(new BigDecimal(price));
							projectSignItem.setMonthIncome(new BigDecimal(monthIncome));
							projectSignItem.setYearIncome(new BigDecimal(yearIncome));
							projectSignItem.setMonthNumber(Integer.parseInt(monthNumber));
							projectSignItem.setCountProportion(new BigDecimal(countProportion));
							projectSignItem.setRemark(remark);
							mapper.updateByPrimaryKey(projectSignItem);
						} else {
							projectSignItem.setBusinessTypeName(businessTypeName);
							projectSignItem.setRatesArea(new BigDecimal(ratesArea));
							projectSignItem.setPrice(new BigDecimal(price));
							projectSignItem.setMonthIncome(new BigDecimal(monthIncome));
							projectSignItem.setYearIncome(new BigDecimal(yearIncome));
							projectSignItem.setMonthNumber(Integer.parseInt(monthNumber));
							projectSignItem.setCountProportion(new BigDecimal(countProportion));
							projectSignItem.setRemark(remark);
							mapper.insert(projectSignItem);
						}

					}
					return new Result().setResultCode(ResultCode.OK).setResultMsg(AdvertisingFileDirectory.SUCESS);
				} else {
					return new Result().setResultCode(ResultCode.FAIL).setResultMsg("校验不通过").setData(mList);
				}
			}catch (Exception e){
			log.error("",e);
				e.printStackTrace();
				mList.add("模板格式错误");
				return new Result().setResultCode(ResultCode.FAIL).setResultMsg("模板校验不通过，请下载最新模板").setData(mList);
			}

	   
	}

    private Boolean checkOrganName(Sheet sheet0, List<String> mList,Boolean flag) {

        for(int i = 4; i <= sheet0.getPhysicalNumberOfRows(); i++) {
            ProjectSign projectSign = new ProjectSign();
            Row row = sheet0.getRow(i); 
            int x=i+1;
            if(null == row) {
                break;
            }
            
           String organName = row.getCell(2).getStringCellValue();
            Organ organj = new Organ();
            organj.setName(organName);
            List<Organ> organList = organMapper.select(organj);
            if(organList.isEmpty()||organList.size()==0) {
                try {
                    String orgMap = orgMap(organName);
                    projectSign.setProposalOrganId(orgMap);
               } catch (ServiceCodeException e) {
                   flag=false;
                   mList.add("第【"+x+"】行的第3列{接管区域} "+e.getMessage());
               }
              
            }
            
        }
        return flag;
    }
	
	
	
	
	
	public String orgMap(String orgName) {
		Map<String,String> map = new HashedMap<String,String>();
		map.put("重庆金阳", "01BU");
		map.put("碧桂园金阳物业服务有限公司", "01BU");
		map.put("天津区域", "01BG");
		
		map.put("衡水碧桂园城市服务有限公司", "01BT");
		map.put("衡水城市公司", "01BT");
		map.put("粤北区域", "dup0303");
		map.put("清远碧桂园城市服务有限公司", "dup0303");
		map.put("菏泽碧桂园凯兴物业服务有限公司", "01BV");
		map.put("青岛碧桂园润锦物业服务有限公司", "dup0103");
		map.put("北京盛世", "dup0102");
		map.put("北京盛世物业服务公司", "dup0102");
		map.put("西藏城市公司", "01BW");
		map.put("西藏碧桂园物业城市服务有限公司", "01BW");
		map.put("苏州区域", "01BQ");
		map.put("上海/苏州区域", "dup0201");
		map.put("韩城城市公司", "01BI");
		map.put("韩城公司", "01BI");
		map.put("韩城碧桂园城市服务有限公司", "01BI");
		
		map.put("湖北区域", "0114");
		map.put("湖北清能", "01BD");
		map.put("清能碧桂园", "01BD");
		map.put("山东润锦公司", "dup0103");
		map.put("遵义城市公司", "01BK");
		map.put("遵义碧桂园物业城市服务有限公司", "01BK");
		map.put("重庆碧桂园坤煌城市服务有限公司", "0153");
		map.put("肇庆区域", "0154");
		
		map.put("河北碧桂园环城物业服务有限公司", "01BH");
		String name = map.get(orgName);
		if(null == name || "".equals(name)) {
		    throw new ServiceCodeException("","查找不到此区域！！");
		}
		return name;
		
	}


	public static Workbook getWorkBook(MultipartFile file) {
		//获得文件名
		String fileName = file.getOriginalFilename();
		//创建Workbook工作薄对象，表示整个excel
		Workbook workbook = null;
		try {
			//获取excel文件的io流
			InputStream is = null;
			try {
				is = file.getInputStream();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
			if(fileName.endsWith("xls")){
				//2003
				workbook = new HSSFWorkbook(is);
			}else if(fileName.endsWith("xlsx")){
				//2007
				workbook = new XSSFWorkbook(is);
			}
		} catch (IOException e) {
			e.getMessage();
			return null;
		}
		return workbook;
	}

}
