<?php


namespace app\controller\manager;

use app\model\{HistoryInfo as MHistoryInfo, History as MHistory, Category as MCategory, Log as MLog, System};
use think\exception\ValidateException;
use app\validate\{History as VHistory, HistoryInfo as VHistoryInfo};
use think\facade\Db;

/**
 * 发展历程
 * Class History
 * @package app\controller\manager
 */
class History extends Base
{
    public function add()
    {
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            try {
                validate(VHistory::class)->check($params);
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                    'category_id'   => $params['category_id'],
                ];
                $newItem = MHistory::create($data);
                MLog::write('history', '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();
        }
    }

    public function edit()
    {
        $id = input('param.id/d', 0);
        $item = MHistory::getById($id);
        if(count($item) == 0) {
            return $this->json(1, '该历程信息不存在');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            try {
                validate(VHistory::class)->check($params);
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                ];
                MHistory::updateById($id, $data);
                MLog::write('history', '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 = MHistory::getById($id);
            if(empty($item)){
                return $this->json(3, '该历程信息不存在');
            }
            if($sort == 'up'){ // sort 变大
                $where = "category_id='{$item['category_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }else{ // sort 变小
                $where = "category_id='{$item['category_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            }
            $forSortItems = MHistory::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 MHistory();
                    $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 = MHistory::getById($historyId);
            if(count($item) == 0) {
                return $this->json(2, '该历程信息不存在');
            }
            Db::startTrans();
            try {
                MHistory::destroy($historyId);
                $hasInfo = MHistoryInfo::countByHistoryId($historyId);
                if($hasInfo > 0) {
                    MHistoryInfo::delByHistoryId($historyId);
                }
                MLog::write('history','del', '删除历程,ID:'.$historyId);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->json(3, '删除失败,'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }


    public function info()
    {
        $historyId = input('param.history_id/d', 0);
        $history = MHistory::getById($historyId);
        $infoItems = [];
        $categoryId = $history['category_id'] ?? 0;
        if(count($history) > 0) {
            $infoItems = MHistoryInfo::getByHistoryId($historyId);
        }
        $this->data['history'] = $history;
        $this->data['categoryId'] = $categoryId;
        $this->data['items'] = $infoItems;
        return $this->view();
    }

    // 新增发展历程详情
    public function  addInfo()
    {
        $historyId = input('param.history_id/d', 0);
        $history = MHistory::getById($historyId);
        if(count($history) == 0) {
            return $this->json(1, '该历程信息不存在');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            $imgs = input('post.img/a');
            if (!empty($imgs) && is_array($imgs)) {
                $imgs = json_encode($imgs);
            } else {
                $imgs = '';
            }
            try {
                validate(VHistoryInfo::class)->check($params);
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                    'history_id'    => $historyId,
                    'imgs'          => $imgs,
                ];
                $newItem = MHistoryInfo::create($data);
                MLog::write('history', 'addInfo', '新增发展历程事例,ID:'.$newItem->id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $imgSize = '425像素 X 280像素';
            $category = MCategory::getById($history['category_id']);
            if(count($category) > 0 && $category['img_width'] && $category['img_height']){
                $imgSize = $category['img_width'] . '像素 X ' . $category['img_height'] . '像素';
            }

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

    // 编辑发展历程详情
    public function  editInfo()
    {
        $id = input('param.id/d', 0);
        $item = MHistoryInfo::getById($id);
        if(count($item) == 0) {
            return $this->json(1, '该历程事例信息不存在');
        }

        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            $imgs = input('post.img/a');
            if (!empty($imgs) && is_array($imgs)) {
                $imgs = json_encode($imgs);
            } else {
                $imgs = '';
            }
            try {
                validate(VHistoryInfo::class)->check($params);
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                    'imgs'          => $imgs,
                ];
                MHistoryInfo::updateById($id, $data);
                MLog::write('history', 'editInfo', '修改发展历程事例,ID:'.$id);
            } catch (ValidateException $e) {
                return $this->json(2, $e->getError());
            }
            return $this->json();
        } else {
            $history = MHistory::getById($item['history_id']);
            $imgSize = '425像素 X 280像素';
            if(count($history) > 0) {
                $category = MCategory::getById($history['category_id']);
                if(count($category) > 0 && $category['img_width'] && $category['img_height']){
                    $imgSize = $category['img_width'] . '像素 X ' . $category['img_height'] . '像素';
                }
            }

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

    public function sortInfo()
    {
        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 = MHistoryInfo::getById($id);
            if(empty($item)){
                return $this->json(3, '该历程事例信息不存在');
            }
            if($sort == 'up'){
                $where = "history_id='{$item['history_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }else{
                $where = "history_id='{$item['history_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            }
            $forSortItems = MHistoryInfo::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 MHistoryInfo();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    MLog::write('history', 'sortInfo', "发展历程事例排序,ID:{$id} ,{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    public function delInfo()
    {
        if(request()->isPost()) {
            $infoIds = [];
            $ids = input('post.ids', []);
            $id = input('post.id', 0);
            if(!empty($ids)) {
                if(is_array($ids)) {
                    $infoIds = $ids;
                } else {
                    $infoIds = explode(',', $ids);
                }
            } elseif($id > 0) {
                $infoIds[] = $id;
            }
            if(count($infoIds) > 0) {
                MHistoryInfo::destroy($infoIds);
                MLog::write('history','delInfo', '删除历程事例,IDs:'.implode(',', $infoIds));
                return $this->json();
            }
            return $this->json(2, '参数错误');
        }
        return $this->json(1, '无此操作');
    }
}