<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-31 20:43
// +----------------------------------------------------------------------

namespace app\system\controller\v1;


use app\BaseController;
use app\model\api\MemberDetail;
use app\model\system\Member as MemberModel;
use app\model\system\MemberFollow;
use app\model\system\MemberLevel;
use library\services\UtilService;
use library\utils\IpLocation;
use app\Request;

class Member extends  BaseController
{
    /**
     *
     * @param Request $request
     * @return mixed
     */
    public function getMember(Request $request)
    {
        $pageSize = 50;
        $post = UtilService::getMore([
            ['page',1],
            ['keyword',''],
            ['i_uid',''],
            ['sassid',''],
            ['mobile',''],
            ['level',''],
            ['uid',''],
            ['follow_type',''],
            ['timeVal',[]],
            ['not_buy',''],
            ['label',''],
            ['admin_id',''],
            ['not_follow',''],
            ['lately_login',''],
            ['type','']
        ]);
        list($pageCount,$data) = (new MemberModel())
            ->getList($post['page'],$post,$pageSize,'*','uid desc');
        $result = UtilService::getParam([
            'uid',
            'mobile',
            'label',
            'weixin_name',
            'nickname',
            'sex',
            'avatar',
            'address',
            'money',
            'name',
            "tx_money",
            "level_name",
            "site_name",
            'status',
            'follow_type',
            'levelid',
            'order_count',
            'recharge_count',
            'order_info_count',
            ['last_con_time','last_con_time','getLastTime($1)'],
          //  'i_mobile',
            'i_nickname',
            'i_uid',
            'sassid',
            'regip',
            ['regtime','regtime','date("Y-m-d H:i:s",$1)'],
            ['lasttime','lasttime','date("Y-m-d H:i:s",$1)'],
            ['ipara','regip',function($item){
                return  (new IpLocation())->getlocation($item)['country'];
            }],
            'last_follow_time'
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }



    public function down(Request $request) {
        $where = UtilService::getMore([
            ['page',1],
            ['keyword',''],
            ['i_uid',''],
            ['sassid',''],
            ['mobile',''],
            ['level',''],
            ['uid',''],
            ['follow_type',''],
            ['timeVal',[]],
            ['not_buy',''],
            ['label',''],
            ['admin_id',''],
            ['not_follow',''],
            ['lately_login',''],
            ['type','']
        ]);
        $data = (new MemberModel())

            ->field("m.*,s.name as site_name,l.name as level_name,
            (select count(*) from table_order where uid = m.uid and status > 0) as order_count,
            (select sum(v) from table_recharge where status = 1 and uid = m.uid ) as recharge_count,
            (select count(*) from table_order_info where status > 0 and uid = m.uid ) as order_info_count,
            (select nickname from table_member where uid = m.i_uid) as i_nickname
            "
            )
            ->alias("m")
            ->join('site s','s.sassid=m.sassid')
            ->leftJoin("member_level l","l.id=m.levelid")
            ->when(!empty($where),function ($query) use($where){
                //keyword
                if(!empty($where['keyword'])) {
                    $query->whereLike('m.nickname',"%{$where['keyword']}%");
                }

                if(!empty($where['timeVal'][0]) && !empty($where['timeVal'][1])) {
                    $query->where('regtime','>',strtotime($where['timeVal'][0]));
                    $query->where('regtime','<',strtotime($where['timeVal'][1]));
                }

                if(!empty($where['not_buy'])) {

                    //今日消费
                    if($where['not_buy'] == 'today') {
                        $query->whereTime("last_con_time",'today');
                    }

                    //7天内消费
                    if($where['not_buy'] == '1_7day') {
                        $time = time() - 6*24*3600;
                        $query->where("last_con_time",'>',$time);
                        $query->order("last_con_time","desc");
                    }

                    //7-13天未消费
                    if($where['not_buy'] == '7day') {
                        $time = time() - 13*24*3600;
                        $times = time() - 6*24*3600;
                        $query->where("last_con_time",'>',$time);
                        $query->where("last_con_time",'<',$times);
                        $query->order("last_con_time","desc");
                    }

                    //14天未消费
                    if($where['not_buy'] == '14day') {
                        $time = time() - 13*24*3600;
                        $query->where("last_con_time",'<',$time);
                        $query->where("last_con_time",'<>',0);
                        $query->order("last_con_time","desc");
                    }

                    //1个月未消费
                    if($where['not_buy'] == 'month') {
                        $time = strtotime('-1 month');
                        $query->where("last_con_time",'<',$time);
                        $query->where("last_con_time",'<>',0);
                        $query->order("last_con_time","desc");
                    }

                    //从无消费
                    if($where['not_buy'] == 'nothing') {
                        $query->where("last_con_time",0);
                    }
                }


                if(!empty($where['mobile'])) {
                    $query->whereLike('m.mobile',"%{$where['mobile']}%");
                }

                if(!empty($where['level'])) {
                    $query->where('m.levelid',$where['level']);
                }

                if(strlen($where['follow_type']) > 0) {
                    $query->where('m.follow_type',$where['follow_type']);
                }


                if(!empty($where['sassid'])) {
                    //判断是否多个
                    $sassIds = explode(',',(string)$where['sassid']);
                    if(count($sassIds) > 1)
                        $query->whereIn('m.sassid',$sassIds);
                    else
                        $query->where('m.sassid',$where['sassid']);
                }

                if(!empty($where['i_uid'])) {
                    $query->where('m.i_uid',$where['i_uid']);
                }

                if(!empty($where['uid'])) {
                    $query->where('m.uid',$where['uid']);
                }

                if(!empty($where['label'])) {
                    $query->where('m.label',$where['label']);
                }

                if(!empty($where['admin_id'])) {
                    $query->where('m.admin_id',$where['admin_id']);
                }

                if(!empty($where['not_follow'])) {
                    if($where['not_follow']=='3day'){
                        $time = time() - 3*24*3600;
                        $query->where("last_follow_time",'<',$time);
                    }else{
                        $time = time() - 7*24*3600;
                        $query->where("last_follow_time",'<',$time);
                    }
                }

                if(!empty($where['lately_login'])) {
                    $time = time() - 3*24*3600;
                    $query->where("lasttime",'>',$time);
                }

                if(!empty($where['type'])) {
                    if($where['type']=='new'){
                        $query->where("last_con_time",'=',0);
                    }else{
                        $query->where("last_con_time",'<>',0);
                    }
                }

            })
            ->order('uid desc')
            ->select()
            ->toArray();

        $result = UtilService::getParam([
            'uid',
            'mobile',
            'weixin_name',
            'nickname',
            'sex',
            'avatar',
            'address',
            'money',
            'name',
            "tx_money",
            "level_name",
            "site_name",
            'status',
            'follow_type',
            'levelid',
            'order_count',
            'recharge_count',
            'order_info_count',
            //  'i_mobile',
            'i_nickname',
            'i_uid',
            'sassid',
            'regip',
            ['regtime','regtime','date("Y-m-d H:i:s",$1)'],
            ['lasttime','lasttime','date("Y-m-d H:i:s",$1)'],
            ['ipara','regip',function($item){
                return  (new IpLocation())->getlocation($item)['country'];
            }]
        ],$data);
        return app('json')->success($result);
    }
    /**
     * 获取会员数据
     * @param Request $request
     * @return mixed
     */
    public function getItem(Request $request)
    {
        $pageSize = 50;
        $post = UtilService::getMore([
            ['uid',1]
        ]);
        $data = (new MemberModel())->getItem($post['uid']);
        $result = UtilService::getParam([
            'uid',
            'mobile',
            'nickname',
            'sex',
            'avatar',
            'address',
            'money',
            'name',
            "tx_money",
            "level_name",
            "site_name",
            'status',
            'levelid',
            'order_count',
            'recharge_count',
            'order_info_count',
            'regip',
            ['regtime','regtime','date("Y-m-d H:i:s",$1)'],
            ['lasttime','lasttime','date("Y-m-d H:i:s",$1)'],
            ['ipara','regip',function($item){
                return  (new IpLocation())->getlocation($item)['country'];
            }]
        ],[$data]);
        return app('json')->success(empty($result) ? [] : $result[0]);
    }
    /**
     * 会员等级
     * @param Request $request
     * @return mixed
     */
    public function getMemberLevel(Request $request)
    {
        $pageSize = 50;
        $post = UtilService::getMore([
            ['page',1]
        ]);
        list($pageCount,$data) = (new MemberLevel())
            ->getList($post['page'],[function($query) use($post){
                
        }
        ],$pageSize,'*','id desc');
        $result = UtilService::getParam([
            'id',
            'name',
            'code'
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    /**
     * 获取跟进管理员
     */
    public function getAdmin()
    {
        $admin = MemberFollow::alias("f")
            ->leftjoin('system_admin a','f.admin_id=a.id')
            ->field('a.id,a.name,a.username')
            ->where('a.id','<>','')
            ->group('f.admin_id')
            ->select()->toArray();
        return app('json')->success($admin);
    }

    /**
     * 修改会员数据
     * @param Request $request
     */
    public function memberUpdate(Request $request) {
        $post = UtilService::getMore([
            ['levelid','0'],
            ['mobile','','isMobile','请输入手机号码'],
            ['nickname',''],
            ['status','0'],
            ['name',''],
            ['password',''],
            ['avatar',''],
            ['sex','0'],
            ['uid','0','empty','参数错误']
        ], $request);
        $save = [
            'mobile'    => $post['mobile'],
            'nickname'  => $post['nickname'],
            'sex'       => $post['sex'],
            'name'      => $post['name'],
            'levelid'   => $post['levelid'],
            'status'    => $post['status'],
            'avatar'    => $post['avatar']
        ];

        if(!empty($post['password'])) {
           $save['password'] = md5($post['password']);
        }
        //
        (new MemberModel)->where('uid',$post['uid'])->save($save);
        return app('json')->success('修改成功');
    }
    /**
     * 操作明细
     * @param Request $request
     */
    public function detailList(Request $request) {
        $pageSize = 10;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['uid','0'],
                ['time',[]]
            ],$request
        );
        $where['uid'] = $post['uid'];
        if(!empty($post['tabType']) && $post['tabType'] != 'all') {
            $where['code'] = $post['tabType'];
        }

        if(!empty($post['time'])) {
            $where['time'] = [[strtotime($post['time'][0]),strtotime($post['time'][1])],'whereBetween'];
        }

        $detail = new MemberDetail();
        list($pageCount,$data) = $detail->getList($post['page'],$where,$pageSize,"*","time desc");
        $result = UtilService::getParam([
            "id",
            "code",
            "v",
            'title',
            'content',
            "type",
            ["time","time","date('Y-m-d H:i:s',$1)"]
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    /**
     * 修改推荐人
     * @param Request $request
     */
    public function editTj(Request $request) {
        $post =  UtilService::getMore(
            [
                ['uid','','empty','参数错误'],
                ['i_uid','0']
            ],$request
        );
        if($post['uid'] == $post['i_uid']) {
            return app('json')->fail('自己无法挂载自己下面');
        }

        (new \app\model\system\Member)->where('uid',$post['uid'])->save(['i_uid'=>$post['i_uid']]);
        return app('json')->success('操作成功');
    }

    /**
     * 转账操作
     */
    public function sendMoney(Request $request){
        $post =  UtilService::getMore(
            [
                ['uid','','empty','参数错误'],
                ['type','','empty','请输入转账类型'],
                ['money','0','empty','请输入转账金额'],
                ['mono','']
            ],$request
        );
        $member = \app\model\system\Member::where('uid',$post['uid'])->find();
        if(empty($member)) {
            return app('json')->fail('找不到用户数据');
        }
        $detail = new MemberDetail();
        //减少
        if($post['type'] == 'jdd') {
            $detail->adminInc(
                $post['money'],
                $post['uid'],
                ['time'=>date('Y-m-d'),'money'=>$post['money'],'mono'=>empty($post['mono']) ? '无': $post['mono']],
                $member['sassid'],
                $post['type']
            );
        }
        //添加
        if($post['type'] == 'add') {
            $detail->adminInc(
                $post['money'],
                $post['uid'],
                ['time'=>date('Y-m-d'),'money'=>$post['money'],'mono'=>empty($post['mono']) ? '无': $post['mono']],
                $member['sassid'],
                $post['type']
            );
        }

        return app('json')->success('操作成功');
    }


    /**
     * 操作明细
     * @param Request $request
     */
    public function followUpList(Request $request) {
        $pageSize = 5;
        $post =  UtilService::getMore(
            [
                ['page',1],
                ['uid','0'],
                ['time',[]]
            ],$request
        );
        $where['uid'] = $post['uid'];

        if(!empty($post['time'])) {
            $where['time'] = [[strtotime($post['time'][0]),strtotime($post['time'][1])],'whereBetween'];
        }

        $detail = new MemberFollow();
        list($pageCount,$data) = $detail->getList($post['page'],$where,$pageSize,"*","time desc");
        $result = UtilService::getParam([
            "id",
            'title',
            'content',
            "type",
            ['name',"username"],
            ["time","time","date('Y-m-d H:i:s',$1)"]
        ],$data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page']
        ]);
    }

    /**
     * 会员跟进
     * @param Request $request
     */
    public function followUpSave(Request $request) {
        $post = UtilService::getMore(
            [
                ['uid','','empty','参数错误'],
                ['title','','empty','参数错误'],
                ['content','','empty','参数错误'],
                ['type','0'],
            ],$request
        );
        $user = (new \app\model\system\Member)->where('uid',$post['uid'])->find();
        if(empty($user))
            return app('json')->fail('参数错误');
        $memberFollow = new MemberFollow;
        $memberFollow->insert([
            'uid' => $post['uid'],
            'title' => $post['title'],
            'content' => $post['content'],
            'admin_id' => $this->request->adminInfo['id'],
            'time' => time(),
            'sassid' =>$user['sassid'],
            'type' => $post['type']
        ]);
        (new \app\model\system\Member)->where('uid',$post['uid'])->save(['follow_type'=>$post['type'],'last_follow_time'=>time()]);

        return app("json")->success('操作成功');

    }

}