<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║
 *  ║                                                   ║
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\api\controller;

use app\common\model\IndexVisit;
use app\common\model\MerchantCategory;
use app\common\model\MerchantTopList;
use app\common\model\MerchantVisit;
use app\common\service\ConfigService;

/**
 * Summary of Group
 */
class Merchant extends BaseShopController
{
    public array $notNeedLogin = ['categroyList', 'list', 'details'];

    // 自定义模板表单
    public function getFormTemplate()
    {
        $template_id=\app\common\service\ConfigService::get('form_template','merchant');
        $data=[];
        if(!empty($template_id)){
            \app\common\model\FormTemplate::with('item')->find($template_id);
        }

        return show(1,'',[
            'template_id'=>$template_id,
            'data'=>$data,
        ]);
    }

    public function createMerchant()
    {

        $params = $this->request->post();

        $merchant = \app\common\model\Merchant::where('user_id',$this->userId)->find();

        \think\facade\Db::startTrans();
        try{
            $createData = [
                'user_id'=>$this->userId,
                'name'=>$params['name'],//商家名称
                'desc'=>$params['desc'],//商家描述
                'type'=>2,//默认企业
                'status'=>!ConfigService::get('merchant', 'apply_status', 1),//待审核

                'category_id'=>$params['category_id'],

                'region_id'=>$params['region_id'],

                // 位置
                'longitude'=>$params['longitude'],
                'latitude'=>$params['latitude'],
                'province'=>$params['province'],
                'city'=>$params['city'],
                'district'=>$params['district'],
                'address'=>$params['address'],

                'logo'=>$params['logo'],
                'mp4'=>$params['mp4'],
                'opening_hours'=>$params['opening_hours'],

                // 联系
                'phone'=>$params['phone'],
                'email'=>$params['email'],
                'wechat_code'=>$params['wechat_code'],

                // 认证资料
                'license'=>$params['license'],//营业执照
                'person'=>$params['person'],//法人/个人名字
                'id_card_number'=>$params['id_card_number'],//法人/个人身份证
                'qualifications'=>$params['qualifications']??'',//资质

                'images'=>$params['images']??'',
                // 'scale'=>$params['scale']??'',

                'vip_order_id'=>$params['order_id'],

                'scale_min'=>$params['scale_min']??0,
                'scale_max'=>$params['scale_max']??0,

            ];
            $template_id=\app\common\service\ConfigService::get('form_template','merchant');
            if(!empty($template_id)){
                $template=\app\common\model\FormTemplate::with('item')->find($template_id);
                // 自定义表单模板数据
                $formData = $params['form_template'];

                //自定义提交表单主记录
                $form_submission=[
                    "template_id"=>$template_id,//模板id
                    "user_id"=>$this->userId,
                    "ip"=>$this->request->ip(),
                    "status"=>0,//待审核
                    "code"=>"merchant",
                ];

                // 表单提交详情
                $form_submission_details=[];

                // 自定义提交的表单项值
                foreach($formData as $v){
                    $form_submission_details[]=[
                        "submission_id"=>$v['id'],
                        "template_item_id"=>$v['template_item_id'],
                        "value"=>$v['value']
                    ];
                }
                // 添加表单提交数据表
                \app\common\model\FormSubmission::create($form_submission);
                // 添加表单项值
                \app\common\model\FormSubmissionDetails::insertAll($form_submission_details);

            }

            if($merchant){
                if (!$merchant->save($createData)) {
                    return show(0, '更新失败');
                }
                $res = $merchant;
            } else {
                $order = \app\common\model\MerchantVipOrder::where('id',$params['order_id'])->where('user_id',$this->userId)->find();

                if (!$order) {
                    return show(0, '订单不存在');
                }

                $vip = \app\common\model\MerchantVipLevel::find($order->vip_level_id);

                if (!$vip) {
                    return show(0, '会员等级不存在');
                }

                $createData['vip_id'] = $vip->id;
                $createData['vip_expires'] = time() + $vip->available_days * 86400;

                $res = \app\common\model\Merchant::create($createData);
            }
            
            if(!isset($res)){
                return $this->success('error',[],0);
            };
            
            \think\facade\Db::commit();
            return $this->success('ok',['merchant_id'=>$res->id]);

        }catch(\Exception $e){
            \think\facade\Db::rollback();
            return show(config('status.error'),'创建失败：'.$e->getMessage());
        }

    }


