<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
/**
 * 用户中心
 */
class Usercenter extends Api
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    //我的搜索历史
    public function search_history(){
        $list = Db::name('user_search')->where('user_id',$this->auth->id)->order('id desc')->select();

        if(!empty($list) && count($list) > 10){
            $list = array_chunk($list,10);
            $list = $list[0];

            $rs_ids = array_column($list,'id');

            Db::name('user_search')->where('user_id',$this->auth->id)->where('id','NOT IN',$rs_ids)->delete();
        }

        $this->success(1,$list);
    }

    //清空搜索历史
    public function search_clear(){
        Db::name('user_search')->where('user_id',$this->auth->id)->delete();
        $this->success(1);
    }


    //我的收藏列表
    public function my_collect()
    {
        $where = [
            'p.is_show' => 1,
            'c.user_id' => $this->auth->id,
        ];

        $list = Db::name('user_collect')->alias('c')
            ->field('p.id,p.name,p.image,p.view_number,p.price,c.createtime')
            ->join('product p','c.product_id = p.id','LEFT')
            ->where($where)
            ->order('c.id desc')
            ->autopage()->select();

        $list = list_domain_image($list,['image']);

        $this->success(1,$list);
    }

    //关注某人
    public function collect_one(){
        $product_id = input('product_id',0);

        if(!$product_id){
            $this->error(__('Invalid parameters'));
        }

        $map = [
            'user_id' => $this->auth->id,
            'product_id' => $product_id,
        ];

        $check = Db::name('user_collect')->where($map)->find();
        if($check){
            //取关
            $rs = Db::name('user_collect')->where($map)->delete();
            $this->success('操作成功');
        }

        $map['createtime'] = time();
        $id = Db::name('user_collect')->insertGetId($map);
        $this->success('操作成功');
    }

}
