package com.bjtdba.merchant.service.impl;

import at.favre.lib.crypto.bcrypt.BCrypt;
import com.bjtdba.entity.merchant.*;
import com.bjtdba.merchant.config.ResourceConfig;
import com.bjtdba.merchant.dao.*;
import com.bjtdba.merchant.entity.StoreStaff;
import com.bjtdba.merchant.entity.User;
import com.bjtdba.merchant.service.AdapayService;
import com.bjtdba.merchant.service.MerchantSettleInService;
import com.bjtdba.merchant.vo.Address;
import com.bjtdba.merchant.vo.MerchantAnnualCostOrderVo;
import com.bjtdba.utils.FileUtil;
import com.bjtdba.utils.QRCodeUtil;
import com.bjtdba.utils.ResponseUtil;
import com.bjtdba.utils.uploadDownload;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.model.MerConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

@Service
@Slf4j
public class MerchantSettleInServiceImpl implements MerchantSettleInService {

    @Autowired
    private MerchantAnnualCostOrderDao merchantAnnualCostOrderDao;

    @Autowired
    private MerchantIntentionDao merchantIntentionDao;

    @Autowired
    private SxySettlementBankOldDao sxySettlementBankOldDao;

    @Autowired
    private UserProvinceDao userProvinceDao;

    @Autowired
    private UserCityDao userCityDao;

    @Autowired
    private UserAreaDao userAreaDao;

    @Autowired
    private MerchantDao merchantDao;

    @Autowired
    private MerchantAdminDao merchantAdminDao;

    @Autowired
    private ResourceConfig resourceConfig;

    @Autowired
    private AdapayService adapayService;

    @Autowired
    private UserStreetDao userStreetDao;

    @Autowired
    private ActivationCodeDao activationCodeDao;

    @Autowired
    private SystemConfigValueDao systemConfigValueDao;

    @Autowired
    private StoreStaffDao storeStaffDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private HfbankcodeDao hfbankcodeDao;

    @Autowired
    private MerchantQrcodeDao merchantQrcodeDao;

    @Value("${huifu.urlWx}")
    private String urlWx;

    @Value("${huifu.urlWx2}")
    private String urlWx2;

    @Value("${huifu.urlAli}")
    private String urlAli;


    @Override
    public Object selectMerchant(String uid) throws ParseException {
        Map<String,Object> data=new HashMap<String,Object>();
        MerchantAnnualCostOrder merchantAnnualCostOrder=merchantAnnualCostOrderDao.selectMerchantAnnualCostOrderByMerId(uid);
        MerchantIntention merchantIntention=merchantIntentionDao.selectMerchantIntentionStstus(uid);
        int num=activationCodeDao.selectByuid(Integer.parseInt(uid)); //查询是否通过激活码支付
        if (null != merchantAnnualCostOrder || null != merchantIntention || num > 0) {//num大于0 激活码支付
            if(merchantIntention!=null){
                Merchant merchant= merchantDao.selectByUId(Integer.parseInt(uid));
                if("0".equals(merchantIntention.getStatus().toString())){
                    data.put("status",0);
                    data.put("msg","待审核");
                    if(num>0){
                        data.put("pay_type","2");
                    }
                    data.put("merId",merchant.getMer_id());
                } else if("1".equals(merchantIntention.getStatus().toString())){
                    data.put("status",1);
                    data.put("msg","审核通过");
                    if(num>0){
                        data.put("pay_type","2");
                    }
                    data.put("merId",merchant.getMer_id());
                } else if("2".equals(merchantIntention.getStatus().toString())){
                    data.put("status",2);
                    data.put("msg","拒绝");
                    if(num>0){
                        data.put("pay_type","2");
                    }
                    data.put("merId",merchant.getMer_id());
                } else if("3".equals(merchantIntention.getStatus().toString())){
                    if(merchant==null){
                        Integer merchantid = tianjia(uid);
                        data.put("merId",merchantid);
                    }else{
                        data.put("merId",merchant.getMer_id());
                    }
                    data.put("status",3);
                    data.put("msg","店铺申请");
                    data.put("pay_type","2");//邀请码支付
                }
                data.put("merchantAnnualCostOrder",merchantAnnualCostOrder);
                data.put("merchantIntention",merchantIntention);
            }else{
                if(num>0){
                    data.put("status",3);
                    data.put("merId",0);
                    data.put("pay_type","1");//正常支付
                    data.put("msg","未填写资料");
                }else{
                    data.put("status",4);
                    data.put("merId",0);
                    data.put("pay_type","1");//正常支付
                    data.put("msg","未填写资料");
                }
            }
        }else{
            //查询商户管理表，查看是否是管理员
            StoreStaff storeStaff = storeStaffDao.selectAdminUser(uid);
            if(storeStaff != null){
                data.put("pay_type",0);
                data.put("status",5);
                data.put("merId",storeStaff.getMerId());
                data.put("msg","管理员登录");
            }else{
                data.put("pay_type","0");//未支付
                data.put("status",-1);
                data.put("merId",0);
                data.put("msg","支付入驻金额");
            }
        }
        return ResponseUtil.ok(data);
    }

