package com.uas.eis.serviceImpl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.alibaba.fastjson.JSON;
import com.uas.eis.dao.BaseDao;
import com.uas.eis.service.YundingService;
import com.uas.eis.utils.BaseUtil;
import com.uas.eis.utils.SqlUtil;



@Service
public  class YundingServiceImpl implements YundingService  {
	@Autowired
	private BaseDao baseDao;
	
	
	/**
	 * 出入库单审核接口
	 * 
	 * @param id
	 * @param piclass
	 *            单据主表id
	 *            单据类型piclass
	 *            
	 */
	@Override
	public void  ProdInOutAuidted(int id,String piclass) {
		Map<Object, Object> store = new HashMap<Object, Object>();	
		//传入查询code、单据ID传回单据主从表信息Map
		if (piclass=="采购验收单"||piclass=="委外验收单"){
		//云顶插入采购/委外验收单接口
		}
		if (piclass=="采购验退单"||piclass=="委外验退单"){
			//云顶插入采购/委外验退单接口	
		}
		if (piclass=="拨出单"){
			//云顶插入拨出单接口	
		}
		if (piclass=="其他入库单"){
			//云顶插入其他入库单接口	
		}
		if (piclass=="其他出库单"){
			//云顶插入其他出库单接口	
		}
	}
	
	
	/**
	 * 出入库单云顶数据中心传UAS过账接口
	 * 
	 * @param Store
	 *            单据编号,类型等Json数据 Store
	 *            
	 */
	@Override
	public void  ProdInOutPOST(String Store) {



		com.alibaba.fastjson.JSONObject json = JSON.parseObject(Store);
		String Code=json.getString("xxxxxx").toString();
		String Piclass=json.getString("xxxxxx").toString();
		String res=null;
		baseDao.procedure("SP_GetCostPrice", new Object[] { Piclass, Code });
		res = baseDao.callProcedure("Sp_SplitProdOut",
				new Object[] { Piclass, Code, "ADMIN" });

		if (res != null && !res.trim().equals("")) {
			// 重新添加提示限制信息
			BaseUtil.showError(res + "  " +Piclass + Code + "，过账失败");
			// BaseUtil.showError(res);
		}
		res = baseDao.callProcedure("Sp_CommitProdInout",
				new Object[] { Piclass, Code, "ADMIN"});
		if (res != null && !res.trim().equals("")) {
			BaseUtil.showError(res);
		}
			
	}
	
	
	
