/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2019-07-04
 * 描述            ：工模辅具价值表
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Cm.impl;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import market.Cm.mapper.CmReportGrossProfitDetailMapper;
import market.Cm.service.CmReportService;
import market.Cm.vo.CmReportGrossProfitDetail;
import market.Com.mapper.PbModelDbMapper;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.FundManagement.mapper.SlmFundSettleBillMapper;
import market.Slm.FundManagement.vo.SlmFundSettleBill;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

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

@RemoteService(path="CmReportService")
public class CmReportServiceImpl extends BaseServiceImpl<Object,Object> implements CmReportService {
	
	/**
	 * 销售毛利明细表
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryCmReportGrossProfitDetail(CommonPage<SlmFundSettleBill> cp) throws Exception{
		ResultModel rm  = new ResultModel();
		SlmFundSettleBill sfsb = cp.getObject();
		String startTime = cp.getStartTime();	//结算开始时间
		String endTime = cp.getEndTime();		//结算结束时间
		String condition = " and sfsb.flag in ('5', '6', '7')";
		if (StringUtils.isNotEmpty(sfsb.getContract_no().trim())) { 	//合同号
			condition += " and t.order_no like '%"+sfsb.getContract_no().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(sfsb.getMaterailcoilno().trim())) {	//原料卷号
			condition += " and t.materailcoilno like '%"+sfsb.getMaterailcoilno().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(sfsb.getSettle_bill_no().trim())) {	//结算单号
			condition += " and sfsb.settle_bill_no like '%"+sfsb.getSettle_bill_no().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(startTime)) {						//结算开始时间
			condition += " and to_char(sfsb.update_time, 'yyyy-MM-dd hh24:mi:ss') >= '"+startTime+"'";
		}
		if (StringUtils.isNotEmpty(endTime)) {							//结算结束时间
			condition += " and to_char(sfsb.update_time, 'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"'";
		}
		List<HashMap> hmList = this.getMapper(SlmFundSettleBillMapper.class).doQueryCmReportGrossProfitDetail(condition);
		rm.setData(hmList);
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 销售毛利明细表：红字开票查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryAddInvoiceDetail(CommonPage<SlmFundSettleBill> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime();	//结算开始时间
		String endTime = cp.getEndTime();		//结算结束时间
		if (StringUtils.isEmpty(startTime.trim()) || StringUtils.isEmpty(endTime.trim())) {
			throw new Exception("查询时间条件有误");
		}
		//获取所有红色开票的卷号
		String sql = "select t.settle_bill_no, slbd.bill_no, slbd.coilno,slbd.materailcoilno,slbd.factweight,"
				+ " soi.contract_no,soi.delivery_state_desc,cbci.parent_item_name,soi.steel_name "
				+ " from slm_fund_invoice_apply t "
				+ " left join slm_fund_settle_bill_line l on t.settle_bill_no = l.settle_bill_no "
				+ " left join slm_lading_bill_detail slbd on l.bill_no = slbd.bill_no "
				+ " left join slm_order_info soi on slbd.order_no = soi.contract_no||soi.contract_line_seq||soi.order_seq and nvl(soi.change_flag,'0')<>'1' "
				+ "	left join cm_base_item_cmp cbic on soi.steel_code = cbic.cmp_code "
				+ " left join cm_base_cost_item cbci on cbic.item_code = cbci.item_code"
				+ " where t.invoice_fund < 0 and t.valid_flag = '1' "
				+ " and t.create_time >= to_date('"+startTime+"','yyyy-MM-dd hh24:mi:ss') "
				+ " and t.create_time <= to_date('"+endTime+"','yyyy-MM-dd hh24:mi:ss')";
		List<HashMap> list = this.getMapper(SlmFundSettleBillMapper.class).doQueryAddDetail(sql);
		rm.setData(list);
		rm.setMsgInfo("查询成功");
		rm.setState("200");
		return rm;
	}
	
	/**
	 * 销售毛利明细表:月度查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryCmReportGrossProfitDetailHis(CommonPage<CmReportGrossProfitDetail> cp) throws Exception{
		ResultModel rm = new ResultModel();
		CmReportGrossProfitDetail crd = cp.getObject();
		String startTime = cp.getStartTime();	//结算开始时间
		String endTime = cp.getEndTime();		//结算结束时间
		String condition = " 1=1";
		if (StringUtils.isNotEmpty(crd.getContract_no().trim())) { 	//合同号
			condition += " and t.order_no like '%"+crd.getContract_no().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(crd.getMaterailcoilno().trim())) {	//原料卷号
			condition += " and t.materailcoilno like '%"+crd.getMaterailcoilno().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(crd.getSettle_bill_no().trim())) {	//结算单号
			condition += " and t.settle_bill_no like '%"+crd.getSettle_bill_no().trim()+"%'";
		}
		if (StringUtils.isNotEmpty(startTime)) {						//结算开始时间
			condition += " and t.set_time >= '"+startTime+"'";
		}
		if (StringUtils.isNotEmpty(endTime)) {							//结算结束时间
			condition += " and t.set_time <= '"+endTime+"'";
		}
		String sql = "select t.* from cm_report_gross_profit_detail t where "+condition + " order by t.input_type,t.parent_item_name,t.item_name,t.org_name,t.materailcoilno";
		List<HashMap> hmList = this.getMapper(PbModelDbMapper.class).doQueryHashMap(sql);
		rm.setState("200");
		rm.setData(hmList);
		return rm;
	}
	
	/**
	 * 销售毛利明细表：月度保存
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddCmReportGrossProfitDetail(CommonPage<SlmFundSettleBill> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		
		//判断是不是月初
		if (StringUtils.isEmpty(startTime) || !startTime.contains("-01 00:00:00")) {
			throw new Exception("月初时间有误，无法保存");
		}
		//判断是不是月末
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(endTime));
	  	calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
		if (calendar.get(Calendar.DAY_OF_MONTH) != 1) {
			throw new Exception("月末时间有误，无法保存");
	 	} 
	        
		String condition = " and sfsb.flag in ('5', '6', '7')";
		if (StringUtils.isNotEmpty(startTime)) {						//结算开始时间
			condition += " and to_char(sfsb.update_time, 'yyyy-MM-dd hh24:mi:ss') >= '"+startTime+"'";
		}
		if (StringUtils.isNotEmpty(endTime)) {							//结算结束时间
			condition += " and to_char(sfsb.update_time, 'yyyy-MM-dd hh24:mi:ss') <= '"+endTime+"'";
		}
		List<HashMap> hmList = this.getMapper(SlmFundSettleBillMapper.class).doQueryCmReportGrossProfitDetail(condition);
		if (CollectionUtils.isNotEmpty(hmList)) {
			for (HashMap hm : hmList) {
				CmReportGrossProfitDetail crd = new CmReportGrossProfitDetail();
				crd.setInput_type(hm.get("INPUT_TYPE")+"");
				crd.setParent_item_name(hm.get("PARENT_ITEM_NAME")+"");
				crd.setItem_name(hm.get("ITEM_NAME")+"");
				crd.setMaterailcoilno(hm.get("MATERAILCOILNO")+"");
				crd.setTrade_price(hm.get("TRADE_PRICE")==null?0d:Double.parseDouble(hm.get("TRADE_PRICE").toString()));
				crd.setProcess_price(hm.get("PROCESS_PRICE")==null?0d:Double.parseDouble(hm.get("PROCESS_PRICE").toString()));
				crd.setCarriage_price(hm.get("CARRIAGE_PRICE")==null?0d:Double.parseDouble(hm.get("CARRIAGE_PRICE").toString()));
				crd.setBalance_good_price(hm.get("BALANCE_GOOD_PRICE")==null?0d:Double.parseDouble(hm.get("BALANCE_GOOD_PRICE").toString()));
				crd.setBalance_price(hm.get("BALANCE_PRICE")==null?0d:Double.parseDouble(hm.get("BALANCE_PRICE").toString()));
				crd.setWeight(hm.get("WEIGHT")==null?0d:Double.parseDouble(hm.get("WEIGHT").toString()));
				crd.setAmount(hm.get("AMOUNT")==null?0d:Double.parseDouble(hm.get("AMOUNT").toString()));
				crd.setAmount_not(hm.get("AMOUNT_NOT")==null?0d:Double.parseDouble(hm.get("AMOUNT_NOT").toString()));
				crd.setPrice_value(hm.get("PRICE_VALUE")==null?0d:Double.parseDouble(hm.get("PRICE_VALUE").toString()));
				crd.setAmount_value(hm.get("AMOUNT_VALUE")==null?0d:Double.parseDouble(hm.get("AMOUNT_VALUE").toString()));
				crd.setGross_price(hm.get("GROSS_PRICE")==null?0d:Double.parseDouble(hm.get("GROSS_PRICE").toString()));
				crd.setOrg_name(hm.get("ORG_NAME")+"");
				crd.setCj_amount(hm.get("CJ_AMOUNT")==null?0d:Double.parseDouble(hm.get("CJ_AMOUNT").toString()));
				crd.setProcess(hm.get("PROCESS")+"");
				crd.setMat_weight(hm.get("MAT_WEIGHT")==null?0d:Double.parseDouble(hm.get("MAT_WEIGHT").toString()));
				crd.setOriginal_price(hm.get("ORIGINAL_PRICE")==null?0d:Double.parseDouble(hm.get("ORIGINAL_PRICE").toString()));
				crd.setJiagong_price(hm.get("JIAGONG_PRICE")==null?0d:Double.parseDouble(hm.get("JIAGONG_PRICE").toString()));
				crd.setCustomer_name(hm.get("CUSTOMER_NAME")+"");
				crd.setDelivery_state_desc(hm.get("DELIVERY_STATE_DESC")+"");
				crd.setOrder_no(hm.get("ORDER_NO")+"");
				crd.setContract_no(hm.get("CONTRACT_NO")+"");
				crd.setContract_time(hm.get("CONTRACT_TIME")+"");
				crd.setIn_date(hm.get("IN_DATE")+"");
				crd.setOutdate(hm.get("OUTDATE")+"");
				crd.setPrd_num(hm.get("PRD_NUM")+"");
				crd.setSet_time(hm.get("SET_TIME")+"");
				crd.setSettle_bill_no(hm.get("SETTLE_BILL_NO")+"");
				
				this.getMapper(CmReportGrossProfitDetailMapper.class).insert(crd);
			}
		}
		rm.setState("200");
		rm.setMsgInfo("月度保存成功");
		return rm;
	}
	
	/**
	 * 销售毛利明细表:月度删除
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	public ResultModel doDeleteCmReportGrossProfitDetail(CommonPage<SlmFundSettleBill> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime();
		String endTime = cp.getEndTime();
		//判断是不是月初
		if (StringUtils.isEmpty(startTime) || !startTime.contains("-01 00:00:00")) {
			throw new Exception("月初时间有误，无法保存");
		}
		//判断是不是月末
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(endTime));
	  	calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
		if (calendar.get(Calendar.DAY_OF_MONTH) != 1) {
			throw new Exception("月末时间有误，无法保存");
	 	}
		
		String sql = "delete from cm_report_gross_profit_detail t where 1=1"
				+ " and t.set_time >= '"+startTime+"'"
				+ " and t.set_time <= '"+endTime+"'";
		this.getMapper(PbModelDbMapper.class).doDeleteSql(sql);
		rm.setState("200");
		rm.setMsgInfo("删除月度信息成功");
		return rm;
	}
	
	/**
	 * 销售毛利明细表:库存导出查询
	 * @param cp
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public ResultModel doQueryYdmProductDetailHistory(CommonPage<SlmFundSettleBill> cp) throws Exception{
		ResultModel rm = new ResultModel();
		String startTime = cp.getStartTime();//格式：yyyy-MM-dd
		String sql = "select com_get_basename(t.storageattr) storageattr,com_get_basename(nvl(t.object_attr,ypd.object_attr)) object_attr,t.coilno,t.materailcoilno,ypd.machine_name,cbci.parent_item_name,cbci.item_name,t.factweight/1000 factweight"
				+ " from ydm_product_detail_history t "
				+ " left join ydm_product_detail ypd on t.coilno = ypd.coilno"
				+ " left join cm_base_item_cmp cbic on t.judgesteelcode = cbic.cmp_code "
				+ " left join cm_base_cost_item cbci on cbic.item_code = cbci.item_code"
				+ " where t.statdate = '"+startTime+"' and t.storageattr is not null"
				+ " order by t.storageattr,ypd.machine_name,cbci.parent_item_name,cbci.item_name";
		List<HashMap> hmList = this.getMapper(PbModelDbMapper.class).doQueryHashMap(sql);
		rm.setState("200");
		rm.setData(hmList);
		return rm;
	}
	
}