    @Override
    public Object insertMerchantSettlen(MerchantIntention merchantIntention) throws Exception {
        log.info("进入提交方法");
        Map<String,Object> data=new HashMap<String,Object>();
        merchantIntention.setStatus(0);
        List<Merchant> merchant= merchantDao.selectListByUId(merchantIntention.getUid());
        if(merchant==null||merchant.size()==0){
            Integer mer_id = insterMerchant(merchantIntention);//将数据存到店铺表中
            //生产二维码
            log.info("准备添加收款吗");
            insterQrCode(merchantIntention.getUid(),mer_id);
            merchantIntention.setMer_id(mer_id);
            boolean merchantAdmin = insterMerchantAdmin(merchantIntention);//将数据添加到店铺管理员表中
            //添加商户分类
            if(merchantAdmin){
                insterMerchantIntention(merchantIntention);//将店铺添加到店铺申请表中
                //我去查询二维码表如果没有绑定商户的话，我就绑定一下
                executeCreateHuiFuWx1(1,mer_id);//微信
                //executeCreateHuiFuAli(2,mer_id);//支付
            }else{
                return ResponseUtil.fail("数据填写错误");
            }
            return ResponseUtil.ok();
        }else{
            //
            return ResponseUtil.fail("重复提交数据");
        }
    }
    //微信1
    public void executeCreateHuiFuWx1(int payType,Integer mer_id)throws Exception{
        Adapay.debug = false;
        Adapay.prodMode = true;
        String apiKey = "";
        String rsaPrivateKey = "";
        String reaPublicKry= "";
        apiKey = resourceConfig.getWx_apikey_live();
        rsaPrivateKey = resourceConfig.getWx_rsaPrivateKey();
        reaPublicKry= resourceConfig.getWx_reaPublicKry();
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        merConfig.setRSAPublicKey(reaPublicKry);
        Adapay.initWithMerConfig(merConfig);
        MerchantIntention merchantIntention = merchantIntentionDao.selectMerchantIntentionByMerId(mer_id);
        String app_id = resourceConfig.getWx_app_id();
        if(merchantIntention.getType()==1) {
            //String url = resourceConfig.getUrlWx();
            adapayService.executeCreateCorpMember(app_id,merchantIntention,urlWx);//微信
        }else{
            adapayService.executeCreateMember(app_id,merchantIntention);//个人微信1
            executeCreateHuiFuWx2(payType,mer_id);
            //executeCreateHuiFuAli(payType,mer_id);
        }
    }
    //微信2------------------------------------------------------------------------------------------
    public void executeCreateHuiFuWx2(int payType,Integer mer_id)throws Exception{
        Adapay.debug = false;
        Adapay.prodMode = true;
        String apiKey = "";
        String rsaPrivateKey = "";
        String reaPublicKry= "";
        apiKey = resourceConfig.getWx2_apikey_live();
        rsaPrivateKey = resourceConfig.getWx2_rsaPrivateKey();
        reaPublicKry= resourceConfig.getWx2_reaPublicKry();
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        merConfig.setRSAPublicKey(reaPublicKry);
        Adapay.initWithMerConfig(merConfig);
        MerchantIntention merchantIntention = merchantIntentionDao.selectMerchantIntentionByMerId(mer_id);
        String app_id = resourceConfig.getWx2_app_id();
        if(merchantIntention.getType()==1) {
            //String url = resourceConfig.getUrlWx();
            adapayService.executeCreateCorpMember(app_id,merchantIntention,urlWx2);//微信
        }else{
            adapayService.executeCreateMember(app_id,merchantIntention);//个人微信1
            executeCreateHuiFuAli(payType,mer_id);
        }
    }
    //阿里---------------------------------------------------------------------------------------------------
    public void executeCreateHuiFuAli(int payType,Integer mer_id) throws Exception {
        Adapay.debug = true;
        Adapay.prodMode = true;
        String apiKey = "";
        String rsaPrivateKey = "";
        String reaPublicKry= "";
        apiKey = resourceConfig.getAli_apikey_live();
        rsaPrivateKey = resourceConfig.getAli_rsaPrivateKey();
        reaPublicKry= resourceConfig.getAli_reaPublicKry();
        MerConfig merConfig = new MerConfig();
        merConfig.setApiKey(apiKey);
        merConfig.setRSAPrivateKey(rsaPrivateKey);
        merConfig.setRSAPublicKey(reaPublicKry);
        Adapay.initWithMerConfig(merConfig);
        MerchantIntention merchantIntention = merchantIntentionDao.selectMerchantIntentionByMerId(mer_id);
        String app_id = resourceConfig.getAli_app_id();
        if(merchantIntention.getType()==1) {//个人还是企业   1企业
            //String url = resourceConfig.getUrlAli();
            adapayService.executeCreateCorpMember(app_id,merchantIntention,urlAli);//支付宝
        }else{
            adapayService.executeCreateMember(app_id,merchantIntention);//支付宝
        }
    }

