<?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\allwin\model;
use app\common\facade\Inform;
use app\allwin\model\Levels;
use app\allwin\model\Vip;
use think\Model;
use util\Util;
use filter\Filter;
use think\db\Where;

class AllwinInfo extends Model{

    protected $pk = 'id';

    //用户
    public function user(){
        return $this->hasOne('app\common\model\SystemUser','id','user_id');
    }
    
    //一对多管理回复的评论
    public function comments(){
        return $this->hasMany('AllwinInfoReply','info_id','id');
    }

    //所属栏目
    public function cate(){
        return $this->hasOne('AllwinInfoCate','id','cate_id');
    }

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

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

    /**
     * 锁定
     * @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->user_id,$member_miniapp_id,['title' =>'业务进展通知','type' => '同城信息申请','content' =>'您的同城信息申请已经通过审核','state' => '成功']);
        }
        return AllwinInfo::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 AllwinInfo::where('id',$id)->update($data);
    }


   /**
     * API的信息列表查询
     * @param integer $id
     */
    public static function apiLists($where,$order,$user,$keyword = ''){
        $rel = AllwinInfo::with([
            'user' => function($query) {
                $query->field('id,nickname,face');
            },
            'cate' => function($query) {
                $query->field('id,tpl_id,title');
            },
            'mp'   => function($query) {
                $query->field('id,uid,logo,title,is_vip');
            }
        ])->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;
            }
            $images                    = empty($value->images) ? [] : json_decode($value->images,true);
            foreach ($images as $i => $img) {
                $images[$i] = $img.'?x-oss-process=style/300';
            }
            $data[$key]['images']      = $images;
            $data[$key]['images_len']  = count($images);
            $data[$key]['fields']      = empty($value->fields) ? [] : json_decode($value->fields,true);
            $data[$key]['create_time'] = util::ftime($value->create_time);
            $data[$key]['is_mp']       = empty($value->mp)?0:1;
            //是否点赞
            $data[$key]['is_like']     = 0; 
            $data[$key]['like_face']   = empty($value->like_face) ? [] : json_decode($value->like_face,true);
            //判断是否被关注
            $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['user_id']           = $param['user_id'];
        $data['cate_id']           = $param['cate_id'];
        $data['store_id']          = $param['store_id'];
        $data['order_no']          = $param['order_no'];
        $data['price']             = (int)$param['price'];
        $data['create_time']       = time();
        $data['views']             = rand(1,500);
        $data['is_lock']           = 1;
        $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,user_id,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('allwin_info_reply','id,info_id,user_id,reply,create_time')
        ->view('system_user','face,nickname','allwin_info_reply.user_id = 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;
    }
    
   /**
     * 信息发布获利
     * @param integer $miniapp_id   来源小程序
     * @param integer $uid  用户ID
     * @param float $cash_fee  (分)
     * @param [type] $config  系统配置
     * @return void
     */
    public static function sendinfo($order){
        $level  = Levels::where(['user_id' => $order->user_id,'level'=>[1,2]])->select();
        $level1 = 0;
        $level2 = 0;
        foreach ($level as $value) {
            if ($value['level'] == 1) {
                $level1 = $value['parent_id'];
            }
            if ($value['level'] == 2) {
                $level2 = $value['parent_id'];
            }
        }
        $config = AllwinInfoConfig::config($order->member_miniapp_id);
        if ($level1) {
            $rel1 = Vip::where(['user_id' => $level1,'state'=>1,'is_lock' =>0])->field('user_id')->find();
            if (!empty($rel1)) {
                $bring = intval($order->top_money*($config->bring/100));
                $l1_money = (float)money($bring/100);
                if ($l1_money > 0) {
                    Bank::dueMoney($order->member_miniapp_id,$level1,$l1_money);
                    BankBill::add(['miniapp_id'=>$order->member_miniapp_id,'store_id' => 0,'money'=>$l1_money,'uid'=>$level1,'pay_uid' => $order->user_id],'同城推荐奖励');
                }
            }
        }
        if ($level2) {
            $rel2 = Vip::where(['user_id' => $level2,'state'=>1,'is_lock' => 0])->field('user_id')->find();
            if (!empty($rel2)) {
                $reward = intval($order->top_money*($config->reward/100));
                $l2_money = (float)money($reward/100);
                if ($l2_money > 0) {
                    Bank::dueMoney($order->member_miniapp_id,$level2,$l2_money);
                    BankBill::add(['miniapp_id' => $order->member_miniapp_id,'store_id' => 0,'money'=> $l2_money,'uid'=>$level2,'pay_uid' =>$order->user_id],'同城推荐奖励');
                }
            }
        }
    }
}