    public function categroyList()
    {
        $lists = \app\common\model\MerchantCategory::where('status',1)
            ->order(['sort'=>'desc','id'=>'desc'])
            ->select()
            ->toArray();

        $lists = linear_to_tree($lists,'sons');

        return show(config('status.success'),'分类',$lists);
    }

    public function vipInfo()
    {
        $merchant = \app\common\model\Merchant::where('user_id',$this->userId)->find();
        if (!$merchant) {
            return show(config('status.error'),'商户不存在');
        }
        $vip = \app\common\model\MerchantVipLevel::find($merchant->vip_id);
        if (!$vip) {
            return show(config('status.error'),'会员等级不存在');
        }

        return show(config('status.success'),'会员等级',$vip);
    }

    /**
     * 商户列表信息
     */
    public function list()
    {
        $params = $this->request->get();

        $query = \app\common\model\Merchant::with(['user','vip']);

        $where = [];

        if(isset($params['category_id'])){
            $cids = MerchantCategory::where('id',$params['category_id'])->whereOr('pid',$params['category_id'])->column('id');

            $where[]=['category_id','in',$cids];
        }

        if(isset($params['region_id'])){
            $where[]=['region_id','like',$params['region_id'].'%'];
        }

        if(isset($params['label_id'])){
            $where[]=['label_ids','like','%,'.$params['label_id'].',%'];
        }

        if(isset($params['name'])){
            $where[]=['name','like','%'.$params['name'].'%'];
        }

        if(isset($params['category_id'])){
            // $where[]=['category_id','like',$params['category_id']];
        }

        if(isset($params['province'])){
            $where[]=['province','like','%'.$params['province'].'%'];
        }
        if(isset($params['city'])){
            $where[]=['city','like','%'.$params['city'].'%'];
        }
        if(isset($params['district'])){
            $where[]=['district','like','%'.$params['district'].'%'];
        }
        if(isset($params['address'])){
            $where[]=['county','like','%'.$params['county'].'%'];
        }

        $order = 'id desc';

        if (isset($params['order'])) {

            if ($params['order'] == 1) {
                if (!isset($params['longitude']) || !isset($params['latitude'])) {
                    return show(0, '参数错误');
                }

                $longitude =  $params['longitude'];
                $latitude =  $params['latitude'];
            
                $query =$query->alias('s')
                    ->field("*,".get_distance_sql($longitude,$latitude))
                    ->whereNotNull('latitude') // 确保纬度不为空
                    ->whereNotNull('longitude') // 确保经度不为空
                    ->order("distance", "asc");
            }

            if ($params['order'] == 2) {
                $order = 'rand()';
            }

            if ($params['order'] == 3) {
                // TODO: 最热
            }

            if ($params['order'] == 4) {
                $order = 'created_time desc';
            }

            if ($params['order'] == 5) {
                $where[]=['id','in',\app\common\model\MerchantFollow::where('user_id', $this->userId)->column('merchant_id')];
            }

            if ($params['order'] == 6) {
                $order = 'share_count desc';
            }
            
        }

        $topIds = MerchantTopList::where([
            [
                'expire_time','>',time()
            ]
        ])->column('merchant_id');

       if(!empty($topIds)){
         $order = 'CASE WHEN id IN (' . implode(',', $topIds) . ') THEN 0 ELSE 1 END,' . $order;
       }

        $list = $query
        ->where($where)
        ->where('status',1)
        ->orderRaw($order)
        ->paginate(20);


        
        $list = $list->toArray();
        // dd(is_int($v['label_list']));
        foreach($list['data'] as &$v){
            $v['is_top'] = in_array($v['id'],$topIds);
            // dd($v);
            if(is_int($v['label_ids']) == true || strpos($v['label_ids'] ?? '', ",") == false){
                $v['label_list'] = \app\common\model\MerchantLabel::where('id','=',$v['label_ids'])->select()->toArray();
            }else{
                $v['label_list'] = \app\common\model\MerchantLabel::where('id','in',explode(',',$v['label_ids']))->select()->toArray();
            }

            $v['is_follow'] = !!\app\common\model\MerchantFollow::where([
                ['user_id','=',$this->userId],
                ['merchant_id','=',$v['id']]
            ])->find();
        }



        // 确保我们处理的是实际的数据数组部分
        // foreach($list as &$v){
        //     if(isset($v['label_ids'])){
        //         $v['label_list'] = \app\common\model\Merchant::where('id','in',explode(',',$v['label_ids']))->select()->toArray();
        //     }
        // }


        return show(config('status.success'),'列表',$list);

    }


