<?php
/**
 * 公共调用的方法,不做登录态验证
 */

namespace App\Http\Controllers;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Sts\Sts;
use App\Facades\CommonService;
use App\Facades\WechatService;
use App\Http\Response\CatchError;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\China;
use App\Models\Group;
use App\Models\MedicalReport;
use App\Models\PublicConfig;
use App\Models\User;
use App\Models\UserInfo;
use App\Models\Version;
use App\Services\ConfigService;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class PublicController extends Controller
{
    use ResponseJson, CatchError;

    /**
     * 获取三部曲配置
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getInfoStepConfig(Request $request)
    {
        try {
            $chat_id = $request->get('chat_id');
            $service_user_id = $request->get('service_user_id');
            $sex = $request->get('sex');
            if(!empty($chat_id)){
                if($service_user_id){
                    $group = Group::with('order')->where('im_chat_id',$chat_id)->first();
                }else{
                    $group = Group::with('order')->where('chat_id',$chat_id)->first();
                }
                $user = User::where('id',$group->order->user_id??0)->first();
                if(empty($user)){
                    return $this->failure('用户信息不存在');
                }
            }else{
                $user = auth()->user();
            }
            $configService = new ConfigService();

            if(empty($sex)){
                $sex = $user->sex;
            }
            $res = $configService->stepConfig($user,$sex);

            if (!$res['status']) {
                return $this->failure($res['msg']);
            }
            return $this->success('ok', $res['data']??[]);
        } catch (\Exception $e) {
            return $this->failure('获取失败');
        }
    }

    /**
     * 获取阿里云oss配置
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function aliYunSignature(Request $request)
    {
        try {
            $id = config('alioss.id');
            $key = config('alioss.secret');
            $host = 'https://' . config('alioss.domain');
            $bucket = config('alioss.bucket');
            //            $host = 'https://ufutx-images.oss-accelerate.aliyuncs.com';
            $now = time();
            $expire = 60 * 30; //设置该policy超时时间是60s. 即这个policy过了这个有效时间，将不能访问
            $end = $now + $expire;
            $expiration = gmt_iso8601($end);

            $dir = urldecode($request->dir);
            if (empty($dir)) {
                $dir = date('Y') . date('m') . "/" . date('d') . "/";
            }


            //最大文件大小.用户可以自己设置
            $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
            $conditions[] = $condition;

            //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
            $start = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
            $conditions[] = $start;


            //这里默认设置是２０２０年.注意了,可以根据自己的逻辑,设定expire 时间.达到让前端定时到后面取signature的逻辑
            $arr = array('expiration' => $expiration, 'conditions' => $conditions);
            $policy = json_encode($arr);
            $base64_policy = base64_encode($policy);
            $string_to_sign = $base64_policy;
            $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));
            $callback_url = $request->root() . '/api/upload';
            $callback_param = array(
                'callbackUrl' => $callback_url,
                'callbackBody' => 'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
                'callbackBodyType' => "application/x-www-form-urlencoded"
            );
            $callback_string = json_encode($callback_param);
            $base64_callback_body = base64_encode($callback_string);


            $response = array();
            $response['access_id'] = $id;
            $response['host'] = $host;
            $response['policy'] = $base64_policy;
            $response['signature'] = $signature;
            $response['expire'] = $end;
            $response['secret'] = $key;
            //这个参数是设置用户上传指定的前缀
            $response['dir'] = $dir;
            $response['picture_domain'] = config('alioss.domain');
            $response['bucket'] = $bucket;
            $response['endpoint'] = config('alioss.out_endpoint');
            //$response['callback'] = $base64_callback_body;
            return $this->success('ok', $response);
        } catch (\Exception $e) {
            AddErrorLog::dispatch('aliYunSignature:' . $e->getMessage())->onQueue('health');
            return $this->failure("上传失败");
        }
    }

    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function getJsSdkConfig(Request $request)
    {
        try {
            $url = $request->get('url');
            if ($url) {
                $url = urldecode($url);
            } else {
                $url = env('APP_URL') . '/home/';
            }
//            $config = WechatService::getOfficialShareConfig($url);
            $config = WechatService::buildJsSdkConfig($url);
            return $this->success('ok', $config);
        } catch (\Exception $e) {
            $this->getError($e);
            return $this->success('ok');
        }
    }

    public function getChina(Request $request)
    {
//        $pid = $request->get('pid');
        if (empty($pid)) {
            $pid = 0;
        }
        $redis = Redis::client();
        $address = $redis->get('china_address');
        if(!empty($address)){
            $address = json_decode($address);
        }else{
            $address = China::where('id', '<>', 0)->where('pid', $pid)->orderBy('id', 'asc')->get()->toArray();
            if (strlen($pid)) {
                foreach ($address as $key => $value) {
                    $address[$key]['city'] = $city = China::where('pid', $value['id'])->orderBy('id', 'asc')->get()->toArray();
                    foreach ($city as $k => $v){
                        $address[$key]['city'][$k]['county'] = China::where('pid', $v['id'])->orderBy('id', 'asc')->get()->toArray();
                    }
                }
            }
            $redis->set('china_address',json_encode($address));
        }
        return $this->success('ok', $address);
    }

    public function getSubscribeTemplateId()
    {
        return $this->success('ok', config('wechat.sub_tpls'));
    }


    public function getVersion(Request $request)
    {
        $type = $request->get('type');
        $version = Version::where('type', $type)->orderBydesc('id')->value('version');
        return $this->success('ok', $version);
    }

    public function getReportType()
    {
        $report = [
            "色情低俗",
            "违法犯罪",
            "政治敏感",
            "违规营销",
            "不实信息",
            "危害人身安全",
            "未成年相关",
            "侵犯权益",
            "其他",
        ];
        return $this->success('ok', $report);
    }

    public function getPrivacy(Request $request)
    {
        try {
            $name = $request->get('name', PublicConfig::APP_PRIVACY);
            $privacy = PublicConfig::where('name', $name)->get();
            foreach ($privacy as $key => $value) {
//                $value->content = json_decode($value->content,true);
                $content = json_decode($value->content, true);
                if ($content != null) {
                    $value->content = $content;
                }
            }
            return $this->success('ok', $privacy);
        } catch (\Exception $e) {
            Log::error('getPrivacy:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    public function getOfficialQrcodeImg()
    {
        try {
            $img = "https://images.health.ufutx.com/202402/27/990ef8b7127a62952a52b25d2cb0eb80.jpeg";
            return $this->success('ok', $img);
        } catch (\Exception $e) {
            Log::error('getOfficialQrcodeImg:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }
}
