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

namespace app\api\controller;

/**
 * 群管理
 * Summary of Group
 */
class Merchant extends BaseShopController
{

    public function createMerchant()
    {
        
        $params = $this->request->post();

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

        if($merchant){
            return show(config('status.error'),'你已申请过商家了');
        }
        
        \think\facade\Db::startTrans(); 
        try{
            
            $createData = [
                'user_id'=>$this->userId,
                'name'=>$params['name'],//商家名称
                'desc'=>$params['desc'],//商家描述
                'type'=>2,//默认企业
                'status'=>0,//待审核

                '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']??'',//资质
            ];


            $res = \app\common\model\Merchant::create($createData);
            if(!$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::field('id,name,pid,image,desc')
            ->order(['sort'=>'desc','id'=>'desc'])
            ->select()
            ->toArray();

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

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

    /**
     * 群列表查询
     */
    public function list()
    {
        $params = $this->request->get();

        $where = [];

        if(isset($params['category_id'])){
            $where[]=['category_id','=',$params['category_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'].'%'];
        }

        $list = \app\common\model\Merchant::with(['user'])
        ->where($where)
        ->where('status',1)
        ->order('create_time','desc')
        ->paginate(20);

        $list = $list->toArray();

        foreach($list as &$v){
            $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);

        $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 != 0){
            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'];


        if(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'),'修改成功');
        
    }



}