/*******************************************************************************
 * Copyright 2019 2Fi Business Solutions Ltd.
 *
 *
 *
 * This code is copyrighted. Under no circumstances should any party, people,
 * or organization should redistribute any portions of this code in any form,
 * either verbatim or through electronic media, to any third parties, unless
 * under explicit written permission by 2Fi Business Solutions Ltd.
 ******************************************************************************/
package com.ffii.tbms.reports.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.ffii.core.dao.JdbcDao;
import com.ffii.core.utils.SecurityUtils;
import com.ffii.core.web.AbstractService;


@Service
public class CustomerReportService extends AbstractService {

	@Autowired
	private JdbcDao jdbcDao;

	@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class, readOnly = true)
	public List<Map<String, Object>> search(Map<String, Object> args) {

		SecurityUtils.authArgs(args);

		StringBuilder sql = new StringBuilder( " SELECT  "
			+ " 	c.created, "
			+" CONCAT(IF(c.firstName IS NULL, '', CONCAT(c.firstName, ' ')), "
				+" IF(c.surname IS NULL, '', CONCAT(c.surname, ' '))) AS customerName, "
			+ " 	c.nameCh, "
			+ " 	c.phone1, "
			+ " 	c.phone2, "
			+ " 	c.email, "
			+ " 	c.address, "
			+ " 	c.remarks, "
			+ " 	co.orderAmount AS orderAmount "
			+ " FROM "
			+ " 	customer c "
			+ " 		LEFT JOIN "
			+ " 	(SELECT  "
			+ " 		o.custId, SUM(oi.price) AS orderAmount "
			+ " 	FROM "
			+ " 		orders o "
			+ " 	LEFT JOIN order_item oi ON o.id = oi.orderId "
			+ " 	WHERE "
			+ " 		o.deleted = 0 AND oi.deleted = 0 "
			+ " 			AND (o.status = 0 OR o.status = 1) "
			+ " 	GROUP BY o.custId) co ON co.custId = c.id "
			+ " WHERE "
			+ " 	c.deleted = 0 "

			);

			if(args != null){
				if(args.containsKey("sysGroupId"))
					sql.append(" AND c.sysGroupId = :sysGroupId ");
			}

			sql.append(" GROUP BY c.id "
			+ " ORDER BY c.created ");
	
		return jdbcDao.queryForList(sql.toString(), args);
	}

}
