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


import cn.com.countrygarden.bi.main.model.erp.CacheEntity;
import cn.com.countrygarden.bi.main.model.erp.JdbcConstants;
import cn.com.countrygarden.bi.main.model.erp.PrepaidAmountMsg;
import cn.com.countrygarden.bi.main.repository.erp.JdbcPrepaidRepository;
import cn.com.countrygarden.bi.main.repository.erp.JdbcPublicRepository;
import cn.com.countrygarden.bi.main.service.erp.ExcelPrepaidAmountService;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import cn.com.countrygarden.bi.main.util.erp.ExcelData;
import cn.com.countrygarden.bi.main.util.erp.ImportExcelUtils;

import org.apache.commons.net.ntp.TimeStamp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

;

/**
 * @Author christ.lai
 * @Description 预收资料
 * @Date 14:31 2018/5/20
 */
@Service
@Scope("prototype")
public class ExcelPrepaidAmountServiceImpl implements ExcelPrepaidAmountService {

    private final Logger logger = LoggerFactory.getLogger(ExcelPrepaidAmountServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getExcel(JdbcConstants jdbcConstants, ServletContext application ) throws Exception {
        logger.info("上传文件开始......");
        ImportExcelUtils excelRead = new ImportExcelUtils();
        //读取excel文件，然后把读出的结果以行的形式存储在List中
        List<ArrayList<String>> arrayLists = excelRead.readExcel(jdbcConstants.getFile(),jdbcConstants.getSheet());
        List<PrepaidAmountMsg> prepaidAmountMsgList = new ArrayList<PrepaidAmountMsg>();
        boolean flag = true;
        JdbcPublicRepository jpr = new JdbcPublicRepository(jdbcConstants); //校验查询工具类
        int cid = Integer.parseInt(arrayLists.get(0).get(0)); //取第一行的第一个commid为参数
        Set<String> roomSet = null;
        Set<String> custSet = null;
        Set<String> parkSet = null;
        //缓存中不存在，查询数据库，得到要缓存的数据，缓存到redis
//		if(!RedisUtils.exits("ERPdataUpload-roomSign-"+cid)){
			CacheEntity ce = jpr.getCacheData(cid);
			roomSet = ce.getRoomSet();
			custSet = ce.getCustSet();
			parkSet = ce.getParkSet();
			//集合不为空，则缓存到redis
			if(roomSet != null && roomSet.size() != 0){
				for(String value : roomSet){
					RedisUtils.sadd("ERPdataUpload-roomSign-"+cid,value);
				}
			}
			if(custSet != null && custSet.size() != 0){
				for(String value : custSet){
					RedisUtils.sadd("ERPdataUpload-custName-"+cid,value);
				}
			}
			if(parkSet != null && parkSet.size() != 0){
				for(String value : parkSet){
					RedisUtils.sadd("ERPdataUpload-parkName-"+cid,value);
				}
			}
//		}
        for (ArrayList<String> stringArrayList : arrayLists) {
            StringBuilder errorBuilder = new StringBuilder();
            // 字段验证
            if (StringUtil.isBlankOrEmpty(stringArrayList.get(0))) {
                errorBuilder.append("项目编号为空 ,");
                flag = false;
            }
            if (StringUtil.isBlankOrEmpty(stringArrayList.get(1))) {
                errorBuilder.append("客户类别为空 ,");
                flag = false;
            }
            if (StringUtil.isBlankOrEmpty(stringArrayList.get(2))) {
                errorBuilder.append("客户名称为空,");
                flag = false;
            }else{
				int commid = Integer.parseInt(stringArrayList.get(0));
				String yzmc = stringArrayList.get(2);
				if(!StringUtil.checkName(stringArrayList.get(2))){
					errorBuilder.append("客户名称格式不正确, ");
					flag = false;
				}
				if(!RedisUtils.sismember("ERPdataUpload-custName-"+commid,yzmc)){
					errorBuilder.append("客户名称不存在, ");
					flag = false;
				}
			}
            if (!StringUtil.isBlankOrEmpty(stringArrayList.get(3))) {
            	int commid = Integer.parseInt(stringArrayList.get(0));
            	String roomSign = stringArrayList.get(3);
            	if(!RedisUtils.sismember("ERPdataUpload-roomSign-"+commid,roomSign)){
            		errorBuilder.append("房屋编号不存在,");
            		flag = false;
				}
            }
            if(!StringUtil.isBlankOrEmpty(stringArrayList.get(4))){
				int commid = Integer.parseInt(stringArrayList.get(0).trim());
				String parkName = stringArrayList.get(4);
				if(!RedisUtils.sismember("ERPdataUpload-parkName-"+commid,parkName)){
					errorBuilder.append("车位编号不存在,");
            		flag = false;
				}
			}
            if (StringUtil.isBlankOrEmpty(stringArrayList.get(5))) {
                errorBuilder.append("收费时间为空 ,");
                flag = false;
            }else{
				if(!StringUtil.checkDate(stringArrayList.get(5).trim())){
					errorBuilder.append("收费时间格式不正确 ,");
					flag = false;
				}
			}
            if (StringUtil.isBlankOrEmpty(stringArrayList.get(7))) {
                errorBuilder.append("预交余额（元）为空 ,");
                flag = false;
            }else{
				if(!StringUtil.checkMoney(stringArrayList.get(7).trim())){
					errorBuilder.append("欠费金额格式不正确,");
					flag = false;
				}
			}
            if (flag) {
                PrepaidAmountMsg prepaidAmountMsg = new PrepaidAmountMsg();
                prepaidAmountMsg.setCommid(Integer.parseInt(stringArrayList.get(0)));
                prepaidAmountMsg.setKhlb(stringArrayList.get(1));
                prepaidAmountMsg.setKhmc(stringArrayList.get(2));
                prepaidAmountMsg.setFwbh(stringArrayList.get(3));
                prepaidAmountMsg.setCwbh(stringArrayList.get(4));
                prepaidAmountMsg.setSfsj(stringArrayList.get(5));
                prepaidAmountMsg.setFyxm(stringArrayList.get(6));
                prepaidAmountMsg.setYjye(stringArrayList.get(7));
                prepaidAmountMsgList.add(prepaidAmountMsg);
            } else {
            	stringArrayList.add(errorBuilder.toString().split(",")[0]); //添加 Error Message 列
            }
        }
        System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" :校验模板结束.......");
        if (flag) {
            JdbcPrepaidRepository.jdbcConnect(jdbcConstants, prepaidAmountMsgList);//批量插入数据
            logger.info("上传文件结束......");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" :数据入库结束.......");
        } else {
            ExcelData data = new ExcelData();
            data.setName("预收资料");
            List<String> titles = new ArrayList<String>();
            titles.add("项目编号");
            titles.add("客户类别");
            titles.add("客户名称");
            titles.add("房屋编号");
            titles.add("车位编号");
            titles.add("收费时间");
            titles.add("费用项目");
            titles.add("预交余额（元）");
            titles.add("Error Message");
            data.setTitles(titles);
            data.setRows(arrayLists);
            String key = "prepaid";
            String current_key = key +"-"+ TimeStamp.getCurrentTime().toString();
            //使用域做缓存
            application.setAttribute(current_key,data);
            logger.info("上传文件异常......");
            return current_key;
        }
        return "success";
    }
}
