/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-06-21
 * 描述            ：分配结果实绩表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import market.Cm.mapper.BaseCostCptDMapper;
import market.Cm.mapper.BaseCostCptMMapper;
import market.Cm.mapper.BaseCostItemMapper;
import market.Cm.mapper.BaseCostOrgMapper;
import market.Cm.mapper.BaseDstItemMapper;
import market.Cm.mapper.BaseFiscalPeriodDMapper;
import market.Cm.mapper.CmCostDstResultMapper;
import market.Cm.mapper.CmCostItemResultMapper;
import market.Cm.service.CmCostDstResultService;
import market.Cm.vo.BaseCostCptD;
import market.Cm.vo.BaseCostCptM;
import market.Cm.vo.BaseCostItem;
import market.Cm.vo.BaseCostOrg;
import market.Cm.vo.BaseDstItem;
import market.Cm.vo.BaseFiscalPeriodD;
import market.Cm.vo.CmCostDstResult;
import market.Cm.vo.CmCostItemResult;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Pms.Util.ImportUtil;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="CmCostDstResultService")
public class CmCostDstResultServiceImpl extends BaseServiceImpl<CmCostDstResult,Object> implements CmCostDstResultService {
	
	/**
	 * 分配结果实绩：查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doQueryCmCostDstResult(CommonPage<CmCostDstResult> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		CmCostDstResult ccdr = cp.getObject();
		try {
			String swhere = "";			
			if (ccdr.getDst_item_code()!=null && !"".equals(ccdr.getDst_item_code())) {
				swhere+=" and t.dst_item_code = '"+ccdr.getDst_item_code()+"'";//分配项目代码
			}
			if (ccdr.getDst_item_code_f()!=null && !"".equals(ccdr.getDst_item_code_f())) {
				swhere+=" and t.dst_item_code_f = '"+ccdr.getDst_item_code_f()+"'";//上级分配项目代码
			}
			if (ccdr.getItem_code()!=null && !"".equals(ccdr.getItem_code())) {
				swhere+=" and t.item_code = '"+ccdr.getItem_code()+"'";//成本项目
			}			
			if (ccdr.getOrg_code()!=null && !"".equals(ccdr.getOrg_code())) {
				swhere+=" and t.org_code = '"+ccdr.getOrg_code()+"'";//成本组织
			}
			if (ccdr.getPrd_num()!=null && !"".equals(ccdr.getPrd_num())) {
				swhere+=" and t.prd_num like '%"+ccdr.getPrd_num()+"%'";//成本期间
			}			
			if (ccdr.getValid_flg()!=null && !"".equals(ccdr.getValid_flg())) {
				swhere+=" and t.valid_flg = '"+ccdr.getValid_flg()+"'";//是否有效
			}
			if (ccdr.getAudit_flg()!=null && !"".equals(ccdr.getAudit_flg())) {
				swhere += " and t.audit_flg = '"+ccdr.getAudit_flg()+"'";//是否审核
			}
			if (ccdr.getIs_result()!=null && !"".equals(ccdr.getIs_result())) {
				swhere += " and t.is_result = '"+ccdr.getIs_result()+"'";//是否结果
			}
			List<CmCostDstResult> list = this.getMapper(CmCostDstResultMapper.class).doQueryCmCostDstResult(swhere);
			rm.setState("200");
			rm.setData(list);
		} catch (Exception e) {
			throw new Exception("查询失败，请联系管理员");
		}
		return rm;
	}
	
	/**
	 * 分配结果的审核及审核
	 * @param cp memo1[1:审核  0反审] dst_item_code分配项目代码  prd_num成本期间
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doChangeCmCostDstResultValidFlg(CommonPage<CmCostDstResult> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm = new ResultModel();
		String opr = cp.getMemo1();		
		List<CmCostDstResult> cdrList = cp.getObjectList();
		if (cdrList==null) {
			throw new Exception("请传入参数");
		}
		Date now = new Date();
		for (CmCostDstResult cdr : cdrList) {
			if (cdr.getDst_item_code()==null || "".equals(cdr.getDst_item_code())) {
				throw new Exception("分配项目代码不能为空");
			}
			if (cdr.getPrd_num()==null || "".equals(cdr.getPrd_num())) {
				throw new Exception("成本期间不能为空");
			}
			CmCostDstResult CDR = this.getMapper(CmCostDstResultMapper.class).findById(cdr.getDst_item_code(),cdr.getPrd_num());
			if (CDR==null) {
				throw new Exception("分配项目【"+cdr.getDst_item_code()+"】【"+cdr.getPrd_num()+"】对应的分配结果实绩不存在");
			}
			cdr.setAudit_man(userName);//审核人
			cdr.setAudit_time(now);//审核时间
			if ("1".equals(opr)) {//启用
				if ("1".equals(CDR.getAudit_flg())) {
					throw new Exception("分配结果实绩【"+CDR.getDst_item_name()+"】【"+CDR.getPrd_num()+"】已经审核，无法继续审核");
				}
				cdr.setAudit_flg("1");
			}else if ("0".equals(opr)) { //反审
				if ("0".equals(CDR.getAudit_flg())) {
					throw new Exception("分配结果实绩【"+CDR.getDst_item_name()+"】【"+CDR.getPrd_num()+"】未审核，无法反审");
				}
				cdr.setAudit_flg("0");
			}
			this.getMapper(CmCostDstResultMapper.class).update(cdr);
		}		
		rm.setState("200");
		rm.setMsgInfo("0".equals(cp.getMemo1())?"反审":"审核" + "操作成功");
		return rm;
	}
	
	/**
	 * 分配结果的修改：调整金额
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doUpdateCmCostDstResult(CommonPage<CmCostDstResult> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm  = new ResultModel();
		List<CmCostDstResult> list = cp.getObjectList();
		if (list==null || list.size()<=0) {
			throw new Exception("请传入参数");
		}
		Date now = new Date();
		for (CmCostDstResult cdr : list) {
			if (cdr.getDst_item_code()==null || "".equals(cdr.getDst_item_code())) {
				throw new Exception("分配项目代码不能为空");
			}
			if (cdr.getPrd_num()==null || "".equals(cdr.getPrd_num())) {
				throw new Exception("成本期间不能为空");
			}
			//判断传递的分配结果实绩是否存在
			CmCostDstResult CDR = this.getMapper(CmCostDstResultMapper.class).findById(cdr.getDst_item_code(),cdr.getPrd_num());
			if (CDR==null) {
				throw new Exception("当前选择的分配结果实绩在数据库中不存在，请重新查询");
			}
			if ("1".equals(CDR.getAudit_flg())) {
				throw new Exception("当前选择的分配结果实绩已经审核，无法修改");
			}		
			//核算量=分配量+调整量
			cdr.setAmount_value((CDR.getDst_value()!=null?CDR.getDst_value():0)+cdr.getAdjust_value());
			cdr.setUpdate_man(userName);
			cdr.setUpdate_time(now);
			this.getMapper(CmCostDstResultMapper.class).update(cdr);
		}
		rm.setState("200");
		rm.setMsgInfo("修改成功");
		return rm;
	}
	
	/**
	 * 分配结果的删除
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doDeleteCmCostDstResult(CommonPage<CmCostDstResult> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		List<CmCostDstResult> list = cp.getObjectList();
		if (list==null || list.size()<=0) {
			throw new Exception("请传入参数");
		}
		for (CmCostDstResult cdr : list) {
			if (cdr.getDst_item_code_f()==null || "".equals(cdr.getDst_item_code_f())) {
				throw new Exception("分配目标代码不能为空");
			}
			if (cdr.getPrd_num()==null || "".equals(cdr.getPrd_num())) {
				throw new Exception("成本期间不能为空");
			}
			
			//判断传递的分配结果实绩是否存在
			List<CmCostDstResult> cdrList = this.getMapper(CmCostDstResultMapper.class).find(cdr, 0, 0);
			if (cdrList!=null && cdrList.size()>0) {
				for (CmCostDstResult ccdr : cdrList) {
					if ("1".equals(ccdr.getAudit_flg())) {
						throw new Exception("分配目标【"+ccdr.getDst_item_name()+"】【"+ccdr.getPrd_num()+"】对应的分配结果实绩已经审核，无法删除");
					}
				}
				this.getMapper(CmCostDstResultMapper.class).deleteByDstItemCodeFPrdnum(cdr.getDst_item_code_f(), cdr.getPrd_num());
			}			
		}
		rm.setState("200");
		rm.setMsgInfo("删除成功");
		return rm;
	}
	
	/**
	 * 新增分配结果
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doInsertCmCostDstResult(CommonPage<CmCostDstResult> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		map.clear();
		Date now = new Date();
		ResultModel rm  = new ResultModel();
		
		List<CmCostDstResult> CCDRList = cp.getObjectList();
		if (CCDRList==null || CCDRList.size()<=0) {
			throw new Exception("请传入参数");
		}
		String prd_num = CCDRList.get(0).getPrd_num();
		BaseFiscalPeriodD bfpd = this.getMapper(BaseFiscalPeriodDMapper.class).findById(prd_num);
		if (bfpd==null) {
			throw new Exception("请传入正确的成本期间");
		}
		
		for (CmCostDstResult CIR : CCDRList) {
			//1.查找分配项目对应的分配目标项目【主表】
			BaseCostCptM bccm = this.getMapper(BaseCostCptMMapper.class).findById(CIR.getDst_item_code());
			if (bccm==null) {
				throw new Exception("未找到分配项目【"+CIR.getDst_item_name()+"】对应的分配目标");
			}
			//2.查找分配项目对应的分配依据项目【从表】
			BaseCostCptD BCCD = new BaseCostCptD();
			BCCD.setDst_item_code_f(bccm.getDst_item_code());
			List<BaseCostCptD> bccdList = this.getMapper(BaseCostCptDMapper.class).find(BCCD, 0, 0);
			if (bccdList==null || bccdList.size()<=0) {
				throw new Exception("未找到分配项目【"+CIR.getDst_item_name()+"】对应的分配依据");
			}
			
			//3.判断核算类型 【0分配  1归集】			
			if ("1".equals(bccm.getCpt_type())) {
				//4  【归集】
				//4.0 判断是否重复归集
				CmCostDstResult CCDR = this.getMapper(CmCostDstResultMapper.class).findById(bccm.getDst_item_code(),prd_num);
				if (CCDR!=null) {
					throw new Exception("已经存在成本期间【"+prd_num+"】的【"+bccm.getDst_item_name()+"】分配结果项目信息");
				}
				//通过核算公式得到【计算量】
				Double dst_value = doCalculate(bccm.getFormula_amount(), CIR.getPrd_num());			
				//4.1获取分配依据项目 对应的成本项目
				BaseDstItem bdi = this.getMapper(BaseDstItemMapper.class).findById(bccm.getDst_item_code());
				if (bdi==null) {
					throw new Exception("未找到分配项目【"+bccm.getDst_basis_name()+"】对应的分配项目信息");
				}
				//4.2保存数据到分配结果实绩表
				CmCostDstResult cdr = new CmCostDstResult();
				cdr.setDst_item_code(bccm.getDst_item_code());//分配项目代码
				cdr.setDst_item_name(bccm.getDst_item_name());
				cdr.setDst_item_code_f(bccm.getDst_item_code());//分配项目代码父
				cdr.setDst_item_name_f(bccm.getDst_item_name());//分配项目代码父
				cdr.setCpt_type(bccm.getCpt_type());//核算类型
				cdr.setItem_code(bdi.getItem_code());
				cdr.setItem_name(bdi.getItem_name());
				cdr.setOrg_code(bdi.getOrg_code());
				cdr.setOrg_name(bdi.getOrg_name());
				cdr.setPrd_num(CIR.getPrd_num());
				cdr.setRate_value(1d);//计算比率 (100%)
				cdr.setAmount_all(0d);//计算目标额
				cdr.setConsume_value(0d);//计算依据值	
				cdr.setDst_value(dst_value);//计算量
				cdr.setAmount_value(dst_value);//核算量==计算量
				cdr.setAdjust_value(0d);//调整量(0)
				cdr.setMsr_unit(bdi.getMsr_unit());//单位
				cdr.setIs_result(bdi.getIs_result());//是否结果
				cdr.setValid_flg("1");
				cdr.setCreate_man(userName);
				cdr.setCreate_time(now);
				this.getMapper(CmCostDstResultMapper.class).insert(cdr);
			}else if ("0".equals(bccm.getCpt_type())) {
				//5 【分配】			
				//5.1获取分配目标项目的分配目标量
				BaseDstItem bdiM = getDataOriginValue(bccm.getDst_item_code(), CIR.getPrd_num());
				Double dstValueM = bdiM.getDataValue();
				Double dstValueDTotal = 0d;//合计重量
				for (BaseCostCptD bccd : bccdList) {
					//5.2 判断分配结果实绩表是否重复
					CmCostDstResult CCDR = this.getMapper(CmCostDstResultMapper.class).findById(bccd.getDst_item_code(),CIR.getPrd_num());
					if (CCDR!=null) {
						throw new Exception("已经存在成本期间【"+CIR.getPrd_num()+"】的【"+bccd.getDst_item_name()+"】分配结果项目信息");
					}
					//5.3 获取分配依据项目 对应的成本项目
					BaseDstItem bdi = getDataOriginValue(bccd.getDst_item_code(), CIR.getPrd_num());					
					//5.4 保存数据到分配结果实绩表		
					CmCostDstResult cdr = new CmCostDstResult();
					cdr.setDst_item_code(bccd.getDst_item_code());
					cdr.setDst_item_name(bccd.getDst_item_name());
					cdr.setDst_item_code_f(bccm.getDst_item_code());
					cdr.setDst_item_name_f(bccm.getDst_item_name());
					cdr.setItem_code(bdi.getItem_code());
					cdr.setItem_name(bdi.getItem_name());
					cdr.setOrg_code(bdi.getOrg_code());
					cdr.setOrg_name(bdi.getOrg_name());
					cdr.setPrd_num(CIR.getPrd_num());			
					//分配项目从表的计算依据量
					Double dstValueD = bdi.getDataValue();
					cdr.setConsume_value(dstValueD);					
					
					//计算比率
					if (bccd.getFormula_rate()!=null && !"".equals(bccd.getFormula_rate())) {
						Double rate = doCalculate(bccd.getFormula_rate(), CIR.getPrd_num());				
						cdr.setRate_value(rate);
					}
					cdr.setAmount_all(dstValueM);//计算目标额 == 分配目标的计算依据量
					if (cdr.getRate_value()!=null && dstValueM!=null) {
						BigDecimal b = new BigDecimal(cdr.getRate_value() * dstValueM);
						cdr.setDst_value(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//计算量
						//如果数据处于集合的最后一位(分配目标量 - 前N未合计的计算量)
						if (bccd.equals(bccdList.get(bccdList.size()-1))) {
							cdr.setDst_value(dstValueM - dstValueDTotal);
						}else {
							dstValueDTotal += cdr.getDst_value();
						}
						cdr.setAmount_value(cdr.getDst_value());//核算量==计算量
					}
					cdr.setAdjust_value(0d);//调整量默认为0
					cdr.setMsr_unit(bdi.getMsr_unit());//单位
					cdr.setIs_result(bdi.getIs_result());//是否结果		
					cdr.setValid_flg("1");
					cdr.setCpt_type(bccm.getCpt_type());//核算类型
					cdr.setCreate_man(userName);
					cdr.setCreate_time(now);
					this.getMapper(CmCostDstResultMapper.class).insert(cdr);
				}
			
			}
		}		
		rm.setState("200");
		rm.setMsgInfo("新增分配结果实绩成功");
		return rm;
	}
	
	/**
	 * 分配结果实绩界面：直接新增
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doInsertCostDstResult(CommonPage<CmCostDstResult> cp) throws Exception{
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		ResultModel rm  = new ResultModel();
		
		CmCostDstResult ccdr = cp.getObject();
		BaseFiscalPeriodD bfpd = this.getMapper(BaseFiscalPeriodDMapper.class).findById(ccdr.getPrd_num());
		if (bfpd==null) {
			throw new Exception("请传入正确的成本期间");
		}
		
		BaseDstItem bdi = this.getMapper(BaseDstItemMapper.class).findById(ccdr.getDst_item_code());
		if (bdi==null) {
			throw new Exception("未找到分配项目【"+ccdr.getDst_item_name()+"】对应的分配项目信息");
		}
		CmCostDstResult cdr = new CmCostDstResult();
		cdr.setDst_item_code(ccdr.getDst_item_code());//分配项目代码
		cdr.setDst_item_name(ccdr.getDst_item_name());
		cdr.setDst_item_code_f(ccdr.getDst_item_code());//分配项目代码父
		cdr.setDst_item_name_f(ccdr.getDst_item_name());//分配项目代码父
		cdr.setCpt_type(ccdr.getCpt_type());//核算类型
		cdr.setItem_code(bdi.getItem_code());
		cdr.setItem_name(bdi.getItem_name());
		cdr.setOrg_code(bdi.getOrg_code());
		cdr.setOrg_name(bdi.getOrg_name());
		cdr.setPrd_num(ccdr.getPrd_num());
		cdr.setRate_value(1d);//分配比率 (100%)
		cdr.setConsume_value(ccdr.getConsume_value());//分配依据值	
		cdr.setDst_value(ccdr.getDst_value());//分配量
		cdr.setAmount_all(ccdr.getDst_value());//分配目标额==分配量
		cdr.setAmount_value(ccdr.getDst_value());//核算量==分配量
		cdr.setAdjust_value(0d);//调整量(0)
		cdr.setMsr_unit(bdi.getMsr_unit());//单位
		cdr.setIs_result(bdi.getIs_result());//是否结果
		cdr.setValid_flg("1");
		cdr.setMemo(ccdr.getMemo());
		cdr.setCreate_man(userName);
		cdr.setCreate_time(new Date());
		this.getMapper(CmCostDstResultMapper.class).insert(cdr);	
		rm.setState("200");
		rm.setMsgInfo("新增分配结果实绩成功");
		return rm;
	}	
	
	
	/**
	 * 分配结果实绩界面的导入功能
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImportCmCostDstResult() throws Exception{
		synchronized (this) {		
			ResultModel rm = new ResultModel();
			Workbook wb = null;
			URL url = this.getClass().getClassLoader().getResource("/");
	        // 替换路径中的空格
	        String filePath = url.getPath().replaceAll("%20", " ");
	        File file = new File(filePath);
	        
	        // 1.导入excel
	        try {
				List<FileItem> items = ImportUtil.getUpload(CmCostDstResultServiceImpl.this,file,getRequest());
				for (FileItem item : items) {
					// 若是文件域则读取文件流
					if (!item.isFormField()) {
						wb = ImportUtil.getWB(item, file.length());
					}
				}
				rm.setState("200");
				rm.setMsgInfo("导入成功！");
			} catch (FileUploadException e) {
				rm.setState("500");
				rm.setMsgInfo("导入失败！");
			}
	        
	        System.out.println("导入成功！");
	        // 2.读取Excel数据
			try {
				//第一个表单
				Sheet sheet = wb.getSheetAt(0);
				int numRow = sheet.getLastRowNum();//最后的行数
				if (numRow >= 1) {
					Date now = new Date();
					String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);										
					//获取所有的成本项目
					BaseCostItem BCI = new BaseCostItem();
					BCI.setValid_flg("1");
					List<BaseCostItem> bciList = this.getMapper(BaseCostItemMapper.class).find(BCI, 0, 0);
					//获取所有的成本组织
					BaseCostOrg BCO = new BaseCostOrg();
					BCO.setValid_flg("1");
					List<BaseCostOrg> bcoList = this.getMapper(BaseCostOrgMapper.class).find(BCO, 0, 0);
					//获取所有的成本分配项目
					BaseDstItem BDI = new BaseDstItem();
					BDI.setValid_flg("1");
					List<BaseDstItem> bdiList = this.getMapper(BaseDstItemMapper.class).find(BDI, 0, 0);
					//从第3行开始遍历读取表格
					String org_name,prd_num,item_name,consume_value,amount_value;
					for (int i = 1; i <= numRow; i++) {
						//读取每行的数据
						Row row = sheet.getRow(i);
						org_name = ImportUtil.getCellValue(row.getCell(0));		//成本组织
						item_name = ImportUtil.getCellValue(row.getCell(1));	//成本项目
						prd_num = ImportUtil.getCellValue(row.getCell(2)).substring(0,6);		//成本期间
						consume_value = ImportUtil.getCellValue(row.getCell(3));//消耗量
						amount_value = ImportUtil.getCellValue(row.getCell(4));	//金额

						CmCostDstResult cir = new CmCostDstResult();						
						//成本项目
						cir.setItem_name(item_name);
						for (BaseCostItem bci : bciList) {
							if (cir.getItem_name().equals(bci.getItem_name())) {
								cir.setItem_code(bci.getItem_code());
								continue;
							}
						}
						if (cir.getItem_code()==null) {
							throw new Exception("未找到成本项目【"+item_name+"】基础信息");
						}
						//成本组织
						cir.setOrg_name(org_name);
						for (BaseCostOrg bco : bcoList) {
							if (cir.getOrg_name().equals(bco.getOrg_name())) {
								cir.setOrg_code(bco.getOrg_code());
								continue;
							}
						}
						if (cir.getOrg_code()==null) {
							throw new Exception("未找到成本组织【"+org_name+"】基础信息");
						}
						//分配项目：通过成本组织和成本项目获取
						for (BaseDstItem bdi : bdiList) {
							if (cir.getOrg_code().equals(bdi.getOrg_code()) && cir.getItem_code().equals(bdi.getItem_code())) {
								cir.setDst_item_code(bdi.getDst_item_code());
								cir.setDst_item_name(bdi.getDst_item_name());																
								cir.setDst_item_code_f(bdi.getDst_item_code());
								cir.setDst_item_name_f(bdi.getDst_item_name());
								cir.setMsr_unit(bdi.getMsr_unit());
								continue;
							}
						}
						if (cir.getDst_item_code()==null) {
							throw new Exception("未找到【"+org_name+"】【"+item_name+"】对应的成本分配项目");
						}				
						cir.setPrd_num(prd_num);
						//判断是否重复导入
						CmCostDstResult isRepeat = this.getMapper(CmCostDstResultMapper.class).findById(cir.getDst_item_code(),cir.getPrd_num());
						if (isRepeat!=null) {
							throw new Exception("成本期间【"+cir.getPrd_num()+"】分配项目【"+cir.getDst_item_name()+"】已经存在分配结果实绩，无法导入");
						}
						cir.setRate_value(1d);//分配比率 (100%)
						cir.setConsume_value("".equals(consume_value)?0:Double.parseDouble(consume_value));						
						cir.setAmount_value("".equals(amount_value)?0:Double.parseDouble(amount_value));//核算量
						cir.setDst_value(cir.getAmount_value());//分配量==核算量
						cir.setAmount_all(cir.getAmount_value());//分配目标额==核算量
						cir.setAdjust_value(0d);//调整量(0)						
						cir.setIs_result("1");//是否结果(1结果项、0过程项)	
						cir.setValid_flg("1");
						cir.setCpt_type("0");//核算类型(0分配，1归集)																	
						cir.setMemo("分配结果实绩导入数据");
						cir.setValid_flg("1");
						cir.setAudit_flg("0");
						cir.setCreate_man(userName);
						cir.setCreate_time(now);
						this.getMapper(CmCostDstResultMapper.class).insert(cir);
					}
				}
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
			rm.setState("200");
			rm.setMsgInfo("表格导入成功！");
			return rm; 
		} 	
	}
	
	/**
	 * 获取分配项目的默认值
	 * @param BDI
	 * @param prd_num
	 * @return
	 * @throws Exception
	 */
	public BaseDstItem getDataOriginValue(String dst_item_code,String prd_num) throws Exception{
		BaseDstItem bdi = this.getMapper(BaseDstItemMapper.class).findById(dst_item_code);
		if (bdi==null) {
			throw new Exception("未找到分配项目代码【"+dst_item_code+"】对应的分配项目信息");
		}
		//A自动，B录入、C默认
		Double dataValue = null;		
		if ("A".equals(bdi.getData_origin())) {
			//自动：取数据源表的对应字段的值
			dataValue = this.getMapper(CmCostDstResultMapper.class).doQuaryDataOriginValue(bdi.getTable_name(), bdi.getColumn_name(), prd_num,bdi.getOrg_code(),bdi.getDst_item_code_rsl());
		}else if ("B".equals(bdi.getData_origin())) {
			if ("0".equals(bdi.getIs_result())) {
				//录入:取【分配项目实绩表】CmCostItemResult的【结果值】Amount_value				
				CmCostItemResult cir = this.getMapper(CmCostItemResultMapper.class).findById(bdi.getDst_item_code(),prd_num);
				if (cir==null) {
					throw new Exception("未找到【录入】的分配项目【"+bdi.getDst_item_name()+"】【"+prd_num+"】对应的分配项目实绩信息");
				}
				dataValue = cir.getAmount_value();				
			}else if ("1".equals(bdi.getIs_result())){
				//录入:取【分配结果实绩表】CmCostItemResult的【结果值】Amount_value				
				CmCostDstResult cir = this.getMapper(CmCostDstResultMapper.class).findById(bdi.getDst_item_code(),prd_num);
				if (cir==null) {
					throw new Exception("未找到【录入】的分配项目【"+bdi.getDst_item_name()+"】【"+prd_num+"】对应的分配结果实绩信息");
				}
				dataValue = cir.getAmount_value();
			}
		}else if ("C".equals(bdi.getData_origin())) {
			//默认:取【分配项目基础表】BaseDstItem的【默认值】Default_value
			dataValue = bdi.getDefault_value();
		}
		//约当系数
		if (dataValue!=null && bdi.getCfc_cpt()!=null) {
			dataValue = dataValue * bdi.getCfc_cpt();
		}
		bdi.setDataValue(dataValue);
		return bdi;
	}
		
