<?php
/**
 * @package benben_merchant
 *
 * @author xaboy
 * @day 2020-04-16
 *
 * 
 */

namespace app\common\repositories\merchant\apply;

use app\common\dao\merchant\apply\MerchantHaikeApplyDao;
use app\common\model\system\merchant\MerchantIntention;
use app\common\repositories\BaseRepository;
use app\common\repositories\merchant\order\OrderMerchantRepository;
use app\traits\HaikeApiRequest;
use crmeb\jobs\SendSmsJob;
use think\facade\Db;
use think\facade\Log;
use Lakala\src\LakalaBoss;
use Lakala\src\AES;
use think\facade\Queue;

/**
 * 海科商户入网业务申请
 * Class MerchantHaikeApplyRepository
 * @package app\common\repositories\merchant
 * @author php迷途小书童
 * @created 2021/1/28 14:28
 */
class MerchantHaikeApplyRepository extends BaseRepository
{
    use HaikeApiRequest;

    /**
     * MerchantRepository constructor.
     * @param MerchantHaikeApplyDao $dao
     */
    public function __construct(MerchantHaikeApplyDao $dao)
    {
        $this->dao = $dao;
    }
    /**
     * 获取单条订单信息
     * @return array|\think\Model|null
     * @author php迷途小书童
     * @created 2021/1/16 10:45
     */
    public function getOne(string $agent_apply_no)
    {
        $where = ['agent_apply_no' => $agent_apply_no];
        return ($this->dao->getWhere($where));
    }
    /**
     * 创建申请订单
     * @return mixed
     * @author php迷途小书童
     * @created 2021/1/16 14:57
     */
    public function createOrder(array $params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['code' => 500, 'msg' => '无申请信息'];
        $card_positive_person = parse_url($intention->card_positive_person, PHP_URL_PATH);//法人正面照
        Log::info('card_positive_person'.$card_positive_person);
        $card_back_person = parse_url($intention->card_back_person, PHP_URL_PATH);//法人反面照
        Log::info('card_back_person'.$card_back_person);
        $open_account = parse_url($intention->open_account, PHP_URL_PATH);//开户许可证
        Log::info('open_account'.$open_account);
        $business_premises1 = parse_url($intention->doorhead, PHP_URL_PATH);//门头照
        Log::info('doorhead'.$business_premises1);
        $business_premises2 = parse_url($intention->business_premises2, PHP_URL_PATH);//室内照1
        Log::info('business_premises2'.$business_premises2);
        $business_premises3 = parse_url($intention->business_premises3, PHP_URL_PATH);//室内照2
        Log::info('business_premises3'.$business_premises3);
        if (in_array($intention->type, [1,2])) {
            $business_license = parse_url($intention->business_license, PHP_URL_PATH);//营业执照
            Log::info('business_license'.$business_license);
            $business_license_base64 = $this->getThumb($business_license);
            $img_business_license = $this->uploadImg($business_license_base64)['image_id'];
        }
        if ($intention->type == 3) {
            $business_premises4 = parse_url($intention->business_premises4, PHP_URL_PATH);//小微入网图片
            Log::info('business_premises4'.$business_premises4);
            $business_premises4_base64 = $this->getThumb($business_premises4);
            $img_business_premises4 = $this->uploadImg($business_premises4_base64)['image_id'];
        }
        $card_positive_person_base64 = $this->getThumb($card_positive_person);
        $card_back_person_base64 = $this->getThumb($card_back_person);

        $open_account_base64 = $this->getThumb($open_account);
        $business_premises1_base64 = $this->getThumb($business_premises1);
        $business_premises2_base64 = $this->getThumb($business_premises2);
        $business_premises3_base64 = $this->getThumb($business_premises3);
        $img_card_positive_person = $this->uploadImg($card_positive_person_base64)['image_id'];
        $img_card_back_person = $this->uploadImg($card_back_person_base64)['image_id'];
        $img_open_account = $this->uploadImg($open_account_base64)['image_id'];

        $img_business_premises1 = $this->uploadImg($business_premises1_base64)['image_id'];
        $img_business_premises2 = $this->uploadImg($business_premises2_base64)['image_id'];
        $img_business_premises3 = $this->uploadImg($business_premises3_base64)['image_id'];
        $orderId = $this->getNewOrderId('MERAPPLY');
        $merchantApplyArray = [
            'acc_type' => $intention->acc_type,
            'type' => $intention->type,
            'agent_apply_no' => $orderId,
            'phone' => $intention->phone,
            'mer_name' => $intention->mer_name,
            'email' => $intention->email,
            'name' => $this->getNameById($intention->mer_intention_id),
            'card_positive_person' => $img_card_positive_person,
            'card_back_person' => $img_card_back_person,
            'legal_cert_no' => $intention->idcard_no,
            'haike_receive_flag' => (string)$intention->haike_receive_flag,
            'business_addr' => $intention->business_addr,
            'mer_short_name' => $intention->mer_short_name,
            'addr' => $intention->addr,
            'bank_account' => $intention->bank_account,
            'credit_code' => $intention->credit_code,
            'bank_branch' =>  $intention->bank_branch,
            'bank_code' => $this->getBankCode($intention->bank_branch),
            'idcard_no' => $intention->idcard_no,
            'province_code' => $this->getProvinceCode($intention->province_id),
            'city_code' => $this->getCityCode($intention->city_id),
            'area_code' => $this->getAreaCode($intention->area_id),
            'bank_province_code' => $this->getProvinceCode($intention->province_id),
            'bank_city_code' => $this->getCityCode($intention->city_id),
            'card_positive_bank' => $img_open_account,
            'business_premises1' => $img_business_premises1,
            'business_premises2' => $img_business_premises2,
            'business_premises3' => $img_business_premises3,
        ];
        $merchantApplyArray['is_again'] = $params['is_again'];
        if ($params['is_again'] > 0) {
            $merchantApplyArray['merch_no'] = $params['merch_no'];
        }
        if ($intention->type == 3) {
            $merchantApplyArray['business_premises4'] = $img_business_premises4;
        }
        if (in_array($intention->type, [1,2])) {
            $merchantApplyArray['credit_img'] = $img_business_license;
        }
        $response = $this->merchantApply($merchantApplyArray);
        Log::info($response);
        if ($response['return_code'] !== 10000) {
            return ['code' => 500, 'msg' => $response['return_msg']];
        }
        if ($params['is_again'] != 2) {
            $intention->merch_no = $merch_no = $response['merch_no'];
        }else {
            $response['merch_no'] = $merch_no = $intention->merch_no;
        }
        $intention->agent_apply_no = $orderId;
        $intention->save();

        $response = $this->merchantWithdrawalSetting([
            "merch_no"=> $response['merch_no'],
            "settlement_cycle" => $intention->acc_type == "10A" ? "T1" : "D1"
        ]);

        Log::info($response);
        $paramOrder = [
            'apply_id' => $intention->mer_intention_id ? : 0,
            'mer_id' => $intention->mer_id ? : 0,
            'uid' => $intention->uid,
            'merch_no' => $merch_no,
            'agent_apply_no' => $orderId,
            'trade_type' => 'WX,ALI',
            'platform' => 1,
            'apply_type' => 1,
        ];

        Db::transaction(function () use ($paramOrder) {
            $merchantOrder = $this->dao->create($paramOrder);
            return $merchantOrder;
        });

        return ['code' => 200, 'orderId' => $orderId];
    }

