package com.bjtdba.merchant.service.impl;

import com.alibaba.fastjson.JSON;
import com.bjtdba.entity.merchant.MerchantIntention;
import com.bjtdba.merchant.config.ResourceConfig;
import com.bjtdba.merchant.controller.StoreStaffController;
import com.bjtdba.merchant.dao.*;
import com.bjtdba.merchant.service.AdapayService;
import com.bjtdba.merchant.service.MerchantMemberService;
import com.bjtdba.utils.FileZipUtils;
import com.bjtdba.utils.uploadDownload;
import com.huifu.adapay.model.CorpMember;
import com.huifu.adapay.model.Member;
import com.huifu.adapay.model.SettleAccount;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdapayServiceImpl implements AdapayService {

    @Autowired
    private UserProvinceDao userProvinceDao;

    @Autowired
    private HfBusinessAddressDao hfBusinessAddressDao;

    @Autowired
    private UserCityDao userCityDao;

    @Autowired
    private ResourceConfig resourceConfig;

    @Autowired
    private MerchantDao merchantDao;

    @Autowired
    private MerchantIntentionDao merchantIntentionDao;

    @Autowired
    private HfUserOrderDao hfUserOrderDao;

    @Autowired
    private MerchantMemberService merchantMemberService;

    private  static final Logger log= (Logger) LoggerFactory.getLogger(StoreStaffController.class);

    /**
     * 个人穿件··创建用户
     */
    public void executeCreateMember(String app_id, MerchantIntention merchantIntention) throws Exception {
        System.out.println("=======execute CreateMember begin=======");
        Map<String, Object> memberParams = new HashMap<String, Object>(2);
        String member_id = "jsdk_member_"+System.currentTimeMillis();
        memberParams.put("member_id",member_id);
        memberParams.put("app_id",app_id);
        memberParams.put("gender", "MALE");
        memberParams.put("nickname", "nick_name");
        System.out.println("创建用户，请求参数：" + JSON.toJSONString(memberParams));
        Map<String, Object> member = Member.create(memberParams);
        if("succeeded".equals(member.get("status"))){
            //int status = 1;
            //判断返回值是微信还是支付宝
            log.info("个人提交成功"+JSON.toJSONString(member));
            executeCreateSettleAccount(app_id,member_id,merchantIntention);
        }else{
            //失败
            System.out.println("创建用户，返回参数：" + JSON.toJSONString(member));
            log.info("个人提交失败"+JSON.toJSONString(member));
            String check_result = member.get("error_msg").toString();
            int status = 2;
            merchantIntentionDao.updateResultByUid(check_result,status,merchantIntention.getUid());
        }
    }

    /**
     * 创建 settleCount
     *
     * @return 创建的settleCount 对象
     * @throws Exception 异常
     */
    public Map<String, Object> executeCreateSettleAccount(String app_id, String member_id,MerchantIntention merchantIntention) throws Exception {
        System.out.println("=======execute Create SettleAccount begin=======");
        Map<String, Object> settleCountParams = new HashMap<String, Object>(2);
        Map<String, Object> accountInfo = new HashMap<String, Object>(2);
        accountInfo.put("card_id", merchantIntention.getBank_account());
        accountInfo.put("card_name", merchantIntention.getName());
        accountInfo.put("cert_id", merchantIntention.getIdcard_no());
        accountInfo.put("cert_type", "00");
        accountInfo.put("tel_no", merchantIntention.getPhone());
        accountInfo.put("bank_acct_type", "2");
        settleCountParams.put("member_id", member_id);
        settleCountParams.put("app_id", app_id);
        settleCountParams.put("channel", "bank_account");
        settleCountParams.put("account_info", accountInfo);
        System.out.println("创建结算账户，请求参数：" + JSON.toJSONString(settleCountParams));
        Map<String, Object> settleCount = SettleAccount.create(settleCountParams);
        if("succeeded".equals(settleCount.get("status"))){
            log.info("个人结算账户提交成功"+JSON.toJSONString(settleCount));
            int status = 1;
            if(settleCount.get("app_id").equals(resourceConfig.getAli_app_id())) {//阿里
                String hf_member_id = settleCount.get("member_id").toString();//写到店铺表中
                merchantDao.updateHuiByUid(hf_member_id,null,merchantIntention.getUid());
                merchantIntentionDao.updateResultByUid("线下支付已授权",status,merchantIntention.getUid());
                merchantMemberService.insterMerchantMember(merchantIntention.getMer_id(),1,member_id,settleCount.get("id").toString());//保存商户支付id
            }else if(settleCount.get("app_id").equals(resourceConfig.getWx_app_id())){//微信1
                String hf_member_id_wx = settleCount.get("member_id").toString();//写到店铺表中
                merchantDao.updateHuiByUid(null,hf_member_id_wx,merchantIntention.getUid());
                merchantIntentionDao.updateResultByUid("线下支付已授权",status,merchantIntention.getUid());
                merchantMemberService.insterMerchantMember(merchantIntention.getMer_id(),2,member_id,settleCount.get("id").toString());//保存商户支付id
            }else if(settleCount.get("app_id").equals(resourceConfig.getWx2_app_id())){//微信2
                merchantMemberService.insterMerchantMember(merchantIntention.getMer_id(),3,member_id,settleCount.get("id").toString());//保存商户支付id
            }
        }else{
            log.info("个人结算账户提交失败"+JSON.toJSONString(settleCount));
            String check_result = settleCount.get("error_msg").toString();
            int status = 2;
            merchantIntentionDao.updateResultByUid(check_result,status,merchantIntention.getUid());
        }
        return settleCount;
    }

    /**
     * 企业创建用户
     * 给汇付准备提交的数据分为两部分，微信一部分，支付宝一部分，主要是app ID和key不一样
     */
    public void executeCreateCorpMember(String app_id,MerchantIntention merchantIntention,String url) throws Exception {
        String member_id = "";
        String order_no="";
        if(app_id.equals(resourceConfig.getAli_app_id())){
            order_no ="jsdk_order_ali" + System.currentTimeMillis();
            member_id = "jsdk_member_ali" + System.currentTimeMillis();
        }else if(app_id.equals(resourceConfig.getWx_app_id())){
            order_no = "jsdk_order_wx" + System.currentTimeMillis();
            member_id = "jsdk_member_wx" + System.currentTimeMillis();
        }else if(app_id.equals(resourceConfig.getWx2_app_id())){
            order_no = "jsdk_order_wx2" + System.currentTimeMillis();
            member_id = "jsdk_member_wx2" + System.currentTimeMillis();
        }
        Map<String, Object> memberParams = new HashMap<String, Object>(2);
        memberParams.put("order_no", order_no);
        memberParams.put("app_id", app_id);
        memberParams.put("member_id", member_id);
        memberParams.put("name", merchantIntention.getMer_name());//企业名称
        System.out.println(userProvinceDao.selectProvinceNameBycode(merchantIntention.getProvince_id()));
        System.out.println(hfBusinessAddressDao.selectCodeByAddress(userProvinceDao.selectProvinceNameBycode(merchantIntention.getProvince_id()),null));
        memberParams.put("prov_code",hfBusinessAddressDao.selectCodeByAddress(userProvinceDao.selectProvinceNameBycode(merchantIntention.getProvince_id()),null));
        memberParams.put("area_code", hfBusinessAddressDao.selectCodeByAddress(null,userCityDao.selectCityNameByCode(merchantIntention.getCity_id())));
        memberParams.put("social_credit_code", merchantIntention.getCredit_code());
        if(merchantIntention.getMerc_end_time().equals(merchantIntention.getMerc_start_time())){
            memberParams.put("social_credit_code_expires", "20991231");
        }else{
            memberParams.put("social_credit_code_expires", merchantIntention.getMerc_end_time().replaceAll("-", ""));
        }
        if (memberParams.get("social_credit_code_expires").toString().equals("20991231")) {
            memberParams.replace("social_credit_code_expires", "20991231");
        }
        memberParams.put("business_scope", "小商品");
        memberParams.put("legal_person", merchantIntention.getName());
        memberParams.put("legal_cert_id", merchantIntention.getIdcard_no());
        memberParams.put("legal_cert_id_expires", merchantIntention.getIdentification_valid_date_end().replaceAll("-", ""));
        memberParams.put("legal_mp", merchantIntention.getPhone());
        memberParams.put("address",merchantIntention.getAddr());
        memberParams.put("email", merchantIntention.getEmail());
        memberParams.put("bank_code",merchantIntention.getBank_name());//银行编码
        if("10A".equals(merchantIntention.getAcc_type())){
            memberParams.put("bank_acct_type", "1");
        }else{
            memberParams.put("bank_acct_type", "2");
        }
        memberParams.put("card_no", merchantIntention.getBank_account());
        memberParams.put("card_name", merchantIntention.getMer_name());//银行卡对应的企业名称
        memberParams.put("notify_url",url);
        String[] files = new String[]{merchantIntention.getBusiness_license().substring(23),merchantIntention.getCard_positive_person().substring(23),merchantIntention.getCard_back_person().substring(23),merchantIntention.getOpen_account().substring(23)};
        String pathName = uploadDownload.downloadImg(files, merchantIntention.getUid().toString());
        File file = new File("/Users/hanyuxing/"+merchantIntention.getUid()+".zip");
        FileOutputStream fos1 = new FileOutputStream(file);
        FileZipUtils.toZip1(pathName, fos1,false);
        //FileInputStream input = new FileInputStream(file);
        //MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
        //String zipUrl = uploadDownload.uploadZip(multipartFile, merchantIntention.getMer_id().toString());
        //File file1 = new File(zipUrl);//照片
        //String merchantKey = null;
        //测试
        log.info("企业提交的数据"+JSON.toJSONString(memberParams));
        Map<String, Object> member = CorpMember.create(memberParams, file);
        member.get("error_msg");
        delZipFile("/Users/hanyuxing/"+merchantIntention.getUid()+".zip");
        deleteDir(new File("/Users/hanyuxing/"+merchantIntention.getUid()));
        if("failed".equals(member.get("status"))){
            //失败
            log.info("创建用户，返回参数   失败：" + JSON.toJSONString(member));
            String check_result = member.get("error_msg").toString();
            int status = 2;
            merchantIntentionDao.updateResultByUid(check_result,status,merchantIntention.getUid());
        }else{
            memberParams.get("order_no");
            merchantIntention.getMer_id();
            log.info("企业提交成功"+JSON.toJSONString(member));
            //这个快需要吧状态设置成待审核0
            //merchantIntentionDao.updateResultByUid(null,0,merchantIntention.getUid());
            hfUserOrderDao.insterHf(memberParams.get("order_no").toString(),merchantIntention.getUid());
        }
        System.out.println(member);
    }

    // 删除解压后的文件

    private boolean deleteDir(File dir) {

        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0;i<children.length;i++){
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }
    // 目录此时为空，可以删除
    return dir.delete();
    }

    // 删除zip 文件

    public void delZipFile(String url) {
        File file = new File(url);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (f.getName().endsWith(".zip")) { // zip文件 判断 是否存在
                    if (f.delete()) {
                        log.info("zip文件已经删除");
                    } else {
                        log.info("zip文件删除失败");
                    }
                }
            }
        }
    }
}
