<?php


namespace Application\Service\DB\Pay;

use Application\Common\StatusCode;
use Application\Service\DB\Db;
use Interop\Container\ContainerInterface;
use EasyWeChat\Factory;
use Application\Service\Extension\Helper\StringHelper;
use Application\Service\Extension\Laminas;
use Laminas\Mvc\Exception\InvalidArgumentException;

class Transfer extends \Application\Service\DB\AbstractDb
{
    //转账配置
    private $app;

    private $inSandbox;


    public function __construct($dbAdapter, ContainerInterface $container)
    {
        $easywechatConfig = Laminas::$app->getConfig()['Easywechat'];
        $this->app = Factory::payment($easywechatConfig);

        $this->inSandbox = $this->app->inSandbox();

        $this->tableName = 'yikeen_item_transfer';
        parent::__construct($dbAdapter, $container);
    }

    /**
     * Notes : 转账到受试者【非批量处理】
     * Author:唐伯虎不虎
     * Date:2023/12/20 13:54
     */
    public function topatient($data) :void
    {
        if($this->inSandbox) echo "当前是测试模式"."<pre/>";

        //生成订单号
        $tradeNo = StringHelper::generatetradeno();

        //获取受试者OpenId  【待完成】
        //$this->LocalService()->adminUser->fetchOne(['where'=>'']);
        Db::beginTransaction();
        try {
            $addId = $this->insert($data);
            Db::commit();

            $result = $this->app->transfer->toBalance([
                'partner_trade_no' => $tradeNo, // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
                'openid' => $data['open_id'],
                'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
                're_user_name' => $data['patient_name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
                'amount' => $data['amount'], // 企业付款金额，单位为分
                'desc' => $data['desc'], // 企业付款操作说明信息。必填
            ]);
            if($result) {
                Laminas::$serviceManager->redisExtend->setDatabase(5)->getRedisInstance()->lPush('transfer',$tradeNo);
            }else{
                $this->update(['is_del'=>1],['id'=>$addId]);
            }
        } catch (\Exception $e) {
            Db::rollback();
            echo "An error occurred".$e->getMessage();die;
        }
    }

    /**
     * Notes : 更新受试者补助发放状态
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     * Author:唐伯虎不虎
     * Date:2023/12/20 16:43
     */
    public function changeorderStatus():void
    {
        $redis = Laminas::$serviceManager->redisExtend->setDatabase(5)->getRedisInstance();
        $tradeNo = $redis->rPop('transfer');

        $status = $this->app->transfer->queryBalanceOrder($tradeNo);
        if(!$status){
            $redis->lPush('transfer',$tradeNo);
        }else{
            Db::beginTransaction();
            try {

                $this->update(['is_success'=>1],['trade_no'=>$tradeNo]);
                Db::commit();
                //发放受试者模板消息【代开发】

            } catch (\Exception $e) {
                Db::rollback();
                $redis->lPush('transfer',$tradeNo);
                echo "An error occurred".$e->getMessage();die;
            }
        }
    }

    public function _getPatientinfo(int $patient_id):array
    {
        //获取受试者信息
        $patientInfo = $this->LocalService()->patient->fetchOne(['where'=> [
            'id' => $patient_id,
            'is_del' => 0,
        ],'columns'=>['patient_tel','patient_name']]);
        if(empty($patientInfo['patient_tel']))
            throw new InvalidArgumentException("此受试者未登录过系统，无法发放补助!", StatusCode::E_FIELD_VALIDATOR['code']);

        $open_id = $this->LocalService()->adminUser->getOneFieldVal('openid',"mobile = ".$patientInfo['patient_tel']." and is_del = 0 and status = 0");
        if(empty($open_id)){
            throw new InvalidArgumentException("此受试者无法发放补助，请联系管理员!", StatusCode::E_FIELD_VALIDATOR['code']);
        }
        $patientInfo['open_id'] = $open_id;
        return $patientInfo;
    }






}