<?php

namespace app\admin\controller\score;

use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 员工管理
 *
 * @icon fa fa-circle-o
 */
class Employee extends Backend
{

    /**
     * Employee模型对象
     * @var \app\admin\model\score\Employee
     */
    protected $model = null;
    protected $qSwitch = true;
    protected $qFields = ["team_id","user_id"];

    public function _initialize()
    {

        $this->model = new \app\admin\model\score\Employee;
        parent::_initialize();
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit, $page, $alias, $bind,$excludearray) = $this->buildparams(null,null,['opertime']);
            //得到查询时间
            $opertime = $excludearray['opertime'] ?? [];
            $start_time = $end_time =null;
            if($opertime){
                //得到查询值
                $value = $opertime['value'];
                list($start_time,$end_time) = explode(" - ",$value);
            }
//            var_dump($sort);
            // 判断是否按 score_count 排序，该字段为PHP计算值无法直接数据库排序
            $sortByScoreCount = ($sort === 'employee.score_count');
//            var_dump($sortByScoreCount);
            if ($sortByScoreCount) {

                // 按积分统计排序：需取全量数据后在PHP层排序再手动分页
                $list = $this->model
                    ->with(['user','team'])
                    ->where($where)
                    ->select();

                foreach ($list as $row) {
                    $row->getRelation('user')->visible(['nickname','mobile','avatar']);
                    $row->getRelation('team')->visible(['name']);
                }

                $list = collection($list)->toArray();

                // 为每条记录计算 score_count
                foreach ($list as &$row) {
                    $row['score_count'] = \app\common\model\score\Employee::getPriceByCoachAndTime($row['id'], $start_time, $end_time);
                    $row['opertime'] = $start_time ? $start_time.'至'.$end_time : '';
                }
                unset($row);

                // PHP层按 score_count 排序
                usort($list, function($a, $b) use ($order) {
                    if (strtolower($order) === 'desc') {
                        return $b['score_count'] <=> $a['score_count'];
                    }
                    return $a['score_count'] <=> $b['score_count'];
                });

                $total = count($list);
                // 手动分页
                $list = array_slice($list, $offset, $limit);

            } else {
                // 常规排序：直接数据库分页
                $list = $this->model
                    ->with(['user','team'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

                foreach ($list as $row) {
                    $row->getRelation('user')->visible(['nickname','mobile','avatar']);
                    $row->getRelation('team')->visible(['name']);
                }

                $total = $list->total();
                $list = $list->items();

                foreach ($list as &$row) {
                    $row['score_count'] = \app\common\model\score\Employee::getPriceByCoachAndTime($row['id'], $start_time, $end_time);
                    $row['opertime'] = $start_time ? $start_time.'至'.$end_time : '';
                }
                unset($row);
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);

        }
        return $this->view->fetch();
    }




    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            //更新队伍日志记录
//            \app\common\model\score\Log::where( "score_team_id",$row->team_id )->update(["score_team_id"=>0]);
            \app\common\model\score\Log::where( "score_employee_id","=",$row->id )->update(["score_team_id"=>$row->team_id]);


            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


}
