<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */
namespace app\api\controller\twoshop;


use app\api\logic\twoshop\GoodsLogic;
use app\common\model\RealVerify;
use app\common\model\TwoAfterSale;
use app\common\model\TwoChatRecord;
use app\common\model\TwoGoods;
use app\common\service\ConfigService;

class User extends \app\api\controller\BaseShopController
{
    public function chat()
    {
        $params = $this->request->param();

        $goods = TwoGoods::where('id', $params['id'])->find();

        if ($goods) {
            $record = TwoChatRecord::where([
                ['goods_id', '=', $goods->id],
                ['user_id', '=', $this->userId]
            ])->find();

            if (!$record && $this->userId != $goods->user_id) {
                TwoChatRecord::create([
                    'goods_id' => $goods->id,
                    'user_id' => $this->userId,
                    'to_user_id' => $goods->user_id
                ]);

                $goods->inc('want_count')->save();
            }
        } else {
            return show(0,'商品不存在');
        }

        return show(1,'成功');
    }

    public function info($id)
    {
        return show(1,'信息',[
            'seller_comment' => GoodsLogic::avgComment($id),
            'buyer_comment' => GoodsLogic::avgComment($id, 'user_id'),
            'rate' => GoodsLogic::getCommentRate($id)
        ]);
    }

    public function time($id)
    {
        if (isActivePluginByPluginName('realverify')) {
            $mustVerifiedTypeId = ConfigService::get('twoshop', 'must_verified_type_id', 0);

            if (!empty($mustVerifiedTypeId)) {
                $realVerifyRecord = RealVerify::where('user_id', $id)->whereIn('type_id', explode(',', $mustVerifiedTypeId))->where('status', 1)->find();

                if (empty($realVerifyRecord)) {
                    $time1 = null;
                } else {
                    $time1 = strtotime($realVerifyRecord->create_time);
                }
            } else {
                $time1 = null;
            }
        } else {
            $time1 = null;
        }

        $firstGoods = \app\common\model\TwoGoods::where('user_id', $id)->order('create_time', 'asc')->find();

        if (!empty($firstGoods)) {
            $time2 = strtotime($firstGoods->create_time);
        } else {
            $time2 = null;
        }

        $time = min(
            array_filter([$time1, $time2], function($v) {
                return !is_null($v);
            })
        );

        return show(1, '时间', [
            'time' => $time
        ]);
    }

    public function comments($id)
    {
        $params = $this->request->param();

    if (!isset($params['type'])) {
        $params['type'] = 0;
    }

    $query = \app\common\model\TwoGoodsComment::with(['user']);

        $where = [
            ['status','=',1]
        ];

        if (isset($params['type'])) {
            if ($params['type'] == 0) {
                $where[] = ['user_id','=',$id];
            }

            if ($params['type'] == 1) {
                $query = $query->where('sell_user_id', $id)
                    ->whereOr(function ($q) use ($id) {
                        $q->where('user_id', $id)
                            ->whereNotNull('reply');
                    });
            }

            if ($params['type'] == 2) {
                $where[] = ['goods_comment|service_comment|description_comment|express_comment','>',3];
            }
        }

        $data = $query
            ->where($where)
            ->paginate(10);

        foreach ($data as &$item) {
            if (!empty($item['user'])) {
                $item['user']['location'] = \app\common\model\User::where('id', $item['user']['id'])->value('ip_address');
            }
        }

        return show(1,'评论列表',$data);
    }

    /**
     * 我的发布
     */
    public function goods()
    {
       $list = \app\common\model\TwoGoods::where('user_id',$this->userId)
       ->select();

       return show(1,'我的发布',$list);
    }

    /**
     * 我卖出的订单
     */
    public function sellOrder()
    {
        $params=$this->request->param();
        $where= [];
        if(isset($params['type'])){
            $where[] = ['order_status','=',$params['type']];
        }
       $list = \app\common\model\TwoOrder::with(['order_goods', 'user'])
           ->where($where)
       ->where('sell_user_id',$this->userId)
       ->select();

       return show(1,'我卖出的',$list);
    }
    
    /**
     * 我买到的订单
     */
    public function buyOrder()
    {
        $params = $this->request->param();

        $where = [];

        if (isset($params['type'])) {
            if ($params['type'] == 'refund_ing') {
                $where[] = [
                    'id', 'in',
                    TwoAfterSale::where('refund_method', 1)->where('status', 1)->column('order_id')
                ];
            }
        }

       $list = \app\common\model\TwoOrder::with(['order_goods', 'user'])
       ->where('user_id',$this->userId)
           ->where($where)
       ->select();

       return show(1,'我买到的订单',$list);
    }

    /**
     * 商品日志
     * Summary of goodsLog
     * @return \think\response\Json
     */
    public function goodsLog()
    {
        $list = \app\common\model\TwoGoodsLog::with('goods')->where('user_id',$this->userId)
        ->order('create_time','desc')
        ->paginate(10);

       return show(1,'商品动态',$list);
    }

    /**
     * 删除商品动态
     * Summary of delGoodsLog
     * @param mixed $id
     * @return \think\response\Json
     */
    public function delGoodsLog($id)
    {
        $res = \app\common\model\TwoGoodsLog::where('id',$id)
        ->delete();
        if ($res) {
            return show(1,'删除成功');
        }
        return show(0,'删除失败');
    }

    /**
     * 我收到的评论列表
     */
    public function commentList()
    {
        $where = [];
        $list = \app\common\model\TwoGoodsComment::with(['goods','user'])->where('sell_user_id',$this->userId)
        ->where( $where)
        ->order('create_time','desc')
        ->paginate(10);

       return show(1,'我收到的评论列表',$list);
    }

    

}