    /**
     * 企业
     * 将数据添加到店铺表中
     * @return
     */
    private Integer insterMerchant(MerchantIntention merchantIntention) throws ParseException {
        Merchant merchant = new Merchant();
        merchant.setUid(merchantIntention.getUid());//uid
        merchant.setMer_name(merchantIntention.getMer_name());//商户名称
        merchant.setReal_name(merchantIntention.getName());//客户姓名
        merchant.setName(merchantIntention.getName());//客户姓名
        merchant.setMer_phone(merchantIntention.getPhone());//手机号
        //经纬度需要查库
        merchant.setCategory_id(Integer.parseInt(merchantIntention.getCate_id()));
        merchant.setMer_address(merchantIntention.getAddr());//地址
        merchant.setAddr(merchantIntention.getAddr());//详细地址
        merchant.setBusiness_license(merchantIntention.getBusiness_license());//营业执照
        merchant.setCard_positive_person(merchantIntention.getCard_positive_person());//身份证 正
        merchant.setCard_back_person(merchantIntention.getCard_back_person());//反
        merchant.setBank_account(merchantIntention.getBank_account());//开户账号
        merchant.setBank_location(merchantIntention.getBank_location());//开户所在地
        merchant.setBank_deposit(merchantIntention.getBank_deposit());////开户行
        merchant.setMer_avatar(merchantIntention.getLogo());
        merchant.setLogo(merchantIntention.getLogo());//logo
        merchant.setMer_info(merchantIntention.getMark());//简介
        merchant.setMerchant_type(3);
        merchant.setBusiness_addr(merchantIntention.getBusiness_addr());
        merchant.setProvince_id(merchantIntention.getProvince_id());
        merchant.setCity_id(merchantIntention.getCity_id());
        merchant.setArea_id(merchantIntention.getArea_id());
        merchant.setStreet_id(merchantIntention.getStreet_id());
        if(merchantIntention.getStreet_id()!=0){
            //经纬度需要查库
            Map<String,String> map = userStreetDao.selectStreetById(merchantIntention.getStreet_id());
            merchant.setLng(map.get("lng"));
            merchant.setLat(map.get("lat"));
        } else{
            merchant.setLng("0");
            merchant.setLat("0");
        }
        merchant.setType(merchantIntention.getType());//个人还是企业
        merchant.setEmail(merchantIntention.getEmail());//邮箱
        merchant.setOpen_account(merchantIntention.getOpen_account());//开户许可证
        LocalDate today = LocalDate.now();//今天日期
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);//一年后的日期
        LocalDateTime a1 = LocalDateTime.parse(nextYear+" 00:00:00", DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss"));
        Date form = Date.from(a1.atZone(ZoneId.systemDefault()).toInstant());
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = df.format(form);
        int times = (int) ((Timestamp.valueOf(time).getTime())/1000);
        System.out.println(times);
        merchant.setExpire_time(times);
        Merchant merchant1 = nullToString(merchant);
        int a = merchantDao.insterMerchant(merchant1);
        System.out.println(merchant.getMer_id());
        return merchant.getMer_id();
    }