    /**
     * 创建申请订单lakala
     * @return mixed
     */
    public function createOrderlakala(array $params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['code' => 500, 'msg' => '无申请信息'];

        $datas=[
            "row"=> [
                "merchant_name"=>$intention->mer_name,//子商户名称
                "merchant_short_n1ame"=>$intention->mer_name,//子商户简称
                "merc_start_time"=>$intention->merc_start_time,
                "merc_end_time"=>$intention->merc_end_time,
                "reg_address"=> $intention->addr,//注册/经营地址
                "merchant_id_type"=> "00",//是否三证合一
                "merchant_id_no"=>$intention->credit_code ,//信用代码\营业执照号
                "province"=>$this->getProvinceCode($intention->province_id) ,//省份地址i
                "city"=>$this->getProvinceCode($intention->city_id) ,//省份地址i
                "region"=>$this->getAreaCode($intention->area_id),//省份地址i
                "mccCd"=>$intention->mcc_cd ,//行业大类
                "mccSubCd"=>$intention->mcc_sub_cd ,//行业细类
                "merc_attr"=>$intention->merc_attr ,//商户性质
                "min_rtn_amt"=>$intention->min_rtn_amt ,//最低留存金额 以分为单位
                "fee_charge_glg"=>$intention->fee_charge_glg,//分账手续费承担方式
                /// mercIdEffDt
            ],
            "illey"=>[
                "enterpriseOwner"=>$intention->name,
                "enterpriseOwnerIdType"=>"00",
                "enterpriseOwnerIdNo"=>$intention->idcard_no,
                "enterpriseOwnerIdEffDt"=>$intention->identification_valid_date_start,
                "enterpriseOwnerIdExpDt"=>$intention->identification_valid_date_end,
                "ownImg1"=>$intention->card_positive_person,
                "ownImg2"=>$intention->card_back_person,
            ],
            "son"=>[
                "usrOprNm"=>$intention->name,
                "usrOprEmail"=>$intention->email,
                "usrOprMbl"=>$intention->name,
            ],
            "link"=>[
                "contactType"=>"0",
                "contactName"=>$intention->name,
                "contactMobile"=>$intention->phone,
            ],
            "stu"=>[
                "bank_name"=>$intention->bank_name,
                "stl_bank_name"=>$intention->bank_deposit,
                "bank_no"=>$this->getBankCode($intention->bank_branch),
                "account_no"=>$intention->bank_account,
                "bank_prov"=>"",
                "bank_city"=>"",
                "pas_stl_flg"=>$intention->pas_stl_flg,
                "stl_beg_amt"=>$intention->stl_beg_amt,
            ],
        ];

        $res=$this->lakalaru($datas,$intention->mer_id);
        return $res;

//        $paramOrder = [
//            'apply_id' => $intention->mer_intention_id ? : 0,
//            'mer_id' => $intention->mer_id ? : 0,
//            'uid' => $intention->uid,
//            'merch_no' => $merch_no,
//            'agent_apply_no' => $orderId,
//            'trade_type' => 'WX,ALI',
//            'platform' => 1,
//            'apply_type' => 1,
//        ];
//
//        Db::transaction(function () use ($paramOrder) {
//            $merchantOrder = $this->dao->create($paramOrder);
//            return $merchantOrder;
//        });


    }
    /**
     * 拉卡拉入网
     * @param array $datas 商户数据
     * @param $mer_id   商户id
     * @data  2021-2-5
     */

