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

import market.Api.Mes.impl.Utils;
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.CmCostItemResultService;
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.beans.BeanUtils;
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="CmCostItemResultService")
public class CmCostItemResultServiceImpl extends BaseServiceImpl<CmCostItemResult,Object> implements CmCostItemResultService {

	/**
	 * 查询项目实绩信息
	 * 
	 * item_name 项目名称
	 * org_name  组织名称
	 * prd_num   成本区间
	 * memo1     1 创建时间 2 更新时间 3 审核时间
	 * @return
	 */
	public ResultModel queryCcirInfo(CommonPage<CmCostItemResult> cp) {
		ResultModel rm = new ResultModel("200", "查询成功!");
		CmCostItemResult ccir = cp.getObject();
		String condition = "  nvl(valid_flg, 1) <> 0 ";
		// 项目名称
		if (Utils.isNotEmpty(ccir.getItem_name())) {
			condition += " and item_name = '" + ccir.getItem_name() + "'";
		}
		// 组织名称
		if (Utils.isNotEmpty(ccir.getOrg_name())) {
			condition += " and org_code = '" + ccir.getOrg_name() + "'";
		}
		// 成本区间
		if (Utils.isNotEmpty(ccir.getPrd_num())) {
			condition += " and prd_num = '" + ccir.getPrd_num() + "'";
		}
		
		// 时间区间 
		if (cp.getMemo1() != null) {
			if ("1".equals(cp.getMemo1())) {
				condition += " and create_time between to_date('" + cp.getStartTime()
						+ "','yyyy-MM-dd HH24:mi:ss') and to_date('" + cp.getEndTime() + "','yyyy-MM-dd HH24:mi:ss') ";
			} else if ("2".equals(cp.getMemo1())) {
				condition += " and update_time between to_date('" + cp.getStartTime()
						+ "','yyyy-MM-dd') and to_date('" + cp.getEndTime() + "','yyyy-MM-dd') ";
			} else if ("3".equals(cp.getMemo1())) {
				condition += " and audit_time between to_date('" + cp.getStartTime()
				+ "','yyyy-MM-dd') and to_date('" + cp.getEndTime() + "','yyyy-MM-dd') ";
			}
		}
		List<CmCostItemResult> result = new ArrayList<CmCostItemResult>();
		try {
			result = this.getMapper(CmCostItemResultMapper.class).findWithCondition(null, condition,
					" create_time desc ", 0, 0);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败，请联系管理员!");
			return rm;
		}
		rm.setData(result);
		return rm;

	}
	
	
	
