<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 分类信息管理
 */
namespace app\citys\model;
use app\common\facade\Inform;
use app\citys\model\Levels;
use app\citys\model\Vip;
use think\Model;
use util\Util;
use filter\Filter;
use think\db\Where;

class Citys extends Model{

    protected $pk = 'id';
    protected $json = ['images','fields','like_face'];
    protected $jsonAssoc = true;
    
    //用户
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','uid');
    }
    
    //一对多管理回复的评论
    public function comments(){
        return $this->hasMany('CitysReply','info_id','id');
    }

    //所属模板
    public function cate(){
        return $this->hasOne('CitysCate','id','cate_id');
    }

    //所属主题
    public function types(){
        return $this->hasOne('CitysType','id','type_id');
    }

    //是否关注
    public function follow(){
        return $this->hasOne('CitysFollow','like_uid','uid');
    }
    
    //是否认证号
    public function mp(){
        return $this->hasOne('CitysMp','uid','uid');
    }

    //是否显示手机号
    public function showphone(){
        return $this->hasOne('CitysPhone','info_id','id');
    }


    //搜索器
    public function searchThemesAttr($query,$value){
        $value = Filter::filter_escape($value);
        if(!empty($value)){
            $query->where('themes','like', '%'. $value .'%');
        }
    }

    /**
     * 图片批量增加处理
     * @return void
     */
    public function getImagesAttr($value){
        $images = empty($value)?[] : $value;
        foreach ($images as $i => $img) {
            $images[$i] = $img;
        }
        return $images;
    }

    /**
     * 锁定
     * @param integer $id
     */
    public static function lock(int $id,$member_miniapp_id){
        $result = self::get($id);
        $data['is_lock'] = $result['is_lock'] ? 0 : 1;
        if($data['is_lock'] == 0) {
            //通知申请者到微信
            Inform::sms($result->uid,$member_miniapp_id,['title' =>'业务进展通知','type' => '同城信息申请','content' =>'您的同城信息申请已经通过审核','state' => '成功']);
        }
        return citys::where('id',$id)->update($data);
    }

   /**
     * 指定
     * @param integer $id
     */
    public static function top(int $id){
        $result = self::where(['id' => $id])->find();
        $data['is_top'] = $result['is_top'] ? 0 : 1;
        return citys::where('id',$id)->update($data);
    }


   /**
     * API的信息列表查询
     * @param integer $id
     */
    public static function apiLists($where,$order,$user,$keyword = ''){
        $rel = citys::with([
            'user' => function($query) {
                $query->field('id,nickname,face');
            },
            'cate' => function($query) {
                $query->field('id,tpl_id,price,title');
            },
            'types' => function($query) {
                $query->field('id,title,price,endtips');
            },
            'mp'   => function($query) {
                $query->field('id,uid,logo,title,is_vip');
            },
            'showphone'   => function($query) use($user){
                $query->field('paid_at,info_id')->where(['uid' => $user->id ?? 0,'paid_at' => 1]);
            }
        ])->withSearch(['themes'],['themes' => $keyword])->where($where)->order($order)->paginate(10);
        $data = [];
        foreach ($rel as $key => $value) {
            $data[$key]                = $value;
            if(empty($value->cate->tpl)){
                $data[$key]['button_name'] = '立即下单';
                $data[$key]['tips']        = '任何有用户发布,下单后请电话再次确认';
                $data[$key]['is_shop']     = 0;
            }else{
                $data[$key]['button_name'] = $value->cate->tpl->button_name;
                $data[$key]['tips']        = $value->cate->tpl->tips;
                $data[$key]['is_shop']     = $value->cate->tpl->is_shop;
            }
            $data[$key]['images']      = $value->images;
            $data[$key]['images_len']  = count($value->images);
            $data[$key]['fields']      = $value->fields;
            $data[$key]['create_time'] = util::ftime($value->create_time);
            $data[$key]['is_mp']       = empty($value->mp)?0:1;
            $data[$key]['showphone']   = empty($value->showphone)?0:1;
            //是否点赞
            $data[$key]['is_like']     = 0; 
            $data[$key]['like_face']   = $value->like_face;
            //判断是否被关注
            $data[$key]['is_follow']   = !empty($value->follow) && ! empty($user)  && $value->follow->uid = $user->id ? 1:0;  
        }
        return $data;  
    }

    //添加或编辑
    public static function postThemes($param){
        $data['themes']            = $param['content'] ?? '';
        $data['telphone']          = $param['telphone'];
        $data['top_money']         = $param['top_money'];
        $data['topday']            = $param['topday'];
        $data['fields']            = $param['fields'];
        $data['images']            = $param['imgs'] ?? [];
        $data['uid']               = $param['uid'];
        $data['cate_id']           = $param['cate_id'];
        $data['type_id']           = $param['type_id'];
        $data['order_no']          = $param['order_no'];
        $data['price']             = $param['price'];
        $data['send_price']        = $param['send_price'];
        $data['create_time']       = time();
        $data['views']             = rand(1,500);
        $data['is_lock']           = $param['is_lock'] ?? 0;
        $data['member_miniapp_id'] = $param['member_miniapp_id'];
        return self::create($data);
    } 
    
    /**
     * 读取信息列表
     * @param integer 读取ID
     * @return json
     */
    public function lists(array $where,int $num = 10){
        $rel = self::where($where)
        ->field('id,is_top,cate_id,cate_name,uid,member_miniapp_id,themes,images,sort,telphone,views,task_money,topday,is_pay,create_time')
        ->order('is_top desc,sort desc,id desc')
        ->paginate($num);     
        $data = [];
        foreach ($rel as $key => $value) {
            $data[$key]             = $value;
            $data[$key]['face']     = $value->user['face'];
            $data[$key]['nickname'] = $value['user']['nickname'];;
            $data[$key]['images']   = empty($value['images']) ? []: json_decode($value['images']);
            $data[$key]['create_time'] = util::ftime($value['create_time']);
        }
        return $data;
    }

    /**
     * 获取某个评论列表
     * @param integer 读取ID
     * @return json
     */
    public function reply(array $where,int $num = 10){
        $rel = self::view('cityinfo_info_reply','id,info_id,uid,reply,create_time')
        ->view('system_user','face,nickname','cityinfo_info_reply.uid = system_user.id')
        ->where($where)
        ->where(['state' => 1])
        ->order('id desc')->paginate($num,true)->toArray();
        $data = $rel['data'];
        foreach ($data as $key => $value) {
            $data[$key]['create_time'] = util::ftime($value['create_time']);
        }
        return $data;
    }
}