    /**
     * 商家标签
     */
    public function merchantLabelList()
    {
        $list = \app\common\model\MerchantLabel::order('sort','desc')->select()->toArray();

        return show(config('status.success'),$list);
    }

    /**
     * 用户创建标签
     */
    public function createLabel()
    {
        $label_name = $this->request->post('label_name');

        $label = \app\common\model\MerchantLabel::where('name',$label_name)->find();

        if($label){
           return show(config('status.success'),'标签已存在');
        }

        $res = \app\common\model\MerchantLabel::create(['name'=>$label_name]);

        return show(config('status.success'),'添加成功',['id'=>$res->id]);

    }

    /**
     * 
     */
    public function details($id)
    {
        $data = \app\common\model\Merchant::with(['user'])->find($id);

        // if(is_int($data['label_ids']) == true || strpos($data['label_ids'], ",") == false){
        //     $data['label_list'] = \app\common\model\MerchantLabel::where('id','=',$data['label_ids'])->select()->toArray();
        // }else{
        //     $data['label_list'] = \app\common\model\MerchantLabel::where('id','in',explode(',',$data['label_ids']))->select()->toArray();
        // }

        $data['label_list'] = \app\common\model\MerchantLabel::where('id','in',explode(',',$data['label_ids'] ?? ''))->select()->toArray();
        $params = $this->request->post();
        $params['terminal'] = $this->terminal;
        $ip = request()->ip();

        $record = MerchantVisit::where([
            'ip' => $ip,
            'terminal' => $params['terminal'],
            'mid' => $id
        ])->whereDay('create_time')->findOrEmpty();

        if ($record->isEmpty()) {
            $data->visit_count += 1;
            $data->save();

            // 生成访客记录
            MerchantVisit::create([
                'ip' => $ip,
                'terminal' => $params['terminal'],
                'mid' => $id
            ]);
        }

        $data['is_follow'] = !!\app\common\model\MerchantFollow::where([
            ['user_id','=',$this->userId],
            ['merchant_id','=',$data['id']]
        ])->find();

        // 商家入驻时候填写的自定义表单
        $data['form_submission']=\app\common\model\FormSubmission::with('details')
        ->where('code','merchant')
        ->select();

        return show(config('status.success'),'',$data);
    }

    public function my()
    {
        $data = \app\common\model\Merchant::where('user_id', $this->userId)->find();

        if (!$data) {
            return show(0, '查询失败');
        }

        // if(is_int($data['label_ids']) == true || strpos($data['label_ids'], ",") == false){
        //     $data['label_list'] = \app\common\model\MerchantLabel::where('id','=',$data['label_ids'])->select()->toArray();
        // }else{
        //     $data['label_list'] = \app\common\model\MerchantLabel::where('id','in',explode(',',$data['label_ids']))->select()->toArray();
        // }

        if ($data['vip_expires'] > time()) {
            $data['vip_level'] = \app\common\model\MerchantVipLevel::find($data['vip_id']);
        } else {
            $data['vip_level'] = null;
        }

        $data['top'] = MerchantTopList::where('merchant_id',$data['id'])->where([
            [
                'expire_time', '>', time()
            ]
        ])->find();

        $data['label_list'] = \app\common\model\MerchantLabel::where('id','in',explode(',',$data['label_ids'] ?? ''))->select()->toArray();

        return show(config('status.success'),'',$data);
    }

    /**
     * 商家修改
     */
    public function update()
    {
        $params = $this->request->post();

        $merchant = \app\common\model\Merchant::find($params['id']);

        if($merchant->user_id != $this->userId){
            return show(config('status.error'),'无权限修改');
        }

        if($merchant->status != 1){
            return show(config('status.error'),'正在审核或冻结无法修改');
        }
        
        $updata_allow = ['name','license','phone','email','wechat_code','province','city','district','address','longitude','latitude','logo','mp4','desc','opening_hours','status','qualifications','person','license','id_card_number'
        ,'scale_min','scale_max'];

        if(isset($params['field']) && !in_array($params['field'],$updata_allow)){
            return show(config('status.error'),'当前字段内容不支持修改');
        }

        // 修改成功后 后台需要重新审核
        \app\common\model\Merchant::where('id',$params['id'])->update([$params['field']=>$params['value'],'status'=>0]);

        return show(config('status.success'),'修改成功');

    }



}