	/**
	 *  编辑项目实绩信息
	 * dst_item_code 必传
	 * prd_num		  必传	
	 * @param cp     都是单条操作
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel updateCcirInfo (CommonPage<CmCostItemResult> cp) {
		ResultModel rm = new ResultModel("200","");
		CmCostItemResult ccir = cp.getObject();
		Date curt_time = new Date();
		String memo = ccir.getMemo();
		String curt_man = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		boolean opt_flg = false ;
		if (Utils.isEmpty(ccir)) {
			rm.setState("500");
			rm.setMsgInfo("请传入相关参数!");
			return rm ;
		}else if (Utils.isEmpty(ccir.getDst_item_code())) {
			rm.setState("500");
			rm.setMsgInfo("请传入分配项目!");
			return rm ;
		}else if (Utils.isEmpty(ccir.getPrd_num())) {
			rm.setState("500");
			rm.setMsgInfo("请传入成本期间!");
			return rm ;
		}
		BaseFiscalPeriodD b = this.getMapper(BaseFiscalPeriodDMapper.class).findById(ccir.getPrd_num());
		if (b==null) {
			rm.setState("500");
			rm.setMsgInfo("传入成本期间格式不对,请重新操作!");
			return rm ;
		}
		CmCostItemResult tmp = this.getMapper(CmCostItemResultMapper.class)
				.findById(ccir.getDst_item_code(),ccir.getPrd_num());
		if (Utils.isEmpty(tmp)) {
			opt_flg = true ;
		}
		// 新增
		if (opt_flg) {
			// 获取项目信息
			BaseDstItem cbdi = this.getMapper(BaseDstItemMapper.class).findById(ccir.getDst_item_code());
			BeanUtils.copyProperties(cbdi, ccir);
			ccir.setCreate_man(curt_man);
			ccir.setCreate_time(curt_time);
			ccir.setMemo(memo);
			this.getMapper(CmCostItemResultMapper.class).insert(ccir);
		}else {
			ccir.setUpdate_time(curt_time);
			ccir.setUpdate_man(curt_man);
			this.getMapper(CmCostItemResultMapper.class).update(ccir);
		}
		return rm;
	}
	
	
	/**
	 * 批量删除信息
	 * 
	 * @param cp
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel deleteCcitInfo(CommonPage<CmCostItemResult> cp) {
		ResultModel rm = new ResultModel("200", "删除成功!");
		List<CmCostItemResult> ccirs = cp.getObjectList();
		if (Utils.isEmpty(ccirs)) {
			rm.setState("500");
			rm.setMsgInfo("请传入相关参数!");
			return rm;
		}
		for (CmCostItemResult ccir : ccirs) {
			if (Utils.isEmpty(ccir.getDst_item_code())) {
				rm.setState("500");
				rm.setMsgInfo("请传入分配项目!");
				return rm;
			} else if (Utils.isEmpty(ccir.getPrd_num())) {
				rm.setState("500");
				rm.setMsgInfo("请传入成本期间!");
				return rm;
			}
			try {
				this.getMapper(CmCostItemResultMapper.class).delete(ccir.getDst_item_code(),ccir.getPrd_num());;
			} catch (Exception e) {
				rm.setState("500");
				rm.setMsgInfo("删除失败，请联系管理员!");
				return rm;
			}
		}
		return rm;
	}
	
	/**
	 * 审核反审
	 * 
	 * @param cp memo1 1 审核 0 反审
	 * @return
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel auditCcitInfo(CommonPage<CmCostItemResult> cp) {
		ResultModel rm = new ResultModel("200", "审核成功!");
		List<CmCostItemResult> ccirs = cp.getObjectList();
		Date curt_time = new Date();
		String curt_man = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		if (Utils.isEmpty(ccirs)) {
			rm.setState("500");
			rm.setMsgInfo("请传入相关参数!");
			return rm;
		}
		for (CmCostItemResult ccir : ccirs) {

			if (Utils.isEmpty(ccir.getDst_item_code())) {
				rm.setState("500");
				rm.setMsgInfo("请传入分配项目!");
				return rm;
			} else if (Utils.isEmpty(ccir.getPrd_num())) {
				rm.setState("500");
				rm.setMsgInfo("请传入成本期间!");
				return rm;
			}
			CmCostItemResult tmp = this.getMapper(CmCostItemResultMapper.class).findById(ccir.getDst_item_code(),
					ccir.getPrd_num());
			if (Utils.isEmpty(tmp)) {
				rm.setState("500");
				rm.setMsgInfo("未找到项目实绩信息,请刷新重试!");
				return rm;
			}
			if (cp.getMemo1() != null && cp.getMemo1().equals("1") && tmp.getAudit_flg().equals("1")) {
				rm.setState("500");
				rm.setMsgInfo("项目已审核,请刷新重试!");
				return rm;
			}
			ccir.setAudit_time(curt_time);
			ccir.setAudit_man(curt_man);
			ccir.setAudit_flg(tmp.getAudit_flg().equals("0") ? "1" : "0");
			this.getMapper(CmCostItemResultMapper.class).update(ccir);

		}
		return rm;
	}
	
	
	/**
	 * 获取项目信息
	 * 
	 * @param data_origin A auto B Manual
	 * @return
	 */
	public ResultModel getDstItemInfo(String data_origin ) {
		ResultModel rm=new ResultModel();
		if (Utils.isEmpty(data_origin)) {
			data_origin = "B";
		}
		try {
			rm.setData(this.getMapper(BaseDstItemMapper.class)
					.findWithCondition(null, "DATA_ORIGIN = '"+data_origin+"'", "DST_ITEM_CODE", 0, 0));
			rm.setState("200");
		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("获取失败"+e.getMessage());
			e.printStackTrace();
		}
		return rm;
	}
	
	/**
	 * 分配项目实绩的导入功能
	 * @return
	 * @throws Exception
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doImportCmCostItemResult() 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(CmCostItemResultServiceImpl.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,amount;
					for (int i = 2; i <= numRow; i++) {
						//读取每行的数据
						Row row = sheet.getRow(i);
						org_name = ImportUtil.getCellValue(row.getCell(1));		//成本组织
						prd_num = ImportUtil.getCellValue(row.getCell(4)).substring(0, 6);		//成本期间											
						item_name = ImportUtil.getCellValue(row.getCell(5));	//成本项目
						amount = ImportUtil.getCellValue(row.getCell(7));		//金额
						//保存数据到分配项目实绩表
						CmCostItemResult cir = new CmCostItemResult();
						//成本项目
						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_dsc(bdi.getDst_item_dsc());
								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.setAmount_value("".equals(amount)?0:Double.valueOf(amount));
						cir.setMemo("分配项目实绩导入数据");
						cir.setValid_flg("1");
						cir.setAudit_flg("0");
						cir.setCreate_man(userName);
						cir.setCreate_time(now);
						this.getMapper(CmCostItemResultMapper.class).insert(cir);
					}
				}
			} catch (Exception e) {
				throw new Exception("Excel表格数据读取失败！" + e.getMessage());
			}
			rm.setState("200");
			rm.setMsgInfo("表格导入成功！");
			return rm; 
		} 	
	}

}