    /**
     * 创建店铺相应的管理员   账号手机号   密码默认123456  php加密方式
     * @return
     */
    private boolean insterMerchantAdmin(MerchantIntention merchantIntention){

        MerchantAdmin merchantAdmin = new MerchantAdmin();
        merchantAdmin.setUid(merchantIntention.getUid());
        merchantAdmin.setMer_id(merchantIntention.getMer_id());
        User user = userDao.selectByUid(merchantIntention.getUid());
        merchantAdmin.setAccount(user.getPhone());

        merchantAdmin.setPwd(BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(10, "123456".toCharArray()));//默认密码123456
        merchantAdmin.setPhone(merchantIntention.getPhone());
        merchantAdmin.setReal_name(merchantIntention.getName());
        merchantAdmin.setLevel(0);
        int a = merchantAdminDao.insterMerchantAdmin(merchantAdmin);
        if(a==1){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 添加入住
     * @return
     */
    private boolean  insterMerchantIntention(MerchantIntention merchantIntention){
        MerchantIntention merchantIntention1 = nullToString(merchantIntention);
        int a = merchantIntentionDao.insterMerchantIntention(merchantIntention1);
        return true;
    }

    @Override
    public Object selectSettlementBank(String bank_name) {
        Map<String,Object> data=new HashMap<String,Object>();
        List<SxySettlementBankOld> sxySettlementBankOldList = hfbankcodeDao.selectSettlementBank(bank_name);
        data.put("sxySettlementBankOldList",sxySettlementBankOldList);
        return ResponseUtil.ok(sxySettlementBankOldList);
    }

    @Override
    public Object selectAddressList(int id,String code) {
        Map<String,Object> data=new HashMap<String,Object>();
        List<Address> addressList =addressList(id,code);
        data.put("addressList",addressList);
        return ResponseUtil.ok(data);
    }

    @Override
    public Object uploadPicture(MultipartFile file, String uid) {
        Map<String,Object> data=new HashMap<String,Object>();
        boolean fileSize = FileUtil.checkFileSize(file.getSize(), 50, "M");
        if(fileSize){
            Map<String, String> urlMap = uploadDownload.uploadImg(file, uid);
            data.put("urlMap",urlMap);
        }else{
            return ResponseUtil.fail("上传的图片太大，请上传50M以内");
        }
        return ResponseUtil.ok(data);
    }

    @Override
    public Object selectMerchaSettlen(String mer_id) {
        Map<String,Object> data=new HashMap<String,Object>();
        if(mer_id != null){
            MerchantIntention merchantIntention = merchantIntentionDao.selectMerchantIntentionByMerId(Integer.parseInt(mer_id));
            if(merchantIntention!=null&&merchantIntention.getProvince_id() != 0){
                merchantIntention.setProvinceMap(address(addressList(1,merchantIntention.getProvince_id().toString()),merchantIntention.getCity_id().toString()));
                merchantIntention.setCityMap(address(addressList(2,merchantIntention.getProvince_id().toString()),merchantIntention.getCity_id().toString()));
                merchantIntention.setAreaMap(address(addressList(3,merchantIntention.getCity_id().toString()),merchantIntention.getCity_id().toString()));
                merchantIntention.setStreetMap(address(addressList(4,merchantIntention.getArea_id().toString()),merchantIntention.getCity_id().toString()));
                data.put("merchantIntention",merchantIntention);
            }else{
                data.put("merchantIntention",merchantIntention);
                return ResponseUtil.ok(data);
            }
        }else{
            return ResponseUtil.fail("mer_id为空");
        }
        return ResponseUtil.ok(data);
    }

    /**
     * 循环地址
     * @param
     * @return
     */
    private Map<String,String> address( List<Address> list,String code){
        AtomicInteger index = new AtomicInteger();
        Map<String,String> map = new HashMap<>();
        Stream.iterate(0, i -> i + 1).limit(list.size()).forEach(i -> {
            if(list.get(i).getCode().equals(code)){
                index.set(i);
            }
        });
        map.put("index",index+"");
        map.put("name",list.get(Integer.parseInt(String.valueOf(index))).getName());
        return map;
    }

    @Override
    public Object updateMerchaSettlen(MerchantIntention merchantIntention) throws Exception {
        log.info("进入商户更新方法");
        merchantIntention.setStatus(0);
        //修改数据数据存到店铺表中
        boolean updateMerchant = updateMerchant(merchantIntention);
        //将数据添加到店铺管理员表中
        boolean updateMerchantAdmin = updateMerchantAdmin(merchantIntention);
        //将店铺添加到店铺申请表中
        int i = merchantIntentionDao.updateMerchantIntention(merchantIntention);
        if(i==1){
            //判断该商户是否有首款二维码，如果有不添加，如果没有就添加
            Map<String, String> map = merchantQrcodeDao.selectMerchantQrcodeByMerId(merchantIntention.getMer_id());
            if(map == null){
                log.info("准备添加收款吗");
                insterQrCode(merchantIntention.getUid(),merchantIntention.getMer_id());
            }
            executeCreateHuiFuWx1(1,merchantIntention.getMer_id());//微信
            //executeCreateHuiFuAli(2,merchantIntention.getMer_id());//支付   暂时不用
        }else{
            return ResponseUtil.fail("数据填写错误");
        }
        return ResponseUtil.ok();
    }
    private boolean updateMerchantAdmin(MerchantIntention merchantIntention){
        MerchantAdmin merchantAdmin = new MerchantAdmin();
        merchantAdmin.setUid(merchantIntention.getUid());
        merchantAdmin.setMer_id(merchantIntention.getMer_id());
        //merchantAdmin.setAccount(merchantIntention.getPhone());
        merchantAdmin.setPwd(BCrypt.with(BCrypt.Version.VERSION_2Y).hashToString(10, "123456".toCharArray()));//默认密码123456
        merchantAdmin.setPhone(merchantIntention.getPhone());
        merchantAdmin.setReal_name(merchantIntention.getName());
        int a = merchantAdminDao.updateMerchantAdmin(merchantAdmin);
        if(a==1){
            return true;
        }else{
            return false;
        }
    }
    private boolean updateMerchant(MerchantIntention merchantIntention){
        Merchant merchant = new Merchant();
        merchant.setUid(merchantIntention.getUid());//uid
        merchant.setMer_name(merchantIntention.getMer_name());//商户名称
        merchant.setReal_name(merchantIntention.getName());//客户姓名
        merchant.setName(merchantIntention.getName());//客户姓名
        merchant.setMer_phone(merchantIntention.getPhone());//手机号
        merchant.setCategory_id(Integer.parseInt(merchantIntention.getCate_id()));
        merchant.setMer_address(merchantIntention.getAddr());//地址
        merchant.setAddr(merchantIntention.getAddr());//详细地址
        merchant.setBusiness_license(merchantIntention.getBusiness_license());//营业执照
        merchant.setCard_positive_person(merchantIntention.getCard_positive_person());//身份证 正
        merchant.setCard_back_person(merchantIntention.getCard_back_person());//反
        merchant.setBank_account(merchantIntention.getBank_account());//开户账号
        merchant.setBank_location(merchantIntention.getBank_location());//开户所在地
        merchant.setBank_deposit(merchantIntention.getBank_deposit());////开户行
        merchant.setMer_avatar(merchantIntention.getLogo());
        merchant.setLogo(merchantIntention.getLogo());//logo
        merchant.setMer_info(merchantIntention.getMark());//简介
        merchant.setMerchant_type(3);
        merchant.setBusiness_addr(merchantIntention.getBusiness_addr());
        merchant.setProvince_id(merchantIntention.getProvince_id());
        merchant.setCity_id(merchantIntention.getCity_id());
        merchant.setArea_id(merchantIntention.getArea_id());
        merchant.setStreet_id(merchantIntention.getStreet_id());
        //经纬度需要查库
        Map<String,String> map = userStreetDao.selectStreetById(merchantIntention.getStreet_id());
        if(map==null){
             map = userAreaDao.selectAreaById(merchantIntention.getArea_id());
        }
        merchant.setLng(map.get("lng"));
        merchant.setLat(map.get("lat"));

        merchant.setType(merchantIntention.getType());//个人还是企业
        merchant.setEmail(merchantIntention.getEmail());//邮箱
        merchant.setOpen_account(merchantIntention.getOpen_account());//开户许可证
        merchant.setMer_id(merchantIntention.getMer_id());
        int a = merchantDao.updateMerchant(merchant);

        if(a==1){
            return true;
        }else{
            return false;
        }

    }

    @Override
    public Object updateActivationCode(String code,String uid) throws ParseException {
        Map<String,Object> data=new HashMap<String,Object>();
        //1、查询排查
        Integer number = activationCodeDao.selectByCode(code);
        if(number==1){
            int status = 3;
            int utime = (int) (new Date().getTime()/1000);
            int a = activationCodeDao.updateActivation(uid,code,status,utime);//修改数据  平切返回成功
            //再将数据添加到数据库中 merchant_intention
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
            MerchantIntention merchantIntention = new MerchantIntention();
            merchantIntention.setUid(Integer.parseInt(uid));
            merchantIntention.setStatus(3);
            merchantIntention.setActivation_code(code);
            merchantIntention.setProvince_id(0);
            merchantIntention.setCity_id(0);
            merchantIntention.setArea_id(0);
            merchantIntention.setStreet_id(0);
            merchantIntention.setType(0);
            merchantIntention.setCreate_time(new Date());
            merchantIntention.setMerc_start_time(df.format(new Date()));
            merchantIntention.setMerc_end_time(df.format(new Date()));
            merchantIntention.setCate_id("26");
            merchantIntention.setIdentification_valid_date_start(df.format(new Date()));
            merchantIntention.setIdentification_valid_date_end(df.format(new Date()));
            MerchantIntention merchantIntention1 = nullToString(merchantIntention);
            Integer merchantid = insterMerchant(merchantIntention1);
            merchantIntention1.setMer_id(merchantid);
            boolean merchantAdmin = insterMerchantAdmin(merchantIntention);//将数据添加到店铺管理员表中
            insterMerchantIntention(merchantIntention1);//添加
            data.put("mer_id",merchantid);
            data.put("pay_type","2");
            return ResponseUtil.ok(data);

        }else{
            return ResponseUtil.fail("邀请码错误");
        }
    }

    @Override
    public Object MerchantOrder(String uid){
        Map<String,Object> data=new HashMap<String,Object>();
        MerchantAnnualCostOrder merchantAnnualCostOrder1=merchantAnnualCostOrderDao.selectMerchantAnnualCostOrderByMerId(uid);//先判断该用户是否已经付钱了。反而不付钱
        if(merchantAnnualCostOrder1 == null){
            MerchantAnnualCostOrderVo merchantAnnualCostOrder = new MerchantAnnualCostOrderVo();
            merchantAnnualCostOrder.setMer_id(0);
            merchantAnnualCostOrder.setUid(Integer.parseInt(uid));
            merchantAnnualCostOrder.setStatus(0);
            merchantAnnualCostOrder.setOrder_no("annual"+System.currentTimeMillis());
            SystemConfigValue systemConfigValue = systemConfigValueDao.selectValue("annual");
            String a1 = systemConfigValue.getValue().replace("\"","");
            merchantAnnualCostOrder.setPay_price(new BigDecimal(Integer.parseInt(a1)));
            int a = merchantAnnualCostOrderDao.MerchantOrder(merchantAnnualCostOrder);
            data.put("id",merchantAnnualCostOrder.getId());
            return ResponseUtil.ok(data);
        }else{
            return ResponseUtil.fail("用户不可重复提交");
        }
    }

    public static <T> T nullToString(T cls) {
        Field[] fields = cls.getClass().getDeclaredFields();
        if (fields == null || fields.length == 0) {
            return cls;
        }
        for (Field field : fields) {
            if ("String".equals(field.getType().getSimpleName())) {
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (value == null) {
                        field.set(cls, "");
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }else if("Integer".equals(field.getType().getSimpleName())){
                field.setAccessible(true);
                try {
                    Object value = field.get(cls);
                    if (value == null) {
                        field.set(cls, 0);
                    }
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return cls;
    }

    /**
     * 地址
     * @param id
     * @param code
     * @return
     */
    private List<Address> addressList(int id,String code){
        List<Address> addressList =null;
        if(id==1){
            addressList = userProvinceDao.selectAddressList();
        }else if(id == 2){
            addressList = userCityDao.selectAddressList(code);
        }else if(id == 3){
            addressList = userAreaDao.selectAddressList(code);
        }else if(id == 4){
            addressList = userStreetDao.selectStreetList(code);
            if(addressList==null||addressList.size()==0){
                Address moren=new Address();
                moren.setCode("0000000000");
                moren.setId("0000000000");
                moren.setName("默认");
                addressList.add(moren);
            }
        }
        return addressList;
    }
    /**
     * 由于以前给了激活码，也激活了，没有办法登录的处理结果
     */
    private Integer tianjia(String uid) throws ParseException {
        //再将数据添加到数据库中 merchant_intention
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        MerchantIntention merchantIntention = new MerchantIntention();
        merchantIntention.setUid(Integer.parseInt(uid));
        merchantIntention.setStatus(3);
        merchantIntention.setActivation_code("");
        merchantIntention.setProvince_id(0);
        merchantIntention.setCity_id(0);
        merchantIntention.setArea_id(0);
        merchantIntention.setStreet_id(0);
        merchantIntention.setType(0);
        merchantIntention.setCreate_time(new Date());
        merchantIntention.setMerc_start_time(df.format(new Date()));
        merchantIntention.setMerc_end_time(df.format(new Date()));
        merchantIntention.setCate_id("26");
        merchantIntention.setIdentification_valid_date_start(df.format(new Date()));
        merchantIntention.setIdentification_valid_date_end(df.format(new Date()));
        MerchantIntention merchantIntention1 = nullToString(merchantIntention);
        Integer merchantid = insterMerchant(merchantIntention1);
        merchantIntention1.setMer_id(merchantid);
        boolean merchantAdmin = insterMerchantAdmin(merchantIntention);//将数据添加到店铺管理员表中
        merchantIntentionDao.updateMerIdByUid(uid,merchantid);//修改商户入驻表中的mer_id
        return merchantid;
    }
    @Value("${zhifu.url}")
    private String zhifuurl;
    /**
     * 生产二维码的方法
     */
    public boolean insterQrCode(int uid,int mer_id){
        /**
         * 1、生成时间戳   充当二维码的code以及名称
         * 2、将本地的二维码上传到远程数据库
         * 3、将二维码的地址以及uid、mer_id、code、二维码的url 保存到数据库中  与商户产生绑定
         * 3、将本的二维码删除
         */

        // 存放在二维码中的内容    http://app.bjtdba.com/offlinepay/index.html?id=164888564678229691#/
//        测试环境：https://offlinepay-test.bjtdba.com/mer_id=148


//        生产环境：https://offlinepay.bjtdba.com/mer_id=148
        log.info("已经进入生成收款方法");
        try {
            long timeNew = System.currentTimeMillis(); // 13位数的时间戳    这个也是code
            String text = zhifuurl + mer_id;
            // 嵌入二维码的图片路径
            String imgPath = "";
            // 生成的二维码的路径及名称
            String destPath = "/Users/hanyuxing/qrcode/" + timeNew + ".jpg";
            //生成二维码
            QRCodeUtil.encode(text, imgPath, destPath, true);
            // 解析二维码
            String str = QRCodeUtil.decode(destPath);
            // 打印出解析出的内容
            System.out.println(str);
            //上传二维码到c d n
            File file = new File(destPath);
            FileInputStream input = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input));
            Map<String, String> qrCode = uploadDownload.qrCode(multipartFile);
            log.info("上传到cdn服务 sQrcode_src="+qrCode.get("url")+"=== Show_src="+qrCode.get("url"));
            MerchantQrcode merchantQrcode = new MerchantQrcode();
            merchantQrcode.setUid(uid);
            merchantQrcode.setMer_id(mer_id);
            merchantQrcode.setCode_id("");
            merchantQrcode.setQrcode_src(qrCode.get("url"));
            merchantQrcode.setShow_src(qrCode.get("url"));
            merchantQrcodeDao.insterMerchantQrcode(merchantQrcode);
            deleteDir(new File("/Users/hanyuxing/qrcode"));
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }



    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();
    }
}




