package com.ym.mec.biz.service.impl;

import java.io.File;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ym.mec.biz.dal.config.AdapayNotifyConstants;
import com.ym.mec.biz.dal.dao.HfMemberDao;
import com.ym.mec.biz.dal.entity.HfMember;
import com.ym.mec.biz.service.HfMemberService;
import com.ym.mec.biz.service.HfMerchantConfigService;
import com.ym.mec.common.dal.BaseDAO;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.service.impl.BaseServiceImpl;
import com.ym.mec.thirdparty.adapay.CorpMemberService;
import com.ym.mec.thirdparty.adapay.SettleAccountService;
import com.ym.mec.thirdparty.adapay.entity.AccountInfo;
import com.ym.mec.thirdparty.adapay.entity.EnterpriseUser;
import com.ym.mec.thirdparty.adapay.entity.HfMerchantConfig;

@Service
public class HfMemberServiceImpl extends BaseServiceImpl<Integer, HfMember> implements HfMemberService {
	
    @Autowired
    private HfMemberDao hfMemberDao;
    
    @Autowired
    private SettleAccountService settleAccountService;
    
    @Autowired
    private CorpMemberService corpMemberService;
    
    @Autowired
    private HfMerchantConfigService hfMerchantConfigService;

    @Value("${spring.profiles.active:dev}")
    private String env;

	private String cardName;

    @Override
    public BaseDAO<Integer, HfMember> getDAO() {
        return hfMemberDao;
    }

    @Override
	public HfMember getByMemberId(String memberId) {
		return hfMemberDao.getByMemberId(memberId);
	}

