package com.xmomen.module.base.service.impl;

import java.util.List;

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

import com.xmomen.framework.mybatis.dao.MybatisDao;
import com.xmomen.module.base.entity.CdContractItem;
import com.xmomen.module.base.entity.CdItem;
import com.xmomen.module.base.model.CreateContractItem;
import com.xmomen.module.base.model.UpdateContractItem;
import com.xmomen.module.base.service.ContractItemService;
@Service
public class ContractItemServiceImpl implements ContractItemService {
	@Autowired
	MybatisDao mybatisDao;
	@Override
	@Transactional
	public void createContractItem(CreateContractItem createContractItem) {
		//根据createContractItem的addType属性，判断是新增还是修改
		if(1 == createContractItem.getAddType()){
			//新增
			CdItem item = new CdItem();
			item.setCdCategoryId(createContractItem.getCdCategoryId());
			//根据cdCategoryId查询CdItem
			List<CdItem> items = mybatisDao.selectByModel(item);
			//遍历查询结果，保存合同项
			for(CdItem itemDb : items){
				saveContractItem(createContractItem,itemDb);
			}
		}else if(2 == createContractItem.getAddType()){
			//修改
			CdItem item = new CdItem();
			item.setItemCode(createContractItem.getItemCode());
			//根据itemCode查询CdItem
			item = mybatisDao.selectOneByModel(item);
			if(item != null){
				//保存合同项
				saveContractItem(createContractItem,item);
			}
		}
		
	}
	@Transactional
	private void saveContractItem(CreateContractItem createContractItem,CdItem item){
		//先查询item是否存在，存在则更新
		CdContractItem contractItem = new CdContractItem();
		contractItem.setCdItemId(item.getId());
		contractItem.setCdContractId(createContractItem.getCdContractId());
		//根据cdItemId和cdContractId查询CdContractItem
		contractItem = mybatisDao.selectOneByModel(contractItem);
		if(contractItem == null){
			//如果不存在，则新增
			contractItem = new CdContractItem();
			contractItem.setCdItemId(item.getId());
			contractItem.setCdContractId(createContractItem.getCdContractId());
			contractItem.setContractType(createContractItem.getContractType());
			contractItem.setContractValue(createContractItem.getContractValue());
			mybatisDao.save(contractItem);
		}else{
			//如果存在，则更新
			contractItem.setContractType(createContractItem.getContractType());
			contractItem.setContractValue(createContractItem.getContractValue());
			mybatisDao.update(contractItem);
		}
	}
	
	@Transactional
	public void updateContractItem(Integer id, UpdateContractItem updateContractItem) {
		//更新合同项
	}
	@Transactional
	public void delete(Integer id) {
		//删除合同项
		 mybatisDao.deleteByPrimaryKey(CdContractItem.class, id);
	}
}
