<?php

namespace app\controller\manager;

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

/**
 * 招聘职位
 * Class Position
 * @package app\controller\manager
 */
class Position extends Base
{
    /**
     * @return Json|View
     */
    public function add()
    {
        if (request()->isPost()) {
            $params                = input('post.item/a', []);
            $params['create_time'] = time();
            try {
                validate(PositionValidate::class)->check($params);
                $newItem = PositionModel::create($params);
                MLog::write('position', '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);

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

    /**
     * @return Json|View
     */
    public function edit()
    {
        $id   = input('param.id/d', 0);
        $item = PositionModel::getById($id);
        if (count($item) == 0) {
            return $this->json(1, '该职位不存在');
        }
        if (request()->isPost()) {
            $params = input('post.item/a', []);
            try {
                validate(PositionValidate::class)->check($params);
                PositionModel::updateById($id, $params);
                MLog::write('position', 'edit', '修改职位，ID:'.$id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $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 = PositionModel::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 = PositionModel::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 PositionModel();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    MLog::write('position', '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      = PositionModel::getById($historyId);
            if (count($item) == 0) {
                return $this->json(2, '该职位不存在');
            }
            try {
                PositionModel::destroy($historyId);
                MLog::write('position', 'del', '删除职位，ID:'.$historyId);
            } catch (\Exception $e) {
                return $this->json(3, '删除失败，'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }
}