/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.cku.oa.finance.service;

import java.util.Date;
import java.util.List;

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

import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.oa.finance.dao.PaymentChargingItemDao;
import com.cku.oa.finance.dao.PaymentChargingItemGroupDao;
import com.cku.oa.finance.dao.PaymentOrderDetailDao;
import com.cku.oa.finance.dao.PaymentOrderProjectDao;
import com.cku.oa.finance.dao.PaymentProjectCartDao;
import com.cku.oa.finance.dao.SaFinanceSubjectMappingDao;
import com.cku.oa.finance.entity.PaymentChargingItem;
import com.cku.oa.finance.entity.PaymentOrderDetail;
import com.cku.oa.finance.entity.PaymentOrderProject;
import com.cku.oa.finance.entity.PaymentProjectCart;
import com.cku.oa.finance.entity.SaFinanceSubjectMapping;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;

/**
 * 项目临时购物车Service
 *
 * @author lyy
 * @version 2016-08-08
 */
@Service
@Transactional(readOnly = true)
public class PaymentProjectCartService extends CrudService<PaymentProjectCartDao, PaymentProjectCart> {
	@Autowired
	private PaymentChargingItemGroupDao paymentChargingItemGroupDao;
	@Autowired
	private PaymentChargingItemDao paymentChargingItemDao;
	@Autowired
	private PaymentOrderDetailDao paymentOrderDetailDao;
	@Autowired
	private PaymentOrderProjectDao paymentOrderProjectDao;
	@Autowired
	private SaFinanceSubjectMappingDao saFinanceSubjectMappingDao;

	public PaymentProjectCart get(String id) {
		return super.get(id);
	}

	public List<PaymentProjectCart> findList(PaymentProjectCart paymentProjectCart) {
		return super.findList(paymentProjectCart);
	}

	public List<PaymentProjectCart> findListByVoucherCode(PaymentProjectCart paymentProjectCart) {
		if (paymentProjectCart.getVoucherCode() == null || "".equals(paymentProjectCart.getVoucherCode())) {
			return null;
		} else {
			PaymentProjectCart findProjectCart = new PaymentProjectCart();
			findProjectCart.setVoucherCode(paymentProjectCart.getVoucherCode());
			findProjectCart.setDelFlag("0");
			return super.findList(findProjectCart);
		}

	}

	public Page<PaymentProjectCart> findPage(Page<PaymentProjectCart> page, PaymentProjectCart paymentProjectCart) {
		return super.findPage(page, paymentProjectCart);
	}

	@Transactional(readOnly = false)
	public void save(PaymentProjectCart paymentProjectCart) {
		String businessOrderCode = IdGen.uuid();
		if (paymentProjectCart.getChargingItemId().startsWith("yw")) {
			saveGroup(paymentProjectCart, businessOrderCode);
		} else {
			saveOne(paymentProjectCart, businessOrderCode);
		}
		// 需要进行项目拆分的项目id
		// if("76,13,100,134".contains(paymentProjectCart.getChargingItemId())){
		// paymentProjectCart.setAddTime(new Date());
		// //此类项目只收费100，剩余的作为服务费进行结算
		// Double total = Integer.parseInt(paymentProjectCart.getNum()) *
		// Double.parseDouble("100");
		// //服务费对象
		// PaymentProjectCart serviceFeeModel = new PaymentProjectCart();
		// try {
		// PropertyUtils.copyProperties(serviceFeeModel , paymentProjectCart);
		// //服务费为每个项目的金额-100再*业务数量
		// Double fee = Integer.parseInt(paymentProjectCart.getNum()) *
		// (Double.parseDouble(paymentProjectCart.getPrice())-Double.parseDouble("100"));
		// Double price =
		// Double.parseDouble(paymentProjectCart.getPrice())-Double.parseDouble("100");
		// serviceFeeModel.setIsNewRecord(false);//设置该记录为新添记录
		// serviceFeeModel.setPrice(price.toString());//计算后服务费的单价
		// serviceFeeModel.setTotalPrice(fee.toString());//计算后服务费的总价
		// serviceFeeModel.setChargingItemId("217");//服务费项目ID
		// serviceFeeModel.setChargingItemName("新生幼犬芯片埋植服务费");//服务费项目名称
		// super.save(serviceFeeModel);
		// } catch (IllegalAccessException | InvocationTargetException |
		// NoSuchMethodException e) {
		// e.printStackTrace();
		// }
		// paymentProjectCart.setPrice("100");
		// paymentProjectCart.setTotalPrice(total.toString());
		// super.save(paymentProjectCart);
		// } else {
		// dao.findList(paymentProjectCart);
		// paymentProjectCart.setAddTime(new Date());
		// Double total = Integer.parseInt(paymentProjectCart.getNum()) *
		// Double.parseDouble(paymentProjectCart.getPrice());
		// paymentProjectCart.setTotalPrice(total.toString());
		// super.save(paymentProjectCart);
		// }
	}

	@Transactional(readOnly = false)
	public void add(String id) {
		PaymentProjectCart paymentProjectCart = this.get(id);
		paymentProjectCart.setNum(Integer.parseInt(paymentProjectCart.getNum()) + 1 + "");
		paymentProjectCart.setTotalPrice(Double.parseDouble(paymentProjectCart.getTotalPrice())
				+ Double.parseDouble(paymentProjectCart.getPrice()) + "");
		super.save(paymentProjectCart);
	}

	@Transactional(readOnly = false)
	public void del(String id) {
		PaymentProjectCart paymentProjectCart = this.get(id);
		paymentProjectCart.setNum(Integer.parseInt(paymentProjectCart.getNum()) - 1 + "");
		paymentProjectCart.setTotalPrice(Double.parseDouble(paymentProjectCart.getTotalPrice())
				- Double.parseDouble(paymentProjectCart.getPrice()) + "");
		super.save(paymentProjectCart);
	}

