<?php

namespace app\controller\api\v1;

use app\controller\api\Base;
use app\model\Account;
use app\model\GoodsArea;
use app\model\GoodsCategory;
use think\Collection;
use think\facade\Log;
use think\response\Json;

class Goods extends Base
{
    protected $noNeedLogin = [
        'list', 'detail', 'category', 'area'
    ];

    // 物品列表
    public function list(): Json
    {
        $page       = input('page/d', 1);
        $size       = input('size/d', 20);
        $keyword    = input('keyword/s');
        $categoryId = input('category_id/d', 0);
        $areaId     = input('area_id/d', 0);

        $where = [];

        if (!empty($keyword)) {
            $where[] = ['a.nickname|g.title|gc.title|g.phone|ga.title', 'like', '%'.$keyword.'%'];
        }

        if ($categoryId > 0) {
            $where[] = ['g.category_id', '=', $categoryId];
        }

        if ($areaId > 0) {
            $where[] = ['g.area_id', '=', $areaId];
        }

        $where[] = ['g.status', '=', 0];//进行中

        $query = \app\model\Goods::alias('g')
            ->leftJoin('goods_category gc', 'gc.id = g.category_id')
            ->leftJoin('account a', 'a.id = g.account_id')
            ->leftJoin('goods_area ga', 'ga.id = g.area_id')
            ->field('g.id,g.cover,g.title,g.images,price,original_price')
            ->where($where);

        $total = $query->count();

        $res = [
            'total'   => $total,
            'current' => $page ?: 1,
            'size'    => $size ?: 20,
            'list'    => new Collection(),
        ];

        if ($total > 0) {
            $res['list'] = $query->page($page, $size)->order('g.sort', 'desc')->order('g.id', 'desc')->select();
            $domain      = request()->domain(true);
            $res['list']->each(function ($item) use ($domain) {
                $item->cover = resourceJoin((string) $item->cover, $domain);
                $images      = explode(',', $item->images);
                foreach ($images as $k => $img) {
                    if (!empty($img)) {
                        $images[$k] = resourceJoin($img, $domain);
                    } else {
                        unset($images[$k]);
                    }
                }
                $item->images = $images;
            });
        }

        return $this->json(0, 'success', $res);
    }

    // 物品详情
    public function detail(): Json
    {
        $id = input('id/d', 0);

        $field = 'g.id,g.title,g.cover,g.images,g.content,g.price,g.original_price,g.phone,ga.title as area_name,gc.title as category_name';

        $item = \app\model\Goods::alias('g')
            ->leftJoin('goods_area ga','ga.id = g.area_id')
            ->leftJoin('goods_category gc','gc.id = g.category_id')
            ->where('g.status', 0)
            ->where('g.id', $id)
            ->field($field)
            ->find();
        if (!$item) {
            return $this->json(4004, '物品不存在或已售出');
        }

        $domain      = request()->domain(true);
        $item->cover = resourceJoin((string) $item->cover, $domain);
        $images      = explode(',', $item->images);
        foreach ($images as &$img) {
            $img = resourceJoin($img, $domain);
        }
        $item->images = $images;

        return $this->json(0, 'success', $item);
    }

    /**
     * 物品添加
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     */
    public function add(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;

        if (!$account = Account::field('id,nickname,status')->find((int) $accountId)) {
            return $this->json(6001, '请先登录');
        }

        if ($account['status'] != Account::STATUS_NORMAL) {
            return $this->json(4003, '用户状态异常');
        }

        $input = input('post.');

        $rules = [
            'title|标题'         => 'require|max:100|min:4',
            'cover|封面图'        => 'require',
            'category_id|所属分类' => 'require',
            'area_id|所属小区'     => 'require',
            'price|价格'         => 'require|number',
        ];

        $validate = $this->validateByApi($input, $rules);

        if ($validate !== true) {
            return $validate;
        }

        if (!isset($input['images']) && !isset($input['content'])) {
            return $this->json(4005, '详情组图和内容至少填一个');
        }

        try {
            $originalPrice = 0;
            if (isset($input['original_price'])) {
                $originalPrice = $input['original_price'] ?: $input['price'];
            }
            \app\model\Goods::create([
                'title'          => $input['title'],
                'cover'          => $input['cover'],
                'category_id'    => $input['category_id'],
                'content'        => $input['content'] ?? '',
                'phone'          => $input['phone'] ?? '',
                'price'          => $input['price'] ?? 0,
                'original_price' => $originalPrice,
                'account_id'     => $accountId,
                'area_id'        => $input['area_id'] ?? 0,
                'images'         => $input['images'] ?? '',
                'created_at'     => date('Y-m-d H:i:s'),
            ]);

            return $this->json();
        } catch (\Exception $e) {
            Log::error('闲置物品添加失败：line '.$e->getLine().' '.$e->getMessage());
            return $this->json(5000, '物品添加失败');
        }
    }