	/**
	 * 销售订单云顶数据中心传UAS并生成一张已过账销售出货单接口
	 * 
	 * @param Store
	 *            销售订单主从表Json数据 Store
	 *            
	 */
	@Override
	public void  Salereceive(String Store) {
		//销售订单插入
		com.alibaba.fastjson.JSONObject json = JSON.parseObject(Store);
		String jsons =json.toString();
		List<Object[]> mappingList = baseDao.getFieldsDatasByCondition("xxx", new String[] { "TD_FROMFIELD", "TD_TOFIELD" }, "qu_id=1");
		Map<String, String> resultmap = new HashMap<String, String>();
		for(Object[] obj : mappingList){
			resultmap.put(String.valueOf(obj[0]), String.valueOf(obj[1]));
		}
		Map<String, Object> njson=BaseUtil.jsonToMap(jsons, resultmap);
		Map<Object, Object> store = (Map<Object, Object>) njson.get("stockout_list");
		store.put("sa_status", "已审核");
		store.put("sa_statuscode", "AUDITED");
		int id= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("dual", "sale_seq.nextval", "1=1")));
		store.put("sa_id", id);
		List<Map<Object, Object>> grid = (List<Map<Object, Object>>) njson.get("details_list");
		for (Map<Object, Object> map : grid) {
			map.put("sd_said", id);	
			map.put("sd_id", "saledetail_seq.nextval");
			}
		int count= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("Sale", "count(1)", "sa_code=" + store.get("order_no"))));
		if (count >0) {
			// 重新添加提示限制信息
			BaseUtil.showError(store.get("order_no")  + "编号已存在");
		}
		// 保存sale
		String formSql = SqlUtil.getInsertSqlByMap(store, "Sale");
		baseDao.execute(formSql);
		// 保存saleDetail
		List<String> gridSql = SqlUtil.getInsertSqlbyList(grid, "SaleDetail", "sd_id");
		baseDao.execute(gridSql);
		//调用生成出货单方法
		TurnProdIN(id);
		//过账生成的出货单
		String pi_inoutno= String.valueOf(baseDao.getFieldDataByCondition("ProdInOut", "pi_inoutno", "pi_sourcecoe="+store.get("order_no")));
		String res=null;
		baseDao.procedure("SP_GetCostPrice", new Object[] { "出货单", pi_inoutno });
		res = baseDao.callProcedure("Sp_SplitProdOut",
				new Object[] { "出货单", pi_inoutno, "ADMIN" });

		if (res != null && !res.trim().equals("")) {
			// 重新添加提示限制信息
			BaseUtil.showError(res + "  出货单"  + pi_inoutno + "，过账失败");
			// BaseUtil.showError(res);
		}
		res = baseDao.callProcedure("Sp_CommitProdInout",
				new Object[] { "出货单", pi_inoutno, "ADMIN"});
		if (res != null && !res.trim().equals("")) {
			BaseUtil.showError(res);
		}
	}
	
	
	
	
	
	/**
	 * 销售订单形成对应得出货单
	 * 
	 * @param id
	 *            单据类型id
	 *            
	 */
	@Override
	public void  TurnProdIN(int id) {
		String code=baseDao.callProcedure("Sp_GetMaxNumber", new Object[] { "ProdInOut!Sale", 2 });
		int pi_id= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("dual", "ProdInOut_seq.nextval", "1=1")));
		String contactSql = "insert into ProdInOut (pi_id,pi_inoutno,pi_recordman,pi_operatorcode,pi_recorddate,pi_invostatus,pi_invostatuscode,pi_class,pi_cardid,pi_cardcode,pi_title,pi_status,pi_statuscode,pi_updatedate,pi_updateman,pi_receivecode,pi_receivename,pi_arcode,pi_arname,pi_currency,pi_rate,pi_sellercode,pi_sellername,pi_address,pi_remark,pi_cusaddresssid,pi_paymentcode,pi_cop,pi_departmentcode,pi_departmentname,pi_transport,pi_payment,pi_printstatus,pi_printstatuscode,pi_chargeamount,pi_sourcecoe) "
						+ "select"+pi_id+","+code+",'admin','ADMIN',sysdate,'在录入','ENTERING','出货单',sa_custid,sa_custcode,sa_custname,'未过账','UNPOST',sysdate,'admin',sa_shcustcode,sa_shcustname,sa_apcustcode,sa_apcustname,sa_currency,sa_rate,sa_sellercode,sa_seller,sa_toplace,sa_remark,sa_cusaddresssid,sa_paymentscode,sa_cop,sa_departmentcode,sa_departmentname,sa_transport,sa_payments,'未打印','UNPRINT',sa_fare,sa_code from sale where sa_id="+id;
		baseDao.execute(contactSql);
		contactSql = "insert into ProdIODetail  (pd_id,pd_piid,pd_orderdetno,pd_ordercode,pd_prodcode,pd_sendprice,pd_outqty,pd_beipinoutqty,pd_pocode,pd_piclass,pd_status,pd_auditstatus,pd_taxrate,pd_sdid,pd_remark,pd_custprodcode,pd_custprodspec,pd_discount,pd_inqty,pd_custproddetail,pd_purcprice,pd_commissionrate,pd_whcode,pd_whname) "
				+ "select ProdIODetail_seq.nextval,"+pi_id+",sd_detno,sa_code,sd_prodcode,sd_price,sd_qty,sd_readyqty,sa_pocode,'出货单',0,'ENTERING',sd_taxrate,sd_id,sd_remark,sd_custprodcode,sd_prodcustcode,sd_discount,0,sd_custproddetail,sd_purcprice,sd_commissionrate,sd_whcode,sd_whcode from saledetail left join sale on sd_said=sa_id where sa_id="+id;
		baseDao.execute(contactSql);
		baseDao.execute("update Prodinout set (pi_whcode,pi_whname)=(select pd_whcode,pd_whname from ProdIODetail where pd_piid="
				+ pi_id + " and pd_pdno=1) where pi_id=" + pi_id + "");
		
		baseDao.execute(
				"update ProdInOut set pi_address=(select cu_add1 from customer where pi_cardcode=cu_code) where pi_id=? and nvl(pi_address,' ')=' '",
				pi_id);
		baseDao.execute("update prodinout set pi_purposename=((select max(ca_person) from CustomerAddress left join customer on ca_cuid=cu_id where cu_code=pi_cardcode and ca_address=pi_address))  where pi_purposename is null  and  pi_id="
				+ pi_id);
		baseDao.execute("update prodinout set pi_expresscode=((select max(ca_phone) from CustomerAddress left join customer on ca_cuid=cu_id where cu_code=pi_cardcode and ca_address=pi_address))  where pi_expresscode is null  and  pi_id="
				+ pi_id);
		baseDao.execute("update prodinout set pi_fax=((select max(ca_fax) from CustomerAddress left join customer on ca_cuid=cu_id where cu_code=pi_cardcode and ca_address=pi_address))  where pi_fax is null  and  pi_id="
				+ pi_id);
		baseDao.execute(
				"update ProdIODetail set pd_netprice=ROUND(pd_sendprice/(1 + pd_taxrate/ 100),6), pd_taxtotal=round(pd_sendprice*pd_outqty/(1+pd_taxrate/100),2), pd_ordertotal=round(pd_outqty*pd_sendprice,2) where pd_piid=?",
				pi_id);
		baseDao.execute(
				"update saleDetail set sdyqty=sd_qty where sd_said=?",
				id);
	}
	
	
	
	
	
	
	/**
	 * 销售退货单云顶数据中心传UAS并过账接口
	 * 
	 * @param Store
	 *            销售退货单主从表Json数据 Store
	 *            
	 */
	@Override
	public void  SaleReturn(String Store) {
		//销售退货单插入
		com.alibaba.fastjson.JSONObject json = JSON.parseObject(Store);
		String jsons =json.toString();
		List<Object[]> mappingList = baseDao.getFieldsDatasByCondition("xxx", new String[] { "TD_FROMFIELD", "TD_TOFIELD" }, "qu_id=1");
		Map<String, String> resultmap = new HashMap<String, String>();
		for(Object[] obj : mappingList){
			resultmap.put(String.valueOf(obj[0]), String.valueOf(obj[1]));
		}
		Map<String, Object> njson=BaseUtil.jsonToMap(jsons, resultmap);
		Map<Object, Object> store = (Map<Object, Object>) njson.get("date");
		store.put("pi_invostatus", "已审核");
		store.put("pi_invostatuscode", "AUDITED");
		int id= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("dual", "ProdInOut_seq.nextval", "1=1")));
		store.put("pi_id", id);
		List<Map<Object, Object>> grid = (List<Map<Object, Object>>) njson.get("refund_orders_list");
		for (Map<Object, Object> map : grid) {
			map.put("pd_piid", id);	
			map.put("pd_id", "ProdIODetail_seq.nextval");
			}
		int count= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("ProdInOut", "count(1)", "pi_inoutno=" + store.get("refund_no")+"and pi_class='销售退货单'")));
		if (count >0) {
			// 重新添加提示限制信息
			BaseUtil.showError(store.get("refund_no")  + "编号已存在");
		}
		// 保存ProdInOut
		String formSql = SqlUtil.getInsertSqlByMap(store, "ProdInOut");
		baseDao.execute(formSql);
		// 保存ProdIODetail
		List<String> gridSql = SqlUtil.getInsertSqlbyList(grid, "ProdIODetail", "pd_id");
		baseDao.execute(gridSql);
		//过账生成的退货单
		String res=null;
		baseDao.procedure("SP_GetCostPrice", new Object[] { "出货单", store.get("refund_no") });
		res = baseDao.callProcedure("Sp_SplitProdOut",
				new Object[] { "销售退货单", store.get("refund_no"), "ADMIN" });

		if (res != null && !res.trim().equals("")) {
			// 重新添加提示限制信息
			BaseUtil.showError(res + "  销售退货单"  + store.get("refund_no") + "，过账失败");
			// BaseUtil.showError(res);
		}
		res = baseDao.callProcedure("Sp_CommitProdInout",
				new Object[] { "销售退货单", store.get("refund_no"), "ADMIN"});
		if (res != null && !res.trim().equals("")) {
			BaseUtil.showError(res);
		}
	}
	
	
	/**
	 * 退货单云顶数据中心传UAS反过账接口
	 * 
	 * @param Store
	 *            单据编号,类型等Json数据 Store
	 *            
	 */
	@Override
	public void  SaleReturnDelete(String Store) {
		com.alibaba.fastjson.JSONObject json = JSON.parseObject(Store);
		String Code=json.getString("refund_no").toString();
		String Piclass="销售退货单";
		int piid= Integer.valueOf(String.valueOf(baseDao.getFieldDataByCondition("ProdInOut", "pi_id", "pi_inoutno=" + Code+"and pi_class="+Piclass)));
		String res=null;
		res= baseDao.callProcedure("Sp_UnCommitProdInout", Piclass,Code);
		if (res != null && !res.trim().equals("")) {
			BaseUtil.showError(res);
		}
		baseDao.updateByCondition("ProdInOut", "pi_statuscode='UNPOST',pi_status='未过账',pi_inoutman=null,pi_date1=null", "pi_id=" + piid);
		//删除反过账销售退货单
		baseDao.deleteByCondition("ProdIODetail", "pd_piid="+piid);
		baseDao.deleteByCondition("ProdInOut", "pi_id="+piid);
		}	
}
