<?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>
 * 小程序公共API服务
 */
namespace app\citys\controller\api\v1;
use app\citys\controller\api\Base;
use app\citys\model\CitysCate;
use app\citys\model\CitysType;
use app\citys\model\Citys;
use app\citys\model\CitysReply;
use app\citys\model\CitysConfig;
use app\citys\model\CitysFollow;
use app\citys\model\CitysMp;
use app\citys\model\MchId;
use app\common\facade\WechatPay;
use app\common\facade\Upload;
use app\common\model\SystemUser;
use think\facade\Config;
use filter\Filter;

class Send extends Base{

    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }


    /**
     * 获取配置参数
     * @return void
     */
    public function getconfig(){
        $this->apiSign();
        $result = CitysConfig::config($this->member_miniapp_id);
        if(empty($result)){
            return enjson(204);
        }else{
            return enjson(200,$result->top);
        }
    }
    
    /**
     * VIP认证
     */
    public function isVip(){
        if(request()->isPost()){
            $rel = CitysMp::where(['uid' => $this->user->id,'is_lock' => 0,'is_vip' => 1])->count();
            if($rel){
                return enjson(200,'认证用户',['vip'=>1]);
            }
        }
        return enjson(200,'非认证用户',['vip'=>0]);
    }

    /**
     * 编辑开通城市号和申请认证城市号
     *
     * @return void
     */
    public function editMp(){
        $param['logo']      = $this->request->param('logo/s');
        $param['skin']      = $this->request->param('skin/s');
        $param['title']     = $this->request->param('title/s');
        $param['note']      = $this->request->param('note/s');
        $param['telphone']  = $this->request->param('telphone/s');
        $param['vip_title'] = $this->request->param('vip_title/s','');
        $param['vip_about'] = $this->request->param('vip_about/s','');
        $param['checked']   = $this->request->param('checked/d',0);
        $this->apiSign($param);
        $data['title'] = $param['title'];
        $data['note']  = $param['note'];
        $rel = CitysMp::where(['uid' => $this->user->id])->find();
        if($rel){
            if($rel->is_lock){
                return enjson(403,'帐号已被锁定');
            }
            //判断是否修改skin
            $rel->note = $param['note'];
            $rel->title = $param['title'];
            //判断是否修改skin
            if(!empty($param['skin'])){
                $rel->skin = $param['skin'];
            }
            //判断是否修改logo
            if(!empty($param['logo'])){
                $rel->logo = $param['logo'];
            }
            if(!$rel->is_apply && !$rel->is_vip){
                $rel->is_apply  = $param['checked'] ? 1 : 0;
                $rel->vip_title = $param['vip_title'];
                $rel->vip_about = $param['vip_about'];
            }
            $result = $rel->save();
            if($result){
                return enjson(200,'信息设置成功');
            }
        }else{
            $data['member_miniapp_id']  = $this->member_miniapp_id;
            $data['uid']                = $this->user->id;
            $data['is_apply']           = $param['checked'] ? 1 : 0;
            $data['vip_title']          = $param['vip_title'];
            $data['vip_about']          = $param['vip_about'];
            $data['reg_time']           = time();
            $data['vip_time']           = time();
            $data['fans']               = CitysFollow::where(['uid' => $this->user->id])->count();
            $data['logo']               = empty($param['logo']) ? $this->user->face: $param['logo'];
            $data['skin']               = empty($param['skin']) ? Config::get('upload.upload_relative').'static/citys/skin/2.jpg':$param['skin'];
            $data['is_vip']             = 0;
            $result = CitysMp::create($data);
            if($result){
                return enjson(200,'帐号开通成功');
            }
        }
        return enjson(403,'设置失败');
    }

    /**
     * 发表信息
     */
    public function send(){  
        if(request()->isPost()){
            $param =  [
                'content'  => $this->request->param('content/s'),
                'telphone' => $this->request->param('telphone/s',''),
                'topday'   => $this->request->param('topday/d',0),
                'cate_id'  => $this->request->param('cate_id/d',0),
                'type_id'  => $this->request->param('type_id/d',0),
                'imgs'     => $this->request->param('imgs/s','[]','htmlspecialchars_decode'),
                'fields'   => $this->request->param('fields/s','[]','htmlspecialchars_decode'),
                'is_get'   => $this->request->param('is_get/d',0),
                'price'    => $this->request->param('price/d'),
                'sign'     => $this->request->param('sign/s',0),
            ];
            $this->apiSign($param);
            $param['member_miniapp_id'] = $this->miniapp_id;
            $param['uid']               = $this->user->id;
            $validate = $this->validate($param,'Info.send');
            if(true !== $validate){
                return json(['code'=>403,'msg'=>$validate]);
            }
            $param['imgs']   = array_column(Filter::filter_escape(json_decode($param['imgs'],true)),'url');
            $param['fields'] = Filter::filter_escape(json_decode($param['fields'],true));
            //置顶
            $amount = 0;
            $config = CitysConfig::config($this->miniapp_id);
            if($param['topday'] && !empty($config)){
                foreach ($config->top as $value) {
                    if($value['day'] == $param['topday']){
                        $amount          = $value['money'];
                        $param['topday'] = $value['day'];
                    }
                }
            }
            $param['top_money'] = $amount; //置顶金额
            $param['order_no']  = $this->user->invite_code.order_no();
            $rel = CitysType::where(['member_miniapp_id' => $this->member_miniapp_id,'id' => $param['type_id']])->find();
            $cate = CitysCate::where(['member_miniapp_id' => $this->member_miniapp_id,'id' => $param['cate_id']])->find();
            $price = $rel->price+$cate->price;  //发布价格
            $param['send_price'] = $price;
            $param['is_lock']    = $price > 0 ? 1 : 0;
            $result = Citys::postThemes($param);
            if($result){
                if($price> 0 && $amount > 0){
                    $msg = '信息发布与推广费';
                }elseif($price > 0 && $amount = 0){
                    $msg = '信息发布费';
                }else{
                    $msg = '信息推广费';
                }
                $amount = $amount+$price;
                if($amount > 0){
                    $order = [
                        'openid'     => $this->user['miniapp_uid'],
                        'miniapp_id' => $this->miniapp_id,
                        'name'       => '信息置顶',
                        'order_no'   => $param['order_no'],
                        'total_fee'  => $amount*100,
                        'notify_url' => api(1,'citys/notify/index',$this->miniapp_id)
                    ];
                    //读取配置
                    if($this->member_miniapp->is_psp){
                        if (empty($config->mch_id)) {
                            return enjson(403,'服务商模式下,必须配置默认商户号');
                        }
                        $order['mchid'] = $config->mch_id;  
                    }
                    $ispay = WechatPay::orderPay($order);;
                    if($ispay['code'] == 0){
                        return json(['code'=>403,'msg'=>$ispay['msg']]);
                    }
                    return enjson(200,'发布成功,内容需审核!',$ispay['data']);
                }else{
                    return enjson(204,'发布成功,内容需审核!');
                }
            }else{
                return enjson(403,'发布失败');
            }
        }
    }
    
    /**
     * 点赞
     **/
    public function onLike(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $rel = Citys::where($condition)->find();
        $like_face = empty($rel->like_face) ? [] : $rel->like_face;
        if(count($like_face) < 10){
            if(!in_array($this->user->face,$like_face)){
                array_push($like_face,$this->user->face);
                $rel->like_face = $like_face;
            }
        } 
        $rel->like = ['inc',rand(10,200)];
        $rel->save();
        if(empty($rel)){
            return enjson(403,'不用重复点赞');
        }else{
            return enjson(200);
        }
    }

    /**
     * 可以已关闭当前信息
     **/
    public function onClose(){
        $param['id'] = $this->request->param('id/d',0);
        $this->apiSign($param);
        $condition['id']  = $param['id'];
        $condition['uid'] = $this->user->id;
        $rel = Citys::where($condition)->find();
        if(empty($rel)){
            return enjson(403,'未找到你的信息');
        }else{
            $rel->is_end = 1;
            $rel->save();
            return enjson(200);
        }
    }

    /**
     * 信息单独置顶
     */
    public function onTop(){
        $param['id']  = $this->request->param('id/d',0);
        $param['day'] = $this->request->param('day/d',0);
        $this->apiSign($param);
        $condition['id']  = $param['id'];
        $condition['uid'] = $this->user->id;
        $rel = Citys::where($condition)->find();
        if(empty($rel)){
            return enjson(403,'未找到你的信息');
        }else{
            //置顶
            $amount = 0;
            $config = CitysConfig::config($this->miniapp_id);
            foreach ($config->top as $value) {
                if($value['day'] == $param['day']){
                    $amount = $value['money'];
                    $topday = $value['day'];
                }
            }
            if($amount > 0){
                $rel->topday    = $topday;
                $rel->top_money = $amount;
                $rel->order_no  = order_no($this->user->invite_code);
                $rel->save();
                $order = [
                    'openid'     => $this->user->miniapp_uid,
                    'miniapp_id' => $this->miniapp_id,
                    'name'       => '信息置顶',
                    'order_no'   => $rel->order_no ,
                    'total_fee'  => $amount,
                    'notify_url' => api(1,'citys/notify/index',$this->miniapp_id)
                ];  
                //读取配置
                if($this->member_miniapp->is_psp){
                    if (empty($config->mch_id)) {
                        return enjson(403,'服务商模式下,必须配置默认商户号');
                    }
                    $order['mchid'] = $config->mch_id;  
                }
                $ispay = WechatPay::orderPay($order);;
                if($ispay['code'] == 0){
                    return json(['code'=>403,'msg'=>$ispay['msg']]);
                }
                return enjson(200,$ispay['data']);
            }else{
                return enjson(403,'信息置顶异常');
            }
        }
    }

    /**
     * 关注或取消
     */
    public function onFollow(){
        $param['uid']   = $this->request->param('uid/d');
        $param['state'] = $this->request->param('state/d',0);
        $this->apiSign($param);
        if($param['uid'] == $this->user->id){
            return enjson(403,'不用关注自己');
        }
        //判断关注用户是否存在
        $is_user = SystemUser::where(['id' => $param['uid'],'is_lock' => 0,'is_delete' => 0])->find();
        if(empty($is_user)){
            return enjson(403,'当前用户已被封号');
        }
        //关注
        $condition['like_uid'] = $param['uid'];
        $condition['uid']      = $this->user->id;
        $info = CitysFollow::where($condition)->find();
        if(empty($info)){
            $follow = CitysFollow::where(['uid' => $this->user->id,'like_uid' => 0])->find();
            if($param['state'] == 1){
                if(empty($follow)){
                    $rel  = CitysFollow::create(['uid' => $this->user->id,'like_uid' => $param['uid']]);
                }else{
                    $follow->like_uid = $param['uid'];
                    $rel  = $follow->save();
                }
            }else{
                return enjson(403,'关注失败');
            }
        }else{
            if($param['state'] == 0){
                $info->like_uid = 0;
                $rel  = $info->save();
            }
        }
        if(empty($rel)){
            return enjson(403,'关注失败');
        }else{
            $infomp = CitysMp::where(['uid' => $param['uid']])->find();
            if($infomp){
                if($param['state']){
                    $infomp->fans = ['inc',1];
                }else{
                    $infomp->fans = ['dec',1];
                }
                $infomp->save();
            }
            return enjson(200,$param['state']?'已关注':'取消关注');
        }
    }

    /**
     * 发布评论
     */
    public function postReply(){
        if(request()->isPost()){
            $param['content'] = $this->request->param('content/s');
            $param['id']      = $this->request->param('id/s');
            $this->apiSign($param);
            $data = [
                'content'           => $param['content'],
                'info_id'           => $param['id'],
                'uid'               => $this->user->id,
                'member_miniapp_id' => $this->member_miniapp_id,
            ];
            $validate = $this->validate($data,'Info.sendReply');
            if(true !== $validate){
                return enjson(403,$validate);
            }
            $result =  CitysReply::postReply($data);
            if($result){
                $result->info->reply_num = ['inc',1];
                $result->info->save();
                return enjson(200,'评论成功');
            }else{
                return enjson(403,'评论失败');
            }
        }
    }

    /**
     * 评论点赞
     * @return void
     */
    public function onReplylike(){
        $param['id']   = $this->request->param('id/d',0);
        $param['sign'] = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['member_miniapp_id'] = $this->miniapp_id;
        $condition['id']                = $param['id'];
        $rel = CitysReply::where($condition)->setInc('like',1);
        if(empty($rel)){
            return enjson(403,'不用重复点赞');
        }else{
            return enjson(200);
        }
    }
}