<?php

namespace app\api\controller\store;

use app\admin\logic\user\UserLogic as UserUserLogic;
use app\api\lists\store\SystemStoreLists;
use app\api\controller\BaseApiController;
use app\api\lists\user_create_log\UserCreateLogLists;
use app\api\logic\store\StoreLogic;
use app\api\logic\user\UserLogic;
use app\api\validate\UserValidate;
use app\common\enum\PayEnum;
use app\common\logic\PaymentLogic;
use app\common\logic\PayNotifyLogic;
use app\common\model\Config;
use app\common\model\user\User;
use app\common\model\user_create_log\UserCreateLog;
use app\common\model\user_recharge\UserRecharge;
use support\Cache;
use Webman\RedisQueue\Redis;

class StoreController extends BaseApiController
{
    public $notNeedLogin = ['detail'];
    public function lists()
    {
        return $this->dataLists(new SystemStoreLists());
    }

    /**
     * 创建用户记录列表
     */
    public function create_lists()
    {
        return $this->dataLists(new UserCreateLogLists());
    }

    /**
     * 门店信息
     */
    public function detail()
    {
        $store_id = (int)$this->request->get('store_id');
        $phone = (int)$this->request->get('phone');
        $where = [];
        if($phone){
            $where['phone'] = $phone;
        }
        if($store_id){
            $where['id'] = $store_id;
        }
        $info = StoreLogic::search($where);
        if ($info) {
            return $this->success('ok',$info);
        } else {
            return $this->fail('店铺不存在');
        }
    }

    /**
     * 门店会员充值
     */
    public function recharge()
    {
        $params = (new UserValidate())->post()->goCheck('rechargeStoreMoney');
        $auth_code = $this->request->post('auth_code'); //微信支付条码
        $recharge_type = $this->request->post('recharge_type',''); //微信支付条码
        $code = $this->request->post('code','');//验证码
        $phone = $params['mobile'];
        if($code && $phone){
            $remark = $phone.'_reporting';
            $codeCache = Cache::get($remark);
            if(empty($codeCache)){
                return $this->fail('验证码不存在');
            }
            if ($codeCache != $code) {
                return $this->fail('验证码错误');
            }
        }
        $find=User::where('mobile',$params['mobile'])->find();
        if(!$find){
            $params['create_uid']=$this->userId;
            $find=UserUserLogic::StoreAdd($params);
        }else{
            $find['real_name']=$params['real_name'];
            $find['label_id']=$params['label_id']??0;
            $find->save();
        }
        if($find === false){
            return $this->fail(UserUserLogic::getError());
        }
        if($recharge_type!='INDUSTRYMEMBERS'){
            return $this->success('添加用户成功');
        }
        $data=[
            'store_id'=>$params['store_id'],
            'uid'=>$find['id'],
            'other_uid'=>$this->userId,
            'staff_id'=>0,
            'order_id'=>getNewOrderId('CZ'),
            'price'=>Config::where('name','recharge')->value('value')??1000,
            'recharge_type'=>'INDUSTRYMEMBERS',
        ];
        $order = UserRecharge::create($data);

        $order['pay_price']=$order['price'];
        $result = PaymentLogic::codepay($auth_code, $order,'条码支付');
        if (PaymentLogic::hasError()) {
            return $this->fail(PaymentLogic::getError(), $params);
        }
        if (isset($result['trade_state_desc']) && $result['trade_state_desc'] == '支付成功') {
            PayNotifyLogic::handle('recharge', $result['out_trade_no'], $result);
        } else {
            Redis::send('send-code-pay', ['order_id' => $order['order_id'],'pay_type'=>'recharge']);
            return $this->success('用户支付中');
        }
        return $this->success('支付成功', ['out_trade_no' => $result['out_trade_no'], 'pay_type' => PayEnum::WECHAT_PAY_BARCODE, 'transaction_id' => $result['transaction_id']]);
    }

    /**
     * 重新充值会员
     */
    public function again_recharge()
    {
        $auth_code = $this->request->post('auth_code'); //微信支付条码
        $id = $this->request->post('id',0); //id
        $order = UserRecharge::where('id', $id)->where('paid',0)->find();
        if(!$order){
            return $this->fail('订单不存在');
        }
        $order_id=getNewOrderId('CZ');
        UserRecharge::where('id', $id)->update(['order_id'=>$order_id]);
        $order['order_id']=$order_id;
        $order['pay_price']=$order['price'];
        $result = PaymentLogic::codepay($auth_code, $order,'条码支付');
        if (PaymentLogic::hasError()) {
            return $this->fail(PaymentLogic::getError());
        }
        if (isset($result['trade_state_desc']) && $result['trade_state_desc'] == '支付成功') {
            PayNotifyLogic::handle('recharge', $result['out_trade_no'], $result);
        } else {
            Redis::send('send-code-pay', ['order_id' => $order['order_id'],'pay_type'=>'recharge']);
            return $this->success('用户支付中');
        }
        return $this->success('支付成功', ['out_trade_no' => $result['out_trade_no'], 'pay_type' => PayEnum::WECHAT_PAY_BARCODE, 'transaction_id' => $result['transaction_id']]);
    }


        /**
     * 门店会员充值数量
     */
    public function recharge_count()
    {
        $store_id = $this->request->get('store_id',0);
        $count=0;
        $createLog=0;
        if($store_id){
           $count= UserRecharge::where(['store_id'=>$store_id,'recharge_type'=>'INDUSTRYMEMBERS','paid'=>1])->count();
           $createLog= UserCreateLog::where(['store_id'=>$store_id])->count();
        }
        return $this->success('ok',['count'=>$count,'create_log'=>$createLog]);

    }
}