<?php

declare (strict_types=1);

namespace app\controller\manager;

use app\model\Account;
use app\model\GoodsArea;
use app\model\GoodsCategory;
use Exception;
use app\model\Log;
use think\Collection;
use think\response\View;
use think\response\Json;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;


class Goods extends Base
{
    protected $noNeedLogin = ['searchAccount'];

    /**
     * 列表
     *
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $params = input('searchParams/a');
            $page   = input('page/d', 1);
            $size   = input('size/d', 20);

            $where = [];
            if (!empty($params)) {
                foreach ($params as $key => $param) {
                    $param = trim($param);
                    if ($key == 'keyword') {
                        $where[] = ['a.nickname|g.title|gc.title|g.phone|ga.title', 'like', '%'.$param.'%'];
                        continue;
                    }
                    if ($param == '0' || !empty($param)) {
                        $where[] = ['g.'.$key, 'like', '%'.$param.'%'];
                    }
                }
            }

            $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.*,gc.title as category_title,a.nickname,ga.title as area_name')
                ->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();
            }

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

        return $this->view();
    }

    /**
     * 添加
     *
     * @return Json|View
     */
    public function add()
    {
        if ($this->request->isPost()) {

            try {
                $input = input('post.');
                //                $images = input('img_images/a', []);
                \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' => $input['original_price'] ?? $input['price'],
                    'account_id'     => $input['account_id'] ?? 0,
                    'status'         => $input['status'] ?? 0,
                    'area_id'        => $input['area_id'] ?? 0,
                    'images'         => $input['images'] ?? '',
                ]);

                return $this->json();
            } catch (Exception $e) {
                return $this->json(4001, '添加失败'.$e->getMessage());
            }
        }

        $this->data['cateList'] = GoodsCategory::order('sort', 'desc')
            ->order('id', 'desc')
            ->column('id,title');
        $this->data['areaList'] = GoodsArea::order('sort', 'desc')
            ->order('id', 'desc')
            ->column('id,title');
        return $this->view();
    }

    /**
     * 编辑
     *
     * @return \think\response\Json|\think\response\View
     */
    public function edit()
    {
        $id = input('id');

        //通过ID查询
        $item = \app\model\Goods::findById((int) $id);

        if (empty($item)) {
            return $this->json(4000, '没有相关的记录!');
        }

        if ($this->request->isPost()) {
            try {
                $input = input('post.');

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

                return $this->json();
            } catch (Exception $e) {
                return $this->json(5000, $e->getMessage());
            }
        }

        $bindAccount = Account::where('id', $item['account_id'])->column('id,nickname,mobile');

        $accountList = [];
        foreach ($bindAccount as $ac) {
            $accountList[] = [
                'account_desc' => $ac['nickname'].'【手机:'.$ac['mobile'].'】',
                'id'           => $ac['id'], 'selected' => true
            ];
        }
        $this->data['jsonStr']  = $bindAccount ? json_encode($accountList, JSON_UNESCAPED_UNICODE) : json_encode([]);
        $this->data['item']     = $item;
        $this->data['id']       = $id;
        $this->data['cateList'] = GoodsCategory::order('sort', 'desc')
            ->order('id', 'desc')
            ->column('id,title');
        $this->data['areaList'] = GoodsArea::order('sort', 'desc')
            ->order('id', 'desc')
            ->column('id,title');
        return $this->view();
    }

    /**
     * 更新属性
     *
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws Exception
     */
    public function modify()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $item     = input('post.');
        $validate = $this->validateByApi($item, [
            'field' => 'require',
            'value' => 'require',
        ]);

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

        // 通过ID查询
        if (!$info = \app\model\Goods::findById((int) $item['id'])) {
            return $this->json(4001, '记录不存在');
        }

        $update = [$item['field'] => $item['value']];

        try {
            $info->save($update);
            return $this->json();
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            return $this->json(5000, '修改失败');
        }
    }

    /**
     * 删除
     *
     * @return \think\response\Json
     */
    public function del(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids   = array_filter($ids);
        }

        try {
            if (count($ids)) {
                \app\model\Goods::whereIn('id', $ids)->delete();

                Log::write(get_class(), 'del', '删除操作,涉及到的ID为:'.implode(',', $ids));
            }
        } catch (Exception $e) {
            return $this->json(5000, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 搜索用户
     */
    public function searchAccount(): Json
    {
        $keyword = input('keyword/s', '');

        $list = [];
        if (!empty($keyword)) {
            $res  = Account::findList([], ['id', 'nickname', 'mobile'], 1, 1000, function ($q) use ($keyword) {
                return $q->where('nickname', 'like', '%'.$keyword.'%')
                    ->whereOr('mobile', 'like', '%'.$keyword.'%');
            });
            $list = $res['list']->toArray();
            foreach ($list as &$item) {
                $item['account_desc'] = $item['nickname'].'【手机:'.$item['mobile'].'】';
            }
            unset($item);
        }

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