<?php

namespace app\controller\api;

use app\extra\basic\Base;
use app\extra\tools\CodeExtend;
use app\extra\weMini\Crypt;
use app\middleware\WxMiddleware;
use app\model\saas\SaasShop;
use app\model\saas\SaasUser;
use app\model\saas\SaasUserOpen;
use LinFly\Annotation\Route\Controller;
use LinFly\Annotation\Route\Route;
use support\Request;
use support\Response;
use LinFly\Annotation\Route\Middleware;
use Shopwwi\WebmanAuth\Facade\Auth as AuthMode;
use support\think\Db;


#[Controller(prefix: "/wx_api/default"),Middleware(WxMiddleware::class)]
class Home extends Base
{


    protected array $whiteShop = [
        "10888572278827"    => "10888572278827", // 惠印多马村店
        "10888566286841"    => "327545130062964", // 中站小学店
        "10888590458813"    => "326945519114632", // 幸小印美店
        "10888645729727"    => "326844775971796", // 焦作和平街店
    ];

    /**
     * 跳出授权
     * @var array|string[]
     */
    protected array $noNeedLogin = ['loginHome','changeData','changeDataSubmit'];


    #[Route(path: "change_save",methods: "post")]
    public function changeDataSubmit(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "shop.require"  => "",
                "old.require"  => "",
                "openid.default"  => ""
            ],$request->method());
            if (!is_array($param)) return error($param);
            $member = (new SaasUser)->where("openid",$param['openid'])->findOrEmpty();
            if (!$member->isEmpty()) return error("无需多次操作");
            $old = Db::connect("old")->table("inmei_member_card")->where("openid",$param['old'])->findOrEmpty();
            if (isset($this->whiteShop[$param['shop']])) {
                $shopId = $this->whiteShop[$param['shop']];
            } else {
                $shopId = $param['shop'];
            }
            $state = $member->insertGetId([
                "openid"    => $param['openid'],
                "shop_id"   => $shopId,
                "card_no"   => strtoupper(md5($param['openid'].$shopId)),
                "balance"   => $old['balance'],
                "total_balance" => $old['total_balance']
            ]);
            if (!$state) return error("操作失败");
            return success("转入成功");
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }

    #[Route(path: "change",methods: "post")]
    public function changeData(Request $request): Response
    {
        try {
            $param = $this->_valid([
                "shop.require"  => "",
                "code.require"  => "",
                "openid.default"  => ""
            ],$request->method());
            if (!is_array($param)) return error($param);
            $userinfo = (new Crypt([
                "appid"     => sConf("wechat.mini_appid"),
                "appsecret" => sConf("wechat.mini_secret")
            ]))->session($param['code']);
            if (!isset($userinfo['openid'])) return error("获取数据失败");
            $openId = $userinfo['openid'];
            $old = Db::connect("old")->table("inmei_member_card")->where("openid",$param['openid'])->where("shop_id",$param['shop'])->findOrEmpty();
            if (empty($old)) $old = null;
            if (isset($this->whiteShop[$param['shop']])) {
                $shopId = $this->whiteShop[$param['shop']];
            } else {
                $shopId = $param['shop'];
            }
            $shop = (new SaasShop)->where("shop_id",$shopId)->findOrEmpty();
            if ($shop->isEmpty()) $shop = null;
            return success("ok",compact("shop",'old','openId'));
        } catch (\Throwable $throwable) {
            return error($throwable->getMessage());
        }
    }


    /**
     * 首页信息
     * @return Response
     */
    #[Route(path: "home",methods: "post")]
    public function loginHome(Request $request)
    {
        try {
            $param = $this->_valid([
                "shop.require"  => "",
                "print.require" => "",
                "code.require"  => "",
                "card.default"  => "",
                "oshop.default"  => "",
                "oid.default"  => ""
            ],$request->method());
            if (!is_array($param)) return error($param);
            $userinfo = (new Crypt([
                "appid"     => sConf("wechat.mini_appid"),
                "appsecret" => sConf("wechat.mini_secret")
            ]))->session($param['code']);
            if (!isset($userinfo['openid'])) return error("获取数据失败");
            $map = ['is_deleted' => 0, 'openid' => $userinfo['openid']];
            $user = (new SaasUserOpen)->where($map)->findOrEmpty();
            if ($user->isEmpty()) {
                $user->insertGetId(['openid' => $userinfo['openid'],'oid' => ($param['oid'] == 'undefined'?'':$param['oid']),'update_at' => getDateFull(),"create_ip" => $request->getRealIp(),"nickname" => "微信用户","headimg" => "https://inmei-print.oss-cn-guangzhou.aliyuncs.com/logo.png"]);
                $user = (new SaasUserOpen)->where($map)->findOrEmpty();
            } else {
                if (!empty($param['oid']) && empty($user['oid'])) {
                    if ($param['oid'] !== 'undefined') {
                        $user->oid = ($param['oid'] == 'undefined'?'':$param['oid']);
                        $user->update_at = getDateFull();
                        $user->save();
                    }
                }
            }
            $userAuth = get_object_vars(AuthMode::guard("member")->login($user->toArray()));
            $shopData = [];
            $cardState = 0;
            if (!empty($param['shop']))
            {
                $shop = (new SaasShop)->where("shop_id", $param['shop'])->field("shop_name,start_at,end_at,vip_end,shop_status,shop_notice,line_time,status,shop_address")->findOrEmpty();
                if ($shop->isEmpty()) return error("店铺已被关闭");
                $currentTime = time();
                $vipEndTime = strtotime($shop['vip_end'] ?? '');
                $lineEndTime = strtotime("+10020000 min", strtotime($shop['line_time'] ?? ''));
                $today = date('Y-m-d');
                $startTime = strtotime("{$today} {$shop['start_at']}");
                $endTime = strtotime("{$today} {$shop['end_at']}");
                if ($currentTime > $vipEndTime){
                    $status = ['text' => '已过期', 'val' => 0];
                } else if ($shop['status'] == 2) {
                    $status = ['text' => '已冻结', 'val' => 0];
                } else if ($currentTime > $lineEndTime) {
                    $status = ['text' => '已离线', 'val' => 0];
                } else if ($currentTime > $endTime || $currentTime < $startTime) // 过了营业时间
                {
                    $status = ['text' => '休息中', 'val' => 0];
                } else {
                    $status = ['text' => '营业中', 'val' => 1];
                }
                $shop['status_text'] = $status['text'];
                $shop['status_val'] = $status['val'];
                $shop['time'] = ($shop['start_at'] == '00:00' && $shop['end_at'] == '23:59')
                    ? '24小时营业'
                    : date('H:i', $startTime) . '-' . date('H:i', $endTime);
                if ($param['card'] == 1) { // 领取会员卡
                    $cardInfo = (new SaasUser)->where("shop_id",$param['shop'])->where("openid",$userinfo['openid'])->findOrEmpty();
                    if ($cardInfo->isEmpty()) {
                        $cardInfo->insertGetId([
                            "shop_id"   => $param['shop'],
                            "openid"    => $userinfo['openid'],
                            "card_no"   => CodeExtend::uniqidDate(16,"1088")
                        ]);
                        $cardState = 1;
                    }
                }
                $shopData = $shop->toArray();
            }
            $share = sConf("wechat.share");
            return success("ok",["shop" => $shopData,'user' => ['nickname' => $user['nickname']??'','avatar' => $user['avatar']??''],"token" => $userAuth,"card" => $cardState,"share" => $share]);
        }catch (\Throwable $e){
            echo $e->getMessage()."\n";
            echo $e->getFile()."\n";
            echo $e->getLine()."\n";
            return error($e->getMessage());
        }
    }

}