<?php

namespace app\controller\manager;

use app\validate\ProductValidate;
use app\model\{ProductModel, Category as MCategory, Log as MLog, System};
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 产品
 * Class Honour
 * @package app\controller\manager
 */
class Product extends Base
{
    /**
     * @return Json|View
     */
    public function add()
    {
        if (request()->isPost()) {
            $images           = input('img_images/a');
            $params           = input('post.item/a', []);
            $params['image']  = input('img');
            $params['images'] = json_encode($images, JSON_UNESCAPED_UNICODE);
            $params['qr']     = input('img_qr');
            try {
                validate(ProductValidate::class)->check($params);
                $newItem = ProductModel::create($params);
                MLog::write('honour', 'add', '新增产品，ID:'.$newItem->id);
            } catch (ValidateException $e) {
                return $this->json(1, $e->getError());
            }
            return $this->json();
        } else {
            $categoryId = input('param.category_id/d', 0);
            $category   = MCategory::getById($categoryId);

            if (count($category) > 0 && $category['img_width'] && $category['img_height']) {
                $imgSize = $category['img_width'].'像素 X '.$category['img_height'].'像素';
            } else {
                $imgSize = System::getArticleImageSize();
            }

            $this->data['imgSize']  = $imgSize;
            $this->data['category'] = $category;
            return $this->view();
        }
    }

    /**
     * @return Json|View
     */
    public function edit()
    {
        $id   = input('param.id/d', 0);
        $item = ProductModel::getById($id);
        if (count($item) == 0) {
            return $this->json(1, '该产品不存在');
        }
        if (request()->isPost()) {
            $params           = input('post.item/a', []);
            $params['image']  = input('img');
            $params['qr'] = input('img_qr');
            $params['images'] = json_encode(array_values(input('img_images/a')), JSON_UNESCAPED_UNICODE);
            try {
                validate(ProductValidate::class)->check($params);
                ProductModel::updateById($id, $params);
                MLog::write('honour', 'edit', '修改产品，ID:'.$id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $category = MCategory::getById($item['category_id']);

            if (count($category) > 0 && $category['img_width'] && $category['img_height']) {
                $imgSize = $category['img_width'].'像素 X '.$category['img_height'].'像素';
            } else {
                $imgSize = System::getArticleImageSize();
            }

            $this->data['imgSize'] = $imgSize;
            $this->data['item']    = $item;
            return $this->view();
        }
    }

    public function sort()
    {
        if (request()->isPost()) {
            $id   = input('post.id/d');
            $sort = input('post.sort');
            $num  = input('post.num/d', 1);
            if ($num <= 0) {
                $num = 1;
            }
            if (!in_array($sort, ['up', 'down'], true)) {
                return $this->json(2, '参数错误');
            }
            $item = ProductModel::getById($id);
            if (empty($item)) {
                return $this->json(3, '该产品不存在');
            }
            if ($sort == 'up') {
                $where = "category_id='{$item['category_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            } else {
                $where = "category_id='{$item['category_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }
            $forSortItems = ProductModel::getListByWhereAndOrder($where, $order, $num);
            if (!empty($forSortItems)) {
                $updateData   = [];
                $forSortCount = count($forSortItems);
                for ($i = 0; $i < $forSortCount; $i++) {
                    if ($i == 0) {
                        $updateData[] = [
                            'id'   => $forSortItems[$i]['id'],
                            'sort' => $item['sort']
                        ];
                    } else {
                        $updateData[] = [
                            'id'   => $forSortItems[$i]['id'],
                            'sort' => $forSortItems[$i - 1]['sort']
                        ];
                    }
                }
                $updateData[] = [
                    'id'   => $item['id'],
                    'sort' => $forSortItems[$i - 1]['sort']
                ];
                if (!empty($updateData)) {
                    $model = new ProductModel();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    MLog::write('history', 'sort', "产品排序，ID：{$id} ，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    // 删除
    public function del()
    {
        if (request()->isPost()) {
            $historyId = input('param.id/d', 0);
            $item      = ProductModel::getById($historyId);
            if (count($item) == 0) {
                return $this->json(2, '该产品不存在');
            }
            try {
                ProductModel::destroy($historyId);
                MLog::write('honour', 'del', '删除产品，ID:'.$historyId);
            } catch (\Exception $e) {
                return $this->json(3, '删除失败，'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }
}