<?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\UserAddress;
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('验证码错误');
//            }
//        }
        if($params['price']>10000){
            return $this->fail('充值金额不能大于10000');
        }
        $find=User::where('account|mobile',$params['mobile'])->find();
        if(!$find){
            $params['create_uid']=$this->userId;
            if(isset($params['user_ship']) && in_array($params['user_ship'],[2,3])){
                UserUserLogic::checkAddress($params);
                if(UserUserLogic::hasError()){
                    return $this->fail(UserUserLogic::getError());
                }
            }
            $find=UserUserLogic::StoreAdd($params);
            if(UserUserLogic::hasError()){
                return $this->fail(UserUserLogic::getError());
            }
        }else{
            if($find['user_ship']!=$params['user_ship'] && in_array($params['user_ship'],[2,3])){
                UserUserLogic::checkAddress($params);
                if(UserUserLogic::hasError()){
                    return $this->fail(UserUserLogic::getError());
                }
            }
            $find['real_name']=$params['real_name'];
            $find['label_id']=$params['label_id']??0;
            $find->save();
            $adds=UserAddress::where('uid',$find['id'])->find();
            $adds_data=[
                'uid' => $find['id'],
                'real_name' => $params['real_name']??"",
                'mobile' => $params['mobile']??'',
                'province' => $params['province']??'',
                'city' => $params['city']??'',
                'area' => $params['area']??'',
                'street' => $params['street']??'',
                'village' => $params['village']??'',
                'brigade' => $params['brigade']??'',
                'is_default' => 1,
            ];
            if($adds){
                $adds->save($adds_data);
            }else{
                UserAddress::create($adds_data);
            }
        }
        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'=>$params['price']??1000,
            'recharge_type'=>'INDUSTRYMEMBERS',
            'user_ship'=>$params['user_ship']??0,
        ];
        $order = UserRecharge::create($data);

        $order['pay_price']=$order['price'];
        $order['attach']='recharge';
        $result = PaymentLogic::codepay($auth_code, $order,'条码支付');
        if (PaymentLogic::hasError()) {
            return $this->fail(PaymentLogic::getError());
        }
        if (isset($result['trade_state_desc']) && $result['trade_state_desc'] == '支付成功') {
            Cache::set('trade_state' . time(), json_encode($result));
            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'];
        $order['attach']='recharge';
        $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]);

    }
}