	/**
	 * 
	 * @param oldFormula 核算公式
	 * @param prd_num 成本期间
	 * @return
	 * @throws Exception
	 */
	HashMap<String,String> map= new HashMap<String,String>();
	public Double doCalculate(String oldFormula,String prd_num) throws Exception{
		//0.公式拆分成单独的符号
		oldFormula = oldFormula.replace("100%", "1");
		String formula = oldFormula;
		formula = formula.replace(" ", "");
		formula = formula.replace("+",",");
		formula = formula.replace("-",",");
		formula = formula.replace("*",",");
		formula = formula.replace("/",",");
		formula = formula.replace("(",",");
		formula = formula.replace(")",",");
		List<String> fList = Arrays.asList(formula.split(","));
		for (String str : fList) {
			if (!isNum(str)) {
				//不是数字
				if (!"".equals(str)) {//键值对中不含公式符号			
					if (!map.containsKey(str)) {
						//1.单独找出每一个公式符号的依据量
						CmCostDstResult ccdr = this.getMapper(CmCostDstResultMapper.class).doQuaryDstItemBySign(str);
						BaseDstItem bdi = getDataOriginValue(ccdr.getDst_item_code(), prd_num);
						//2.找出所有的公式符号放到一个Map(公式符号，依据量)
						map.put(str, bdi.getDataValue()==null?0+"":bdi.getDataValue()+"");
						oldFormula = oldFormula.replace(str, bdi.getDataValue()==null?0+"":bdi.getDataValue()+"");
					}else {
						oldFormula = oldFormula.replace(str, map.get(str));
					}					
				}
			}else {
				//是数字
			}
		}
		System.out.println(formula);
		System.out.println(oldFormula);
		//3.用依据量代替公式符号，计算出比例值
		Double result = this.getMapper(CmCostDstResultMapper.class).doCalculate(oldFormula);		
		return result;
	}
	
	/**
	 * 判断字符是不是数字
	 * @param str
	 * @return
	 */
	public boolean isNum(String str){
		try {
			Double.parseDouble(str);
            return true;
		} catch (Exception e) {
			return false;
		}
	}
	
	 
}