	@Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createMember(HfMember member, File file) throws Exception {
        HfMember hasMember = hfMemberDao.getByMemberId(member.getMemberId());
        if (hasMember != null) {
            throw new BizException("商户号不能与已有商户相同，请核查");
        }
        hasMember = hfMemberDao.getByName(member.getName());
        if (hasMember != null) {
            throw new BizException("公司名与已有公司名相同，请核查");
        }
        
        Integer tenantId = member.getTenantId();
        
        HfMerchantConfig hfMerchantConfig = hfMerchantConfigService.queryByTenantId(tenantId);
        if(hfMerchantConfig == null){
        	throw new BizException("机构[{}]汇付商户信息找不到", tenantId);
        }
        
        EnterpriseUser enterpriseUser = new EnterpriseUser();
        enterpriseUser.setAddress(member.getAddress());
        enterpriseUser.setAreaCode(member.getAreaCode());
        enterpriseUser.setAttachFile(file);
        enterpriseUser.setBankAcctType(member.getBankAcctType());
        enterpriseUser.setBankCode(member.getBankCode());
        enterpriseUser.setBusinessScope(member.getBusinessScope());
        enterpriseUser.setCardName(member.getCardName());
        enterpriseUser.setCardNo(member.getCardNo());
        enterpriseUser.setLegalCertId(member.getLegalCertId());
        enterpriseUser.setLegalCertIdExpires(member.getLegalCertIdExpires());
        enterpriseUser.setLegalMp(member.getLegalMp());
        enterpriseUser.setLegalPerson(member.getLegalPerson());
        enterpriseUser.setMemberId(member.getMemberId());
        enterpriseUser.setName(member.getName());
        
        if(StringUtils.equals(env, "prod")){
            enterpriseUser.setNotifyUrl(AdapayNotifyConstants.corp_member_notify_url_prod);
        }else {
            enterpriseUser.setNotifyUrl(AdapayNotifyConstants.corp_member_notify_url_test);
        }
        enterpriseUser.setProvCode(member.getProvCode());
        enterpriseUser.setSocialCreditCode(member.getSocialCreditCode());
        enterpriseUser.setSocialCreditCodeExpires(member.getSocialCreditCodeExpires());
        
        corpMemberService.create(hfMerchantConfig.getMerKey(), hfMerchantConfig.getAppId(), enterpriseUser, enterpriseUser.getNotifyUrl());

        Date nowDate = new Date();
        member.setCreateTime(nowDate);
        member.setUpdateTime(nowDate);
        member.setStatus("pending");
        insert(member);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateMember(HfMember member, File file) throws Exception {
        HfMember hfMember = hfMemberDao.get(member.getId());
        if (hfMember == null) {
            throw new BizException("商户不存在请核对");
        }

        Integer tenantId = member.getTenantId();
        
        HfMerchantConfig hfMerchantConfig = hfMerchantConfigService.queryByTenantId(tenantId);
        if(hfMerchantConfig == null){
        	throw new BizException("机构[{}]汇付商户信息找不到", tenantId);
        }
        
        EnterpriseUser enterpriseUser = new EnterpriseUser();
        enterpriseUser.setAddress(member.getAddress());
        enterpriseUser.setAreaCode(member.getAreaCode());
        enterpriseUser.setAttachFile(file);
        enterpriseUser.setBankAcctType(member.getBankAcctType());
        enterpriseUser.setBankCode(member.getBankCode());
        enterpriseUser.setBusinessScope(member.getBusinessScope());
        enterpriseUser.setCardName(member.getCardName());
        enterpriseUser.setCardNo(member.getCardNo());
        enterpriseUser.setLegalCertId(member.getLegalCertId());
        enterpriseUser.setLegalCertIdExpires(member.getLegalCertIdExpires());
        enterpriseUser.setLegalMp(member.getLegalMp());
        enterpriseUser.setLegalPerson(member.getLegalPerson());
        enterpriseUser.setMemberId(member.getMemberId());
        enterpriseUser.setName(member.getName());
        
        if(StringUtils.equals(env, "prod")){
            enterpriseUser.setNotifyUrl(AdapayNotifyConstants.corp_member_notify_url_prod);
        }else {
            enterpriseUser.setNotifyUrl(AdapayNotifyConstants.corp_member_notify_url_test);
        }
        
        enterpriseUser.setProvCode(member.getProvCode());
        enterpriseUser.setSocialCreditCode(member.getSocialCreditCode());
        enterpriseUser.setSocialCreditCodeExpires(member.getSocialCreditCodeExpires());
        
        corpMemberService.update(hfMerchantConfig.getMerKey(), hfMerchantConfig.getAppId(), enterpriseUser, enterpriseUser.getNotifyUrl());

        Date nowDate = new Date();
        member.setUpdateTime(nowDate);
        member.setStatus("pending");
        if (update(member) <= 0) {
            throw new BizException("更新商户信息失败,请重试");
        }
        
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean mergeSettleAccount(String memberId, AccountInfo accountInfo) throws Exception {
        HfMember hfMember = hfMemberDao.getByMemberId(memberId);
        if (!hfMember.getStatus().equals("succeeded")) {
            throw new BizException("商户审核通过，才能绑定结算卡");
        }
        /*hfMember.setCardNo(accountInfo.getCardId());
        hfMember.setBankCode(accountInfo.getBankCode());
        hfMember.setBankAcctType(accountInfo.getBankAcctType());
        hfMember.setCardName(accountInfo.getCardName());*/
        
        accountInfo.setAreaCode(hfMember.getAreaCode());
        accountInfo.setBankAcctType(hfMember.getBankAcctType());
        accountInfo.setBankCode(hfMember.getBankCode());
        accountInfo.setBankName(hfMember.getBankCode());
        accountInfo.setCardId(hfMember.getCardNo());
        accountInfo.setCardName(hfMember.getCardName());
        accountInfo.setMemberId(memberId);
        accountInfo.setProvCode(hfMember.getProvCode());
        accountInfo.setTelNo(hfMember.getLegalMp());
        
        Integer tenantId = hfMember.getTenantId();
        
        HfMerchantConfig hfMerchantConfig = hfMerchantConfigService.queryByTenantId(tenantId);
        if(hfMerchantConfig == null){
        	throw new BizException("机构[{}]汇付商户信息找不到", tenantId);
        }

        //删除结算账户
        if (StringUtils.isNotBlank(hfMember.getSettleAccountId())) {
            settleAccountService.delete(hfMerchantConfig.getMerKey(), hfMerchantConfig.getAppId(), memberId, hfMember.getSettleAccountId());
        }

        //创建结算账户
        String settleAccountId = settleAccountService.create(hfMerchantConfig.getMerKey(), hfMerchantConfig.getAppId(), accountInfo);

        hfMember.setSettleAccountId(settleAccountId);
        if (hfMemberDao.update(hfMember) <= 0) {
            throw new BizException("绑卡失败，请重试");
        }
        return true;
    }
}