    /**
     * 物品编辑
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     */
    public function edit(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;

        if (!$account = Account::field('id,nickname,status')->find((int) $accountId)) {
            return $this->json(6001, '请先登录');
        }

        if ($account['status'] != Account::STATUS_NORMAL) {
            return $this->json(4003, '用户状态异常');
        }

        $input = input('post.');

        $rules = [
            'id|ID'            => 'require|number',
            'title|标题'         => 'require|max:100|min:4',
            'cover|封面图'        => 'require',
            'category_id|所属分类' => 'require',
            'area_id|所属小区'     => 'require',
            'price|价格'         => 'require|number',
        ];

        $validate = $this->validateByApi($input, $rules);

        if ($validate !== true) {
            return $validate;
        }

        try {
            if (!$item = \app\model\Goods::find((int) $input['id'])) {
                return $this->json(4004, '记录不存在');
            }

            if ($item['account_id'] != $accountId) {
                return $this->json(4003, '不是您发布的物品');
            }

            if (!isset($input['images']) && !isset($input['content'])) {
                return $this->json(4005, '详情组图和内容至少填一个');
            }

            $originalPrice = 0;
            if (isset($input['original_price'])) {
                $originalPrice = $input['original_price'] ?: $input['price'];
            }

            $item->save([
                'title'          => $input['title'],
                'cover'          => $input['cover'],
                'category_id'    => $input['category_id'],
                'content'        => $input['content'] ?? '',
                'phone'          => $input['phone'] ?? '',
                'price'          => $input['price'] ?? 0,
                'original_price' => $originalPrice,
                'area_id'        => $input['area_id'] ?? 0,
                'images'         => $input['images'] ?? '',
            ]);

            return $this->json();
        } catch (\Exception $e) {
            Log::error('闲置物品编辑失败：line '.$e->getLine().' '.$e->getMessage());
            return $this->json(5000, '物品编辑失败');
        }
    }

    /**
     * 删除
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function del(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;

        if (!$account = Account::field('id,nickname,status')->find((int) $accountId)) {
            return $this->json(6001, '请先登录');
        }

        if ($account['status'] != Account::STATUS_NORMAL) {
            return $this->json(4003, '用户状态异常');
        }

        $ids = input('id');

        try {
            $ids = explode(',', $ids);
            if (!empty($ids)) {
                \app\model\Goods::whereIn('id', $ids)->where('account_id', $accountId)->delete();
            }

            return $this->json();
        } catch (\Exception $e) {
            Log::error('闲置物品删除失败：line '.$e->getLine().' '.$e->getMessage());
            return $this->json(5000, '闲置物品删除失败');
        }
    }

    // 小区
    public function area(): Json
    {
        $page    = input('page/d', 1);
        $size    = input('size/d', 20);
        $keyword = input('keyword/s');

        $where = [];

        if (!empty($keyword)) {
            $where[] = ['title', 'like', '%'.$keyword.'%'];
        }

        $query = GoodsArea::field('id,title')->where($where);

        $total = $query->count();

        $res = [
            'total'   => $total,
            'current' => $page ?: 1,
            'size'    => $size ?: 20,
            'list'    => new Collection(),
        ];

        if ($total > 0) {
            $res['list'] = $query->page($page, $size)->order('sort', 'desc')->order('id', 'desc')->select();
        }

        return $this->json(0, 'success', $res);
    }

    // 分类
    public function category(): Json
    {
        $keyword = input('keyword/s');

        $where = [];

        if (!empty($keyword)) {
            $where[] = ['title', 'like', '%'.$keyword.'%'];
        }

        $res = GoodsCategory::field('id,title')->where($where)->order('sort', 'desc')->order('id', 'asc')->select();

        return $this->json(0, 'success', $res);
    }

    /**
     * 设置状态 0=展示 1=不展示（已完成）
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function setStatus(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '无效请求');
        }

        $accountId = $this->request->user['user_id'] ?? 0;

        if (!$account = Account::field('id,nickname,status')->find((int) $accountId)) {
            return $this->json(6001, '请先登录');
        }

        if ($account['status'] != Account::STATUS_NORMAL) {
            return $this->json(4003, '用户状态异常');
        }

        $id = input('id/d');
        $status = input('status/d', 0);

        if (!in_array($status, [0, 1])) {
            return $this->json(4001, '参数错误');
        }

        try {
            if (!$item = \app\model\Goods::findById($id, ['id', 'status', 'account_id'])) {
                return $this->json(4004, '物品不存在');
            }

            if ($item['account_id'] != $accountId) {
                return $this->json(4003, '不是您发布的物品');
            }

            $item->save([
                'status' => $status
            ]);

            return $this->json();
        } catch (\Exception $e) {
            Log::error('闲置物品状态修改失败：line '.$e->getLine().' '.$e->getMessage());
            return $this->json(5000, '状态设置失败');
        }
    }
}
