/***文档注释***********************************************
 * 作者               :                   易鑫
 * 创建日期      :                   2017.10.24
 * 描述               :        			客户基本信息
 * 注意事项      :                   无
 * 遗留BUG :                   无
 * 修改日期      :                   
 * 修改人员      :                   
 * 修改内容      :                   
 ***********************************************************/
package market.Slm.CustomerInformation.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import market.Com.pb.PbMethod;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Slm.CustomerInformation.mapper.SlmCustomerInfoMapper;
import market.Slm.CustomerInformation.service.SlmCustomerInfoService;
import market.Slm.CustomerInformation.vo.NcCustomerInfo;
import market.Slm.CustomerInformation.vo.NcCustomerParam;
import market.Slm.CustomerInformation.vo.SlmCustomerInfo;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.mapper.UserMapper;
import com.hnshituo.core.auth.service.HomeService;
import com.hnshituo.core.auth.vo.User;

@RemoteService(path="SlmCustomerInfoService")
public class SlmCustomerInfoServiceImpl extends BaseServiceImpl<SlmCustomerInfo,Object> implements SlmCustomerInfoService {
	/**
	 * 查询数据
	 * @return
	 */
	public ResultModel doQueryWeb(CommonPage<SlmCustomerInfo> sum) {
		ResultModel rm=new ResultModel();
		int pageIndex=sum.getPageIndex();
		int pageSize=sum.getPageSize();
		try{
			PageModel<SlmCustomerInfo> pm = new PageModel<SlmCustomerInfo>(pageIndex,pageSize);
			SlmCustomerInfo sb=sum.getObject()==null?(new SlmCustomerInfo()):sum.getObject();
			String sWhere="";
			if(sb!=null&&!"".equals(sb.getCustomer_name())&&sb.getCustomer_name()!=null){
				sWhere=" (customer_name LIKE '%"+sb.getCustomer_name()+"%' or customer_abbr like '%"+sb.getCustomer_abbr()+"%')";
				sb.setCustomer_name(null);
				sb.setCustomer_abbr(null);
			}

			pm.setRows(this.getMapper(SlmCustomerInfoMapper.class).findWithCondition(sb, sWhere, " customer_name ", (pageIndex-1)*pageSize, pageSize));
			pm.setTotal(this.getMapper(SlmCustomerInfoMapper.class).countWithCondition(sb,sWhere));

			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}
	/**
	 * 查询数据
	 * 
	 * @return
	 */
	public ResultModel doQueryWeb2(CommonPage<SlmCustomerInfo> sum) {
		ResultModel rm = new ResultModel();
		int pageIndex = sum.getPageIndex();
		int pageSize = sum.getPageSize();
		PageModel<SlmCustomerInfo> pm = new PageModel<SlmCustomerInfo>(pageIndex, pageSize);
		SlmCustomerInfo sb = sum.getObject() == null ? (new SlmCustomerInfo()) : sum.getObject();
		String sWhere=" 1=1 ";
		try {
			if(sb.getCustomer_name()!=null&&!"".equals(sb.getCustomer_name())){
				sWhere="and  (customer_name LIKE '%"+sb.getCustomer_name()+"%' or customer_abbr like '%"+sb.getCustomer_name()
				+"%' or province_name like '%"+sb.getCustomer_name()+"%' or city_name like '%"+sb.getCustomer_name()+"%')";
				sb.setCustomer_name(null);
				sb.setCustomer_abbr(null);
				sb.setProvince_name(null);
				sb.setCity_name(null);
			}

			pm.setRows(this.getMapper(SlmCustomerInfoMapper.class).findWithCondition(sb, sWhere, " valid_flag desc,py,create_time  desc",(pageIndex - 1) * pageSize, pageSize));
			pm.setTotal(this.getMapper(SlmCustomerInfoMapper.class).countWithCondition(sb, sWhere));

			rm.setState("200");
			rm.setData(pm);
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("查询失败!" + ex.getMessage());
			ex.printStackTrace();
		}
		return rm;
	}

	/**
	 * 查看详情
	 * */
	public ResultModel doQueryDetailWeb(CommonPage<SlmCustomerInfo> sum){
		ResultModel rm=new ResultModel();
		try{
			rm.setState("200");
			rm.setData(this.getMapper(SlmCustomerInfoMapper.class).findById(sum.getObject().getCustomer_no()));
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败!");
			ex.printStackTrace();
		}
		return rm;
	}


	/**
	 * 添加数据
	 * 
	 * @param bd
	 * @return
	 * @throws Exception 
	 */
	@Transactional(value = "tm", rollbackFor = Exception.class)
	public ResultModel doAddWeb(CommonPage<SlmCustomerInfo> sum) throws Exception {
		ResultModel rm=new ResultModel();
		try {
			SlmCustomerInfo bd=sum.getObject();
			SlmCustomerInfo oci=new SlmCustomerInfo();
			oci.setCustomer_name(bd.getCustomer_name().trim());
			int icount=this.getMapper(SlmCustomerInfoMapper.class).count(oci);
			if(icount>0){
				rm.setState("500");
				rm.setMsgInfo("已存在相同的客户名称!");
				return rm;
			}

			String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
			String sNo=new SimpleDateFormat("yyyyMMdd").format(new Date());
			icount=this.getMapper(SlmCustomerInfoMapper.class).countWithCondition(null, " to_char(create_time,'yyyyMMdd')='"+sNo+"' ")+1;
			bd.setCustomer_no(sNo+String.format("%04d", icount));
			bd.setCreate_man_no(userId);
			bd.setCreate_man_name(userName);
			bd.setValid_flag("1");
			bd.setCreate_time(new Date());
			bd.setCustomer_name(bd.getCustomer_name().trim());
			//bd.setPy(PbMethod.ChineseSpell(bd.getCustomer_name()));

			this.getMapper(SlmCustomerInfoMapper.class).insert(bd);
			this.getBean(SlmCustomerObruInfoServiceImpl.class).doAddorUpdate(bd);
			rm.setState("200");

		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("服务端异常，新增失败!"+e.getMessage());
			e.printStackTrace();
			//--19-10-15添加异常回滚
			throw new Exception(rm.getMsgInfo());
		}
		return rm;
	}

	/**
	 * 修改数据
	 * @param bd
	 * @return
	 */
	public ResultModel doUpdateWeb(CommonPage<SlmCustomerInfo> sum) {
		ResultModel rm=new ResultModel();
		SlmCustomerInfo bd = sum.getObject();
		try {
			String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
			String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);

			SlmCustomerInfo sci=this.getMapper(SlmCustomerInfoMapper.class).findById(bd.getCustomer_no());
			if(sci!=null){
				if(!sci.getCustomer_name().equals(bd.getCustomer_name())){
					//验证客户名称
					SlmCustomerInfo oci=new SlmCustomerInfo();
					oci.setCustomer_name(bd.getCustomer_name());
					int icount=this.getMapper(SlmCustomerInfoMapper.class).count(oci);
					if(icount>0){
						rm.setState("500");
						rm.setMsgInfo("已存在相同的客户名称!");
						return rm;
					}
					//bd.setPy(PbMethod.ChineseSpell(bd.getCustomer_name()));
				}

				bd.setUpdate_man_no(userId);
				bd.setUpdate_man_name(userName);
				bd.setUpdate_time(new Date());
				this.getMapper(SlmCustomerInfoMapper.class).update(bd);
				this.getBean(SlmCustomerObruInfoServiceImpl.class).doAddorUpdate(bd);

				rm.setState("200");
			}else{
				rm.setState("500");
				rm.setMsgInfo("未找到客户数据!");
				return rm;
			}

		} catch (Exception e) {
			rm.setState("500");
			rm.setMsgInfo("修改失败!");
			e.printStackTrace();
		}
		return rm;
	}