	@Transactional(readOnly = false)
	public void delete(PaymentProjectCart paymentProjectCart) {
		super.delete(paymentProjectCart);
	}

	@Transactional(readOnly = false)
	public void deletePaymentProjectCart(PaymentProjectCart paymentProjectCart) {
		if (StringUtils.isBlank(paymentProjectCart.getBusinessOrderCode())) {
			super.delete(paymentProjectCart);
		} else {
			dao.deleteByBusinessOrderCode(paymentProjectCart);
		}
	}

	@Transactional(readOnly = false)
	public void changePrice(String id, String price) {
		PaymentProjectCart paymentProjectCart = this.get(id);
		Double priceDouble = Double.parseDouble(price);
		Double totalPrice = priceDouble * Integer.parseInt(paymentProjectCart.getNum());
		paymentProjectCart.setPrice(priceDouble.toString());
		paymentProjectCart.setTotalPrice(totalPrice.toString());
		super.save(paymentProjectCart);
	}

	private void saveOne(PaymentProjectCart paymentProjectCart, String businessOrderCode) {
		// 防止页面多次返回引起的提交数据错误
		PaymentChargingItem item = paymentChargingItemDao.get(paymentProjectCart.getChargingItemId());
		paymentProjectCart.setChargingItemName(item.getName());
		paymentProjectCart.setPrice(item.getPrice());
		PaymentOrderProject paymentOrderProject = paymentOrderProjectDao.get(paymentProjectCart.getProjectId());
		paymentProjectCart.setProjectName(paymentOrderProject.getName());
		SaFinanceSubjectMapping saFinanceSubjectMapping = saFinanceSubjectMappingDao.get(paymentProjectCart.getBusinessId());
		paymentProjectCart.setBusinessName(saFinanceSubjectMapping.getSubjectName());
		PaymentProjectCart findProjectCart = new PaymentProjectCart();
		findProjectCart.setVoucherCode(paymentProjectCart.getVoucherCode());
		findProjectCart.setDelFlag("0");
		List<PaymentProjectCart> list = dao.findList(findProjectCart);
		if (list != null && list.size() > 0) {
			if (!list.get(0).getProjectId().equals(paymentProjectCart.getProjectId())
					|| !list.get(0).getMemberCode().equals(paymentProjectCart.getMemberCode())) {
				throw new ZAException(ZAErrorCode.ZA_ERROR, "此凭证号已经录入，且录入的会员号或标识不同！");
			}
		}
		PaymentOrderDetail paymentOrderDetail = new PaymentOrderDetail();
		paymentOrderDetail.setVoucherCode(paymentProjectCart.getVoucherCode());
		List list1 = paymentOrderDetailDao.findList(paymentOrderDetail);
		if (list1 != null && list1.size() > 0) {
			throw new ZAException(ZAErrorCode.ZA_ERROR, "此凭证号已经录入！");
		}
		paymentProjectCart.setAddTime(new Date());
		paymentProjectCart.setBusinessOrderCode(businessOrderCode);
		// 老的存储方法，存储一条记录，记录里含办理的次数
		// BigDecimal bigNum = new BigDecimal(paymentProjectCart.getNum());
		// BigDecimal bigPrice = new BigDecimal(paymentProjectCart.getPrice());
		// paymentProjectCart.setTotalPrice(bigNum.multiply(bigPrice).toString());
		// super.save(paymentProjectCart);

		// 新的存储方法，存储多条记录，每条记录的num固定为1
		int num = Integer.parseInt(paymentProjectCart.getNum());
		for (int i = 0; i < num; i++) {
			paymentProjectCart.setId(null);
			paymentProjectCart.setNum("1");
			paymentProjectCart.setTotalPrice(paymentProjectCart.getPrice());
			super.save(paymentProjectCart);
		}

	}

	private void saveGroup(PaymentProjectCart paymentProjectCart, String businessOrderCode) {
		String paymentChargingItemGroupId = paymentProjectCart.getChargingItemId().replace("yw", "");
		List<String> paymentChargingItemGroupItemList = paymentChargingItemGroupDao
				.getPaymentChargingItemIdsAndBizIdByGroupId(paymentChargingItemGroupId);
		for (String idStr : paymentChargingItemGroupItemList) {
			String[] ids = idStr.split(",");
			PaymentChargingItem paymentChargingItem = paymentChargingItemDao.get(ids[0]);
			PaymentProjectCart cart = new PaymentProjectCart();
			cart.setProjectId(paymentProjectCart.getProjectId());
			cart.setProjectName(paymentProjectCart.getProjectName());
			cart.setMemberCode(paymentProjectCart.getMemberCode());
			cart.setMemberName(paymentProjectCart.getMemberName());
			cart.setChargingItemId(paymentChargingItem.getId());
			cart.setChargingItemName(paymentChargingItem.getName());
			cart.setNum(paymentProjectCart.getNum());
			cart.setPrice(paymentChargingItem.getPrice());
			cart.setVoucherCode(paymentProjectCart.getVoucherCode());
			cart.setBusinessId(ids.length > 1 ? ids[1] : null);

			// 老的存储方法，只存一条，数量是num
			// saveOne(cart, businessOrderCode);

			// 新的存储方法，数量为1，存储num条记录：
			int num = Integer.parseInt(paymentProjectCart.getNum());
			for (int i = 0; i < num; i++) {
				cart.setId(null);
				cart.setNum("1");
				saveOne(cart, businessOrderCode);
			}
		}
	}
}