/**
 */
package com.sifang.modules.customer.Service;

import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.entity.CrmAcceptingReport;
import com.sifang.modules.customer.entity.CustomerEntry;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.handler.CustomerEntryCodeImportHandler;
import com.sifang.modules.sunshine.handler.CustomerEntryRentHandler;
import com.sifang.modules.sys.common.persistence.Parameter;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.sifang.modules.sys.common.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import com.sifang.modules.customer.entity.CustomerEntryRent;
import com.sifang.modules.customer.dao.CustomerEntryRentDao;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 租金信息Service
 * @author lzp
 * @version 
 */
@Component
@Transactional(readOnly = true)
public class CustomerEntryRentService extends BaseService {

	@Autowired
	private CustomerEntryRentDao customerEntryRentDao;

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public CustomerEntryRent get(String id) {
		return customerEntryRentDao.get(id);
	}

	public void findEntryRentList(LayuiPage<Record> page, Map<String, String> map, Operator operator) {
		List<Record> list =customerEntryRentDao.findEntryRentList(page, map,operator);
		page.setCount(customerEntryRentDao.findEntryRentCount(map,operator));
		page.setData(list);
	}

	public void findEntryRentHis(LayuiPage<Record> page, String entryId) {
		List<Record> list =customerEntryRentDao.findEntryRentHisList(page, entryId);
		page.setCount(customerEntryRentDao.findEntryRentHisCount(entryId));
		page.setData(list);
	}
	
	@Transactional(readOnly = false)
	public void save(CustomerEntryRent customerEntryRent) {
		customerEntryRentDao.save(customerEntryRent);
	}
	
	@Transactional(readOnly = false)
	public void delete(String id) {
		customerEntryRentDao.deleteById(id);
	}



	/**
	 * 修改并网时间
	 */
	@Transactional(readOnly = false)
	public void updateMeetTime(CustomerEntry entry, CrmAcceptingReport report){
		try {
			CustomerEntryRent  rent = customerEntryRentDao.getByHql("from CustomerEntryRent where entryId=:p1",new Parameter(entry.getId()));
			if(rent == null){
				rent = new CustomerEntryRent();
				rent.setId(IdGen.uuid());
				rent.setEntryId(entry.getId());
				rent.setRentStaus("0");
			}
			String pay_cycle = entry.getPayCycle();
			String mergeTime = DateUtils.formatDateTime(entry.getMergeTime());
			String meet_time="";//应付日期
			if("1".equals(pay_cycle)){
				meet_time = DateUtils.subMonth(mergeTime,1);
			} else if ("2".equals(pay_cycle)) {
				meet_time = DateUtils.subMonth(mergeTime,3);
			} else if ("3".equals(pay_cycle)) {
				meet_time = DateUtils.subMonth(mergeTime,12);
			}
			//计算当期的天数
			long daysB = DateUtils.daysBetween(mergeTime,meet_time);
			//并网时间
			Date merge_time =entry.getMergeTime();
			int year = 1;
			BigDecimal unitPic = Db.queryBigDecimal("SELECT end_year FROM crm_project_rent_variable WHERE project_id=? AND start_year<=?<end_year AND STATUS='0'",entry.getProjectId(),year);
			BigDecimal amount = unitPic.multiply(new BigDecimal(daysB)).multiply(new BigDecimal(report.getComponentNum())).divide(new BigDecimal(365),2, BigDecimal.ROUND_HALF_UP);

			logger.info("租金信息：到期时间：{}，到期天数：{}，租金单价：{}   总金额：{}",merge_time,daysB,unitPic,amount);
			rent.setMeetTime(DateUtils.parseDate(meet_time));
			rent.setCurrentPayable(amount);
			rent.setPayCycle(pay_cycle);
			customerEntryRentDao.save(rent);

		}catch (Exception e){
			logger.error("并网修改租金记录并网时间失败{}",e);
		}
	}

	/**
	 * 校验导入支付数据
	 */
	@SuppressWarnings("unchecked")
	public Map<String, Object> checkImportPowerStationCode(Map<String, String> params, InputStream in) {
		Map<String, Object> retMap = Maps.newHashMap();
		retMap.put("operType", "check");
		CustomerEntryRentHandler handler = new CustomerEntryRentHandler();
		handler.setStartSheet(1);
		handler.setStartRow(2);
		try {
			new ExcelReader().check(in, params.get("extName"), handler);
			Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
			String templateError = (String) map.get("TemplateError");
			if (!handler.isCheckFlag()) {
				handler.appendErrorDetail("<p>未填充数据</p>");
			}
			String hanl = handler.getErrorDetail();
			if (StrKit.notBlank(templateError)) {
				retMap.put("errorDetail", templateError);
				retMap.put("errorMessage", "y");
			} else if (StringUtils.isNotBlank(hanl)) {
				retMap.put("errorDetail", hanl);
				retMap.put("errorMessage", "y");
			} else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
				retMap.put("overLimit", "y");
			} else {
				retMap.put("pass", "y");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return retMap;
	}

	/**
	 * 导入支付数据
	 */
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> importPowerStationCode(Map<String, String> params, InputStream in) {
		Map<String, Object> retMap = Maps.newHashMap();
		retMap.put("operType", "import");
		CustomerEntryRentHandler handler = new CustomerEntryRentHandler();
		handler.setStartSheet(1);
		handler.setStartRow(3);

		try {
			new ExcelReader().readExcel(in, params.get("fileName"), handler);

			List<Map<String,Object>> codeList = handler.getRetList();
			for(Map<String,Object> map :codeList){
				long count = Db.update("UPDATE `crm_customer_entry_rent` SET pay_status='1',pay_time=NOW() WHERE power_station_code=? AND DATE_FORMAT(meet_time,'%Y-%m-%d %H:%i:%s')=?",map.get("customerEntryCode"),map.get("payTime"));
			}
			retMap.put("successCount", codeList.size());
			retMap.put("pass", "y");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return retMap;
	}

	
}