	/**
	 * 启用、停用数据
	 * @param bd
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doUpdateFlagWeb(CommonPage<SlmCustomerInfo> sum) {
		ResultModel rm=new ResultModel();
		List<SlmCustomerInfo> obd = sum.getObjectList();
		String userId = (String) this.getSession().getAttribute(HomeService.SESSION_USER_ID);
		String userName = (String) this.getSession().getAttribute(HomeService.SESSION_USER_NAME);
		for(SlmCustomerInfo sci :obd){
			sci.setDelete_man_no(userId);
			sci.setDelete_man_name(userName);
			sci.setDelete_time(new Date());
			this.getMapper(SlmCustomerInfoMapper.class).update(sci);
			//修改其订结收用信息
//			if("0".equals(sci.getValid_flag())){		//置为无效
//				SlmCustomerObruInfo obru=new SlmCustomerObruInfo();
//				obru.setCustomer_no(sci.getCustomer_no());
//				List<SlmCustomerObruInfo> obruList=this.getMapper(SlmCustomerObruInfoMapper.class).find(obru, 0, 0);
//				for(SlmCustomerObruInfo obrus:obruList){
//					obrus.setValid_flag("0");
//					this.getMapper(SlmCustomerObruInfoMapper.class).update(obrus);
//				}
//			}
		}
		rm.setState("200");
		return rm;
	}


	/** ""
	 * for用友接口
	 * taxpayerid-- > 纳税人识别号  custsuptype-- > 客商类别， 1 代表客户， 2 代表供应商 code-- > NC客商编码 
	 * pk_cust_sup-- > NC客商主键 creatorname-- > 创建人 creationtime-- > 创建时间 name-- > 客商名称 
	 * pk_class-- > 客商基本分类名称 def20-- > 自定义项20（ NC系统中需要人员手工维护填写的MES系统对应的客商编码）
	 * */
	public static Logger log = Logger.getLogger(SlmCustomerInfoServiceImpl.class);
	public int i=1;
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel doSynchronizingCustomerInfo(NcCustomerParam pram){
		log.error("条数"+i);
		ResultModel rm=new ResultModel();
		List<NcCustomerInfo> list=pram.getList();
		try{
			for(NcCustomerInfo customer:list){
				i++;
				SlmCustomerInfo slm_customer=null;
				boolean have=true;
				if(customer.getPk_cust_sup()!=null)
					slm_customer=this.getMapper(SlmCustomerInfoMapper.class).findById(customer.getPk_cust_sup());
				if(slm_customer==null){
					String sWhere=" customer_name ='"+customer.getName()+"'";
					List<SlmCustomerInfo> customer_list=this.getMapper(SlmCustomerInfoMapper.class).findWithCondition(null, sWhere, null, 0, 0);
					if(customer_list.size()>0){		//如果已存在
						slm_customer=customer_list.get(0);
					}else{
						have=false;
					}
				}	

				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				if(have){			//mes中已存在该客户，则修改信息
					slm_customer.setCreate_man_name(customer.getCreatorname());
					slm_customer.setCreate_time(sdf.parse(customer.getCreationtime()));
					//纳税人识别号
//					if(customer.getTaxpayerid()!=null&&!"".equals(customer.getTaxpayerid())){
//						List<SlmCustomerAccount> account_list=this.getMapper(SlmCustomerAccountMapper.class).findWithCondition(null, " customer_no='"+slm_customer.getCustomer_no()+"'", null, 0, 0);
//						for(SlmCustomerAccount accounts:account_list){
//							accounts.setTax_registra_number(customer.getTaxpayerid());
//							this.getMapper(SlmCustomerAccountMapper.class).update(accounts);
//						}
//					}
					this.getMapper(SlmCustomerInfoMapper.class).update(slm_customer);
				}else{			//mes中不存在该客户，则新增
					slm_customer=new SlmCustomerInfo();
					slm_customer.setCustomer_name(customer.getName());
					//主键
					if(customer.getPk_cust_sup()!=null&&!"".equals(customer.getPk_cust_sup())){
						slm_customer.setCustomer_no(customer.getPk_cust_sup());
					}else{
						String sNo=new SimpleDateFormat("yyyyMMdd").format(new Date());
						int icount=this.getMapper(SlmCustomerInfoMapper.class).countWithCondition(null, " to_char(create_time,'yyyyMMdd')='"+sNo+"' ")+1;
						slm_customer.setCustomer_no(sNo+String.format("%04d", icount));
					}
					slm_customer.setCreate_man_no(customer.getCreatorname());
					List<User> user_list=this.getMapper(UserMapper.class).findWithCondition(null, " username='"+slm_customer.getCreate_man_no()+"'", null, 0, 0);
					if(user_list.size()>0){
						slm_customer.setCreate_man_no(user_list.get(0).getId());
					}
					slm_customer.setCreate_man_name(customer.getCreatorname());
					slm_customer.setValid_flag("1");
					slm_customer.setCreate_time(sdf.parse(customer.getCreationtime()));
					slm_customer.setPy(PbMethod.ChineseSpell(slm_customer.getCustomer_name()));
					slm_customer.setOrder_unit_flag("1");
					slm_customer.setReciver_unit_flag("1");
					slm_customer.setBalance_unit_flag("1");
					slm_customer.setUser_unit_flag("1");
					this.getMapper(SlmCustomerInfoMapper.class).insert(slm_customer);
					//订结收用
					this.getBean(SlmCustomerObruInfoServiceImpl.class).doAddorUpdate(slm_customer);
				}
				customer.setDef20(slm_customer.getCustomer_no());
			}
			rm.setState("200");
		}catch(Exception e){
			e.printStackTrace();
			rm.setState("500");
			rm.setMsgInfo(e.getMessage());
		}
		return rm;
	}
}
