<?php
namespace app\controller\manager;

use app\model\{AchievementInfo, Category, Achievement as MAchievement, Log};
use app\validate\Achievement as VAchievement;
use think\facade\Db;

/**
 * 业绩管理
 * Class Achievement
 * @package app\controller\manager
 */
class Achievement extends Base
{
    protected $validate;
    public function initialize()
    {
        parent::initialize();
        $this->validate = new VAchievement();
    }

    /****************************
     *  业绩
     ****************************/
    public function add()
    {
        $categoryId = input('param.category_id/d', 0);
        $category = Category::getById($categoryId);
        if(empty($category)) {
            return $this->json(1, '无此栏目信息');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            if($this->validate->checkAchievement($params)) {
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                    'category_id'   => $categoryId,
                    'summary'       => $params['summary'] ?? '',
                    'description'   => $params['description'] ?? '',
                    'create_time'   => time(),
                ];
                $newItem = MAchievement::create($data);
                Log::write('achievement', 'add', '新增业绩，ID:'.$newItem->id);
            } else {
                return $this->json(2, $this->validate->getError());
            }
            return $this->json();
        } else {
            $this->data['category'] = $category;
            return $this->view();
        }
    }

    public function edit()
    {
        $id = input('param.id/d', 0);
        $item = MAchievement::getById($id);
        if(count($item) == 0) {
            return $this->json(1, '该业绩信息不存在');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            if($this->validate->checkAchievement($params)) {
                $data = [
                    'title'         => $params['title'],
                    'visible'       => $params['visible'],
                    'summary'       => $params['summary'] ?? '',
                    'description'   => $params['description'] ?? '',
                ];
                MAchievement::updateById($item['id'] ,$data);
                Log::write('achievement', 'add', '修改业绩，ID:'.$item['id']);
            } else {
                return $this->json(2, $this->validate->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 = MAchievement::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 = MAchievement::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 MAchievement();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('achievement', 'sort', "业绩排序，ID：{$id} ，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    public function del()
    {
        if(request()->isPost()) {
            $id = input('param.id/d', 0);
            $item = MAchievement::getById($id);
            if(count($item) == 0) {
                return $this->json(2, '该业绩信息不存在');
            }
            Db::startTrans();
            try {
                MAchievement::destroy($id);
                $hasInfo = AchievementInfo::hasByAchievementId($id);
                if($hasInfo > 0) {
                    AchievementInfo::delByAchievementId($id);
                }
                Log::write('achievement','del', '删除业绩，ID:'.$id);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->json(3, '删除失败，'.$e->getMessage());
            }
            return $this->json();
        }
        return $this->json(1, '无此操作');
    }

    /****************************
     *  业绩详情
     ****************************/

    public function info()
    {
        $achievementId = input('param.achievement_id/d', 0);
        $achievement = MAchievement::getById($achievementId);
        $infoItems = [];
        $categoryId = $achievement['category_id'] ?? 0;
        if($achievement) {
            $infoItems = AchievementInfo::getByAchievementId($achievementId);
        }
        $this->data['achievement'] = $achievement;
        $this->data['categoryId'] = $categoryId;
        $this->data['items'] = $infoItems;
        return $this->view();
    }

    public function infoAdd()
    {
        $achievementId = input('param.achievement_id/d', 0);
        $achievement = MAchievement::getById($achievementId);
        if(empty($achievement)) {
            return $this->json(2, '无此业绩信息');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            if($this->validate->checkAchievementInfo($params)) {
                $data = [
                    'achievement_id'        => $achievementId,
                    'title'                 => $params['title'],
                    'order_company'         => $params['order_company'],
                    'goods_model'           => $params['goods_model'],
                    'goods_amount'          => $params['goods_amount'],
                    'visible'               => $params['visible'],
                    'owner'                 => $params['owner'] ?? '',
                    'owner_tel'             => $params['owner_tel'] ?? '',
                    'owner_email'           => $params['owner_email'] ?? '',
                    'create_time'           => time(),
                ];
                $newItem = AchievementInfo::create($data);
                Log::write('achievement', 'infoAdd', '新增业绩项目，ID:'.$newItem->id);
            } else {
                return $this->json(2, $this->validate->getError());
            }
            return $this->json();
        } else {
            $this->data['achievementId'] = $achievementId;
            $this->data['achievement'] = $achievement;
            return $this->view();
        }
    }

    public function infoEdit()
    {
        $id = input('param.id/d', 0);
        $item = AchievementInfo::getById($id);
        if(count($item) == 0) {
            return $this->json(1, '该业务项目不存在');
        }
        if(request()->isPost()) {
            $params = input('post.item/a', []);
            $params = arrayHtmlFilter($params);
            if($this->validate->checkAchievementInfo($params)) {
                $data = [
                    'title'                 => $params['title'],
                    'order_company'         => $params['order_company'],
                    'goods_model'           => $params['goods_model'],
                    'goods_amount'          => $params['goods_amount'],
                    'visible'               => $params['visible'],
                    'owner'                 => $params['owner'] ?? '',
                    'owner_tel'             => $params['owner_tel'] ?? '',
                    'owner_email'           => $params['owner_email'] ?? '',
                ];
                AchievementInfo::updateById($id, $data);
                Log::write('achievement', 'infoEdit', '修改业绩项目，ID:'.$id);
            } else {
                return $this->json(2, $this->validate->getError());
            }
            return $this->json();
        } else {
            $this->data['item'] = $item;
            return $this->view();
        }
    }

    public function infoSort()
    {
        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 = AchievementInfo::getById($id);
            if(empty($item)){
                return $this->json(3, '该业绩项目信息不存在');
            }
            if($sort == 'up'){
                $where = "achievement_id='{$item['achievement_id']}' and sort > {$item['sort']}";
                $order = "sort asc";
            }else{
                $where = "achievement_id='{$item['achievement_id']}' and sort < {$item['sort']}";
                $order = "sort desc";
            }
            $forSortItems = AchievementInfo::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 AchievementInfo();
                    $model->saveAll($updateData);
                    $sortStr = $sort == 'up' ? '上移' : '下调';
                    Log::write('achievement', 'infoSort', "业绩项目排序，ID：{$id} ，{$sortStr}了{$num}位");
                    return $this->json();
                }
            }
            return $this->json(4, '无须调整排序!');
        }
        return $this->json(1, '无此操作');
    }

    public function infoDel()
    {
        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) {
                AchievementInfo::destroy($infoIds);
                Log::write('achievement','infoDel', '删除业绩项目，IDs:'.implode(',', $infoIds));
                return $this->json();
            }
            return $this->json(2, '参数错误');
        }
        return $this->json(1, '无此操作');
    }

}