    public function lakalaru($datas,$mer_id){
        $ids=$mer_id;
        $data = $datas["row"];
        $sonStore = $datas["illey"]; //子商户
        $sonManage = $datas["son"]; //子商户
        $sonLink = $datas["link"];//子商户联系方式
        $stu = $datas["stu"];//子商户结算信息开
        $password = substr(md5(time()),-16);
        $aes = AES::init();
        $lakalaBoss = LakalaBoss::getInstance();
        $params = [
            'reqTime' => date('YmdHis'),  //请求时间
            'merchantName' => $data['merchant_name'] ?? '', //子商户名称
            'merchantShortName' => $data['merchant_short_n1ame'] ?? '', //子商户简称
            'mercIdEffDt' => date("Ymd",strtotime($data['merc_start_time'])) ?? '', //营业执照生效日期
            'mercIdExpDt' => date("Ymd",strtotime($data['merc_end_time'])) ?? '',//'20260726', 营业执照到期日期
            'regAddress' => $data['reg_address'] ?? '',  //注册/经营地址
            'merchantIdType' => $data['merchant_id_type'], //是否三证合一
            'merchantIdNo' => $aes->encrypt($data['merchant_id_no'],$password), //信用代码\营业执照号
            'province' => $data['province'] ?? '',//归属省
            'city' => $data['city'] ?? '', //归属市
            'region' => $data['region'] ?? '', //归属地区
            'mccCd' => $data['mcc_cd'] ?? '',  //行业大类
            'mccSubCd' => $data['mcc_sub_cd'] ?? '', //行业细类
            'mercAttr' => (string)$data['merc_attr'] ?? '',//商户性质
            'administrator' => stripslashes(json_encode([  //子商户管理员信息开始
                [
                    'usrOprNm' => $sonManage['usrOprNm'],  //子商户管理员姓名
                    'usrOprMbl' => $aes->encrypt($sonManage['usrOprNm'],$password), //子商户管理员姓名
                    'usrOprEmail' => $sonManage['usrOprEmail'],  //子商户管理员Email
                    'mercCertTyp' => '1-RSA',  //子商户接口类型
                ]
            ],JSON_UNESCAPED_UNICODE)),
            'contact' => stripslashes(json_encode([  //子商户联系人信息开始
                [
                    'contactType' => $sonLink['contactType'],  // 3 紧急联系人
                    'contactName' => $sonLink['contactName'],  //子商户联系人姓名
                    'contactMobile' => $aes->encrypt($sonLink['contactMobile'],$password),  //子商户联系人手机
                ]
            ],JSON_UNESCAPED_UNICODE)),
            'owner' => stripslashes(json_encode([  //子商户法人信息
                [
                    'enterpriseOwner' => $sonStore['enterpriseOwner'], //子商户法人姓名
                    'enterpriseOwnerIdType' => $sonStore['enterpriseOwnerIdType'],  //子商户法人证件类型 00:身份证
                    'enterpriseOwnerIdNo' => $aes->encrypt($sonStore['enterpriseOwnerIdNo'],$password),//子商户法人证件号码
                    'enterpriseOwnerIdEffDt' => $sonStore['enterpriseOwnerIdEffDt'], //子商户法人证件生效日期
                    'enterpriseOwnerIdExpDt' => $sonStore['enterpriseOwnerIdExpDt'],  //子商户法人证件失效日期
                    'ownImg1' =>$sonStore['ownImg1'],//$sonStore['ownImg1'] ? explode("/",$sonStore['ownImg1'])[3]:"",//子商户法人证件照片正面
                    'othImg2' =>$sonStore['ownImg2'],//$sonStore['othImg2'] ?  explode("/",$sonStore['othImg2'])[3] : "",//子商户法人证件照片反面
                ]
            ],JSON_UNESCAPED_UNICODE)),
            'stlLst' => stripslashes(json_encode([  //结算信息
                [
                    'stlSign' => '0',  //结算账号公私标志 0-对公
                    'selfStlFlg' => 'Y', //商户自结算标志 N-不允许 Y-允许
                    'bankName' => $stu['bank_name'] ?? '',  //银行代码
                    'stlBankName' => $stu['stl_bank_name'] ?? '',//开户行名称
                    'lBnkNo' => $stu['bank_no'] ?? '',//联行行号
                    'stlOac' => $aes->encrypt($stu['account_no'],$password),//$stu['account_no'] //银行帐号
                    'bnkOpnName' => $stu['stl_bank_name'] ?? '', //银行开户名称
                    'opnBnkProv' => $stu['bank_prov'] ?? '', //支行归属省
                    'opnBnkCity' => $stu['bank_city'] ?? '', //支行归属市
                    'stlCls' => '1',//$stu['st_class'], //商户结算类型  1-结算到账户2-结算到银行账户

                    'stlPerd' => '0',//$stu['stl_perd'], //结算周期0-日 1-周2-旬3-月4-季5-半年6-年7-指定结算日

                    'pasStlFlg' => $stu['pas_stl_flg'], //暂停结算标志 0-正常结算  1-暂停结算

                    'minRtnAmt' => $data['min_rtn_amt'], //最低留存金额 以分为单位
                    'stlTrfDays' => '1',//$stu['stl_trf_days'],  //结算划款天数
                    'stlDay' => "1",  //结算日当结算周日为7时必填
                    'nextStlDt' => date('Ymd'), //下一结算日期
                    'stlBegAmt' => $stu['stl_beg_amt'], //结算起始金额
                ]

            ],JSON_UNESCAPED_UNICODE)),
            'feeChargeFlg' => $data['fee_charge_glg'],  //分账手续费承担方式
            'certPhotoImg' => "photoimg.jpg",// $data['cert_photo_image'] ? explode("/",$data['cert_photo_image'])[3] : "",  //证照照片
            'secretKey' =>$lakalaBoss->signencrypt($password),  //临时密钥
        ];
        //查看是否存在商户id值
        $isMerc = Db::name("merchant")->where(['mer_id'=>$ids])->find();
        if($isMerc['mer_id']){
            $params['outMerchantId'] = $isMerc['mer_id'];
            $result = $lakalaBoss->editStore($params);
            if($result['code'] != 0){
                return app('json')->fail($result['message']);
            }
            if($result['data']['status'] == 'S'){
                $updateArr = [
                    'mer_id' => $ids,
                    'send_data' => json_encode($params),
                    'result_data' => json_encode($result),
                    "update_time" => time(),
                ];
                Db::name("merchant_extend")->where(['mer_id'=>$ids])->update($updateArr);
//                return app('json')->success($result['message']);
                return ['code' => 200, 'message' => $result['message']];
            }
        }else{

            $result = $lakalaBoss->registerStore($params);
            return $result;
            if($result['code'] != 0){
//                $this->error($result['message']);
//                return app('json')->fail($result['message']);
                return ['code' => 400, 'message' => $result['message']];
            }

            if($result['data']['status'] == 'S'){
                //更新信息到数据库
                $rs  = Db::name("merchant_intention")->where(['mer_id'=>$ids])->update(['mer_id'=>$result['data']['outMerchantId'],'request_id'=>$result['data']['requestId']]);
                $insertArr = [
                    'mer_id' => $ids,
                    'send_data' => json_encode($params),
                    'result_data' => json_encode($result),
                    "update_time" => time(),
                    "create_time" => time(),
                ];
                Db::name("merchant_extend")->insert($insertArr);
                if($rs){
                    //对图片进行压缩文件
                    // system();
                    /**
                     * 子商户号
                     * 最终图片路径
                     */
                    // self::upload_img($result['data']['outMerchantId'],'');
                    return ['code' => 200, 'message' => "操作成功"];
                }
                return ['code' => 400, 'message' => "网络繁忙,请稍后进行操作！"];
            }else{
                return ['code' => 400, 'message' => $result['message']];
            }
        }
    }


    public function getNameById($id)
    {
        return Db::name('merchant_intention')->where('mer_intention_id', $id)->value('name');
    }
    public function getBankCode($branch)
    {
        return Db::name('bank_code')->where('bank_branch', $branch)->value('bank_code');
    }
    public function getProvinceCode($province_id)
    {
        return Db::name('user_province')->where('province_id', $province_id)->value('province_code');
    }
    public function getCityCode($city_id)
    {
        return Db::name('user_city')->where('city_id', $city_id)->value('city_code');
    }
    public function getAreaCode($area_id)
    {
        return Db::name('user_area')->where('area_id', $area_id)->value('area_code');
    }
    /**
     * 获取唯一订单号
     * @return string
     * @author php迷途小书童
     * @created 2021/1/16 14:57
     */
    public function getNewOrderId($trade_type)
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = $trade_type . $msectime . mt_rand(10000, max(intval($msec * 10000) + 10000, 98369));
        return $orderId;
    }
    /**
     * 微信业务申请
     * @author php迷途小书童
     * @created 2021/2/3 15:57
     */
    public function haikeWxApply($params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['return_code' => 500, 'return_msg' => '申请信息不存在'];
        if (!$intention->merch_no)
            return ['return_code' => 500, 'return_msg' => '请先发起入网'];
        if (!$intention->haike_wx_appid)
            return ['return_code' => 500, 'return_msg' => '请先配置微信公众号APPID'];

        $authApply = $this->dao->getWhere(['apply_id' => $intention->mer_intention_id,'trade_type' => 'WXAPPLY']);
        if ($authApply)
            $this->dao->delete($authApply->id);

        $orderId = $this->getNewOrderId('WXAPPLY');
        $paramOrder = [
            'apply_id' => $intention->mer_intention_id ? : 0,
            'mer_id' => $intention->mer_id ? : 0,
            'mer_name' => $intention->mer_name,
            'uid' => $intention->uid,
            'phone' => $intention->phone,
            'merch_no' => $intention->merch_no,
            'agent_apply_no' => $orderId,
            'trade_type' => 'WXAPPLY',
            'platform' => 1,
            'apply_type' => 2,
        ];
        $this->createApplyOrder($paramOrder);
        //刷卡手续费比例
        $souxufee = systemConfig('yanglao');
        $rate = bcmul($souxufee,100);
        $paramOrder = [
            'merch_no' => $intention->merch_no,
            'agent_apply_no' => $orderId,
            'apply_notice' => env('APP_URL')."/api/merchant/apply_notice",
            'haike_wx_type' => (string)$intention->haike_wx_type,
            'rate' => (string)$rate,
        ];
        $response = $this->wxApply($paramOrder);

        if ($response['return_code'] !== 10000) {
            return ['return_code' => 500, 'return_msg' => $response['return_msg']];
        }
        $intention->haike_wx_status = 1;
        $intention->save();
        return ['return_code' => 200, 'return_msg' => '发起成功'];
    }
    /**
     * 微信公众号配置
     * @author php迷途小书童
     * @created 2021/2/3 15:57
     */
    public function haikeWxAppidConfAdd($params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['return_code' => 500, 'return_msg' => '申请信息不存在'];
        if (!$intention->merch_no)
            return ['return_code' => 500, 'return_msg' => '请先发起入网'];
        if (!$intention->haike_wx_appid)
            return ['return_code' => 500, 'return_msg' => '请先配置微信公众号APPID'];
        $paramOrder = [
            'merch_no' => $intention->merch_no,
            'wx_appid' => $intention->haike_wx_appid,
        ];
        $response = $this->wxAppidConfAdd($paramOrder);

        if ($response['return_code'] !== 10000) {
            return ['return_code' => 500, 'return_msg' => '未知错误'];
        }
        if ($response['result'] === "0") {
            $intention->haike_wx_appid_status = 1;
            $intention->save();
            return ['return_code' => 200, 'return_msg' => $response['msg']];
        } else {
            return ['return_code' => 500, 'return_msg' => $response['msg']];
        }
    }
    /**
     * 微信业务二次认证
     * @author php迷途小书童
     * @created 2021/2/3 15:57
     */
    public function haikeWxAuthApply($params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['code' => 500, 'msg' => '申请信息不存在'];
        if (!$intention->merch_no)
            return ['code' => 500, 'msg' => '请先发起入网'];
        $infoResponse = $this->merchantInfo(['merch_no' => $intention->merch_no]);
        if ($infoResponse['return_code'] !== 10000)
            return ['code' => 500, 'msg' => $infoResponse['return_msg']];
        $wxsub_merch_no = $infoResponse['wx_biz_info']['wxsub_merch_no'];
        $intention->haike_wxsub_merch_no = $wxsub_merch_no;
        $save = $intention->save();
        if (!$save)
            return ['code' => 500, 'msg' => '更新微信子商户号失败'];
        $card_positive_person = parse_url($intention->card_positive_person, PHP_URL_PATH);//法人正面照
        Log::info('card_positive_person'.$card_positive_person);
        $card_back_person = parse_url($intention->card_back_person, PHP_URL_PATH);//法人反面照
        Log::info('card_back_person'.$card_back_person);
        $business_license = parse_url($intention->business_license, PHP_URL_PATH);//营业执照
        Log::info('business_license'.$business_license);
        $open_account = parse_url($intention->open_account, PHP_URL_PATH);//开户许可证
        Log::info('open_account'.$open_account);
        $business_premises1 = parse_url($intention->doorhead, PHP_URL_PATH);//门头照
        Log::info('doorhead'.$business_premises1);
        $business_premises2 = parse_url($intention->business_premises2, PHP_URL_PATH);//室内照1
        Log::info('business_premises2'.$business_premises2);
        $card_positive_person_base64 = $this->getThumb($card_positive_person);
        $card_back_person_base64 = $this->getThumb($card_back_person);
        $business_license_base64 = $this->getThumb($business_license);
        $open_account_base64 = $this->getThumb($open_account);
        $business_premises1_base64 = $this->getThumb($business_premises1);
        $business_premises2_base64 = $this->getThumb($business_premises2);
        $img_card_positive_person = $this->uploadImg($card_positive_person_base64)['image_id'];
        $img_card_back_person = $this->uploadImg($card_back_person_base64)['image_id'];
        $img_open_account = $this->uploadImg($open_account_base64)['image_id'];
        $img_business_license = $this->uploadImg($business_license_base64)['image_id'];
        $img_business_premises1 = $this->uploadImg($business_premises1_base64)['image_id'];
        $img_business_premises2 = $this->uploadImg($business_premises2_base64)['image_id'];
        $orderId = $this->getNewOrderId('WXAUTHAPPLY');
        $authApplyArray = [
            'acc_type' => $intention->acc_type,
            'type' => $intention->type,
            'agent_apply_no' => $orderId,
            'phone' => $intention->phone,
            'mer_name' => $intention->mer_name,
            'email' => $intention->email,
            'name' => $this->getNameById($intention->mer_intention_id),
            'card_positive_person' => $img_card_positive_person,
            'card_back_person' => $img_card_back_person,
            'identification_valid_date_start' => $intention->identification_valid_date_start,
            'identification_valid_date_end' => $intention->identification_valid_date_end,
            'legal_cert_no' => $intention->idcard_no,
            'business_addr' => $intention->business_addr,
            'mer_short_name' => $intention->mer_short_name,
            'addr' => $intention->addr,
            'bank_account' => $intention->bank_account,
            'credit_code' => $intention->credit_code,
            'bank_branch' =>  $intention->bank_branch,
            'bank_code' => $this->getBankCode($intention->bank_branch),
            'idcard_no' => $intention->idcard_no,
            'province_code' => $this->getProvinceCode($intention->province_id),
            'city_code' => $this->getCityCode($intention->city_id),
            'area_code' => $this->getAreaCode($intention->area_id),
            'bank_province_code' => $this->getProvinceCode($intention->province_id),
            'bank_city_code' => $this->getCityCode($intention->city_id),
            'credit_img' => $img_business_license,
            'card_positive_bank' => $img_open_account,
            'business_premises1' => $img_business_premises1,
            'business_premises2' => $img_business_premises2,
        ];
        $authApplyArray['merch_no'] = $intention->merch_no;
        $authApplyArray['wx_merch_no'] = $intention->haike_wxsub_merch_no;
        $response = $this->wxAuthApply($authApplyArray);
        Log::info($response);
        if ($response['return_code'] !== 10000) {
            return ['code' => 500, 'msg' => $response['return_msg']];
        }
        $intention->haike_wx_auth_status = 1;
        $intention->save();

        $authApply = $this->dao->getWhere(['apply_id' => $intention->mer_intention_id,'trade_type' => 'WXAUTHAPPLY']);
        if ($authApply)
            $this->dao->delete($authApply->id);

        $paramOrder = [
            'apply_id' => $intention->mer_intention_id ? : 0,
            'mer_id' => $intention->mer_id ? : 0,
            'mer_name' => $intention->mer_name,
            'uid' => $intention->uid,
            'phone' => $intention->phone,
            'merch_no' => $intention->merch_no,
            'wx_merch_no' => $intention->haike_wxsub_merch_no,
            'agent_apply_no' => $orderId,
            'trade_type' => 'WXAUTHAPPLY',
            'platform' => 1,
            'apply_type' => 2,
        ];
        $this->createApplyOrder($paramOrder);

        return ['code' => 200, 'msg' => $response['apply_no']];
    }
    /**
     * 支付宝业务申请
     * @author php迷途小书童
     * @created 2021/2/3 15:57
     */
    public function haikeAliApply($params)
    {
        $intentionRepository = app()->make(MerchantIntentionApplyRepository::class);
        $intention = $intentionRepository->getOne(['mer_intention_id' => $params['mer_intention_id']]);
        if (!$intention)
            return ['return_code' => 500, 'return_msg' => '申请信息不存在'];
        if (!$intention->merch_no)
            return ['return_code' => 500, 'return_msg' => '请先发起入网'];

        $authApply = $this->dao->getWhere(['apply_id' => $intention->mer_intention_id,'trade_type' => 'ALIAPPLY']);
        if ($authApply)
            $this->dao->delete($authApply->id);

        $orderId = $this->getNewOrderId('ALIAPPLY');
        $paramOrder = [
            'apply_id' => $intention->mer_intention_id ? : 0,
            'mer_id' => $intention->mer_id ? : 0,
            'mer_name' => $intention->mer_name,
            'uid' => $intention->uid,
            'phone' => $intention->phone,
            'merch_no' => $intention->merch_no,
            'agent_apply_no' => $orderId,
            'trade_type' => 'ALI',
            'platform' => 1,
            'apply_type' => 3,
        ];
        $this->createApplyOrder($paramOrder);

        $souxufee = systemConfig('yanglao');
        $rate = bcmul($souxufee,100);
        $paramOrder = [
            "merch_no"=> $intention->merch_no,
            "agent_apply_no"=> $orderId,
            "apply_notice"=> env('APP_URL')."/api/merchant/apply_notice",
            "haike_ali_type" => (string)$intention->haike_ali_type,
            "rate"=> (string)$rate,
        ];
        try {
            $response = $this->aliApply($paramOrder);
            if ($response['return_code'] !== 10000) {
                return ['return_code' => 500, 'return_msg' => $response['return_msg']];
            }
        } catch (\Throwable $e) {
            return ['return_code' => 500, 'return_msg' => '支付宝发起失败'];
        }

        $intention->haike_ali_status = 1;
        $intention->save();
        return ['return_code' => 200, 'return_msg' => '发起成功'];

    }
    public function createApplyOrder($paramOrder)
    {
        Db::transaction(function () use ($paramOrder) {
            $merchantOrder = $this->dao->create($paramOrder);
            return $merchantOrder;
        });
    }

    /**
     * 海科发起退款
     * @return array
     * @author php迷途小书童
     * @created 2021/2/5 17:40
     */
    public function haikeRefundApply($params)
    {
        $orderMerchantRepository = app()->make(OrderMerchantRepository::class);
        $recharge = $orderMerchantRepository->getOneById($params['recharge_id']);
        if (!$recharge)
            return ['return_code' => 500, 'return_msg' => '充值信息不存在'];
        if (!$recharge->paid)
            return ['return_code' => 500, 'return_msg' => '订单未完成支付'];

        $orderId = $this->getNewOrderId($recharge->trade_type.'REFUNDAPPLY');
        $recharge->refund_no = $orderId;
        $recharge->status = 2;
        $recharge->save();
        try {
            $response = $this->doRefundApply([
                "out_trade_no" => $recharge->out_trade_no,
                "refund_no" => $orderId,
                "money" => $recharge->money,
            ]);
            if ($response['return_code'] !== 10000) {
                return ['return_code' => 500, 'return_msg' => $response['error_msg']];
            }
        } catch (\Throwable $e) {
            return ['return_code' => 500, 'return_msg' => '发起退款失败'];
        }
        //修改订单状态
        Db::transaction(function () use ($recharge) {
            $recharge->refund_time = date('Y-m-d H:i:s');
            $recharge->status = 3;
            $recharge->save();
        });


        return ['return_code' => 200, 'return_msg' => '发起成功'];
    }
    /**
     * 回调处理
     * @return bool
     * @author php迷途小书童
     * @created 2021/1/16 15:12
     */
    public function doNotify($params)
    {
        $order = $this->dao->getWhere(['agent_apply_no' => $params['agent_apply_no']]);
        if (!$order)
            return false;
        if ($order->status == 3)
            return true;
        switch ($order->trade_type){
            //海科入网审核结果
            case 'WX,ALI':
                Queue::push(SendSmsJob::class, [
                    'tempId' => 'HAIKE_CHECK_MERCHANT_CODE',
                    'id' => $order->id
                ]);
                break;
        }
        //修改订单状态
        Db::transaction(function () use ($order, $params) {
            $intention = MerchantIntention::getInstance()->where('mer_intention_id', $order->apply_id)->find();
            if (!$intention)
                return true;
            if ($order->status == 3) {
                $order->applysms = 1;
            }
            try {
                //如果海科入网通过，且申请类型是个人，则申请微信和支付宝业务
                if ($order->apply_type == 1 && in_array($params['status'], [3,7])) {
                    $this->haikeWxApply(['mer_intention_id' => $intention->mer_intention_id]);
                    $this->haikeAliApply(['mer_intention_id' => $intention->mer_intention_id]);
                }
                //微信业务通过，且申请类型是个人，发起微信二次认证
                if ($order->apply_type == 2 && in_array($params['status'], [3])) {
                    $return = $this->haikeWxAuthApply(['mer_intention_id' => $intention->mer_intention_id]);
                    if ($return['code'] == 200) {
                        $this->haikeWxAppidConfAdd(['mer_intention_id' => $intention->mer_intention_id]);
                    }
                }
            } catch (\Throwable $e) {
                Log::info('mer_intention_id'. $intention->mer_intention_id . $e->getMessage());
            }
            //海科入网拒绝
            if ($order->apply_type == 1 && in_array($params['status'], [1,5,6])) {
                $intention->status = 2;
                $intention->check_result = $params['msg'] ?? '';
                $intention->save();
            }
            //微信报备失败
            if ($order->apply_type == 2 && in_array($params['status'], [2])) {
                $result_msg = '';
                try {
                    $str = substr($params['msg'], strpos($params['msg'], '{'));
                    $array = json_decode($str, true);
                    $result_msg = $array['result_msg'] ?? '';
                } catch (\Throwable $e) {
                    Log::info('微信报备回调:'.$e->getMessage());
                }
                $intention->status = 2;
                $intention->haike_wx_status = 2;
                $intention->check_result = $result_msg;
                $intention->save();
            }
            //支付宝报备失败
            if ($order->apply_type == 3 && in_array($params['status'], [2])) {
                $result_msg = '';
                try {
                    $str = substr($params['msg'], strpos($params['msg'], '{'));
                    $array = json_decode($str, true);
                    $result_msg = $array['result_msg'] ?? '';
                } catch (\Throwable $e) {
                    Log::info('支付宝报备回调:'.$e->getMessage());
                }
                $intention->status = 2;
                $intention->haike_ali_status = 2;
                $intention->check_result = $result_msg;
                $intention->save();
            }
            $order->status = $params['status'] ?? 0;
            $order->check_result = $params['msg'] ?? '';
            $order->apply_no = $params['apply_no'] ?? '';
            $order->update_time = date('Y-m-d H:i:s');
            $order->save();
        });
        return true;
    }
    /**
     * 图片压缩
     * @return bool|mixed
     * @author php迷途小书童
     * @created 2021/1/30 17:17
     */
    public function getThumb($img)
    {
        $img = app()->getRootPath().'/public'.$img;
        $image = \think\Image::open($img);
        // 返回图片的宽度
        $width1 = $width = $image->width();
        if ($width > 1000) {
            $width1 = 1000;
        }
        $multiple = bcdiv($width, $width1);
        // 返回图片的高度
        $height = $image->height();
        $height1 = bcdiv($height, $multiple);
        $image->thumb($width1, $height1)->save($img);
        return $this->getImageBase64($img);
    }

    /**
     * 获取base64
     * @return mixed
     * @author php迷途小书童
     * @created 2021/1/30 17:11
     */
    public function getImageBase64($img)
    {
        $file = $img;
        if($fp = fopen($file,"rb", 0))
        {
            $gambar = fread($fp,filesize($file));
            fclose($fp);

            return chunk_split(base64_encode($gambar));
        } else {
            return false;
        }
    }
}
