<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Tree;
use plugin\admin\app\common\Util;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use support\think\Model;
use support\think\Db;

class Crud extends Base
{

    /**
     * @var Model
     */
    protected $model = null;
    /**
     * 是否是关联查询
     */
    protected $relationSearch = false;
    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = false;
    /**
     * Multi方法可批量修改的字段
     */
    protected $multiFields = 'status';
    /**
     * Selectpage可显示的字段
     */
    protected $selectpageFields = '*';

    /**
     * 查询
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }
    /**
     * selectpage
     * @param \support\Request $request
     */
    public function selectpage(Request $request)
    {
        $searchValue = $request->input('searchValue');
        $searchTable = $request->input('searchTable');
        $searchKey = $request->input('searchKey');
        $orderBy = $request->input('orderBy');
        $showField = $request->input('showField');
        $keyField = $request->input('keyField');
        $keyValue = $request->input('keyValue');
        $searchField = $request->input('searchField');
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $query = $this->doSelect($where, $field, $order);
        if($searchValue){
            $query = $query->whereIn($searchKey,$searchValue);
        }
        $list = $query->field([$showField,$keyField])->paginate($limit);
        return $this->success('ok',$list);
    }
    function index(Request $request): Response
    {
        return view();
    }
    /**
     * 添加
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if($request->method() == 'POST'){
            $data = $this->insertInput($request);
            $id = $this->doInsert($data);
            $ret =  $this->success('操作成功', ['id' => $id]);
            return $ret;
        }
        return view(strtolower(get_controller_name()).'/update');
    }
    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function update(Request $request): Response
    {
        if($request->method() == 'POST'){
            [$id, $data] = $this->updateInput($request);
            $this->doUpdate($id, $data);
            $ret =  $this->success('操作成功');
            return $ret;
        }
        $vo = [];
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $aliasName = $name . '.';
            $vo = $this->model->alias($name)->withJoin($this->relationSearch)->whereIn($aliasName.'id',$request->get('ids'))->find();
        }else{
            $vo = $this->model->whereIn('id',$request->get('ids'))->find();
        }

        return view('',[
            'row'   =>  $vo
        ]);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        $this->doDelete($ids);
        return $this->success('删除成功');
    }

    /**
     * 查询前置
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function selectInput(Request $request): array
    {
        $field = $request->input('sort','id');
        $order = $request->input('sortOrder', 'asc');
        $format = $request->input('format', 'normal');
        $limit = (int)$request->input('limit', $format === 'tree' ? 1000 : 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $order = $order === 'asc' ? 'asc' : 'desc';
        $where = $request->input('filter',[]);
        $page = (int)$request->input('page');
        $page = $page > 0 ? $page : 1;
        $allow_column = [];
        //var_dump($this->model->getConnectionName());
        //if ($this->model->getConnection()->getDriverName() == 'mongodb') {
        if ($this->model->getConnection() != 'plugin.admin.mysql') {
        } else {
            $table = $this->model->getTable();

            $allow_column = Util::db()->select("desc `$table`");
            if (!$allow_column) {
                throw new BusinessException('表不存在');
            }
            $allow_column = array_column($allow_column, 'Field', 'Field');
            if (!in_array($field, $allow_column)) {
                $field = null;
            }
        }
        // foreach ($where as $column => $value) {
        //     if (
        //         $value === '' || !isset($allow_column[$column]) ||
        //         is_array($value) && (empty($value) || !in_array($value[0], ['null', 'not null']) && !isset($value[1]))
        //     ) {
        //         unset($where[$column]);
        //     }
        // }
        // 按照数据限制字段返回数据
        if (!Auth::isSuperAdmin()) {
            if ($this->dataLimit === 'personal') {
                $where[$this->dataLimitField] = ['symbol'=>'=', 'value1'=>admin_id()];
            } elseif ($this->dataLimit === 'auth') {
                $primary_key = $this->model->getPk();
                if (!Auth::isSuperAdmin() && (!isset($where[$primary_key]) || $this->dataLimitField != $primary_key)) {
                    $where[$this->dataLimitField] = ['symbol'=>'in', 'value1'=>Auth::getScopeAdminIds(true)];
                }
            }
        }
        return [$where, $format, $limit, $field, $order, $page];
    }

    /**
     * 指定查询where条件,并没有真正的查询数据库操作
     * @param array $where
     * @param string|null $field
     * @param string $order
     * @return Model
     */
    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model;
        $aliasName="";
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $aliasName = $name . '.';
            $model = $model->alias($name)->withJoin($this->relationSearch);
            $field = false===strpos($field?:'','.') ? $aliasName.$field : $field;
        }
        foreach ($where as $column => $value) {
            $model = $this->parseOneWhere($model,$column,$value,$aliasName);
        }
        if ($field) {
            $model = $model->order($field, $order);
        }
        return $model;
    }
    protected function parseOneWhere($model,$column,$value,$aliasName=''){
        $column = false===strpos($column,'.') ? $aliasName.$column : $column;
        if (is_array($value)) {
            $symbol = isset($value['symbol']) ? $value['symbol'] : '';
            $value1 = isset($value['value1']) ? $value['value1'] : '';
            $value2 = isset($value['value2']) ? $value['value2'] : '';
            if ($symbol === 'like' || $symbol === 'not like') {
                $model = $model->where($column, $symbol, "%$value1%");
            } elseif (in_array($symbol, ['>', '=', '<', '<>','>=','<='])) {
                $model = $model->where($column, $symbol, $value1);
            } elseif (($symbol == 'in'|| $symbol == 'not in') && !empty($value1)) {
                $valArr = $value1;
                if (is_string($value1)) {
                    $valArr = explode(",", trim($value1));
                }
                if($symbol == 'in'){
                    $model = $model->whereIn($column, $valArr);
                }else{
                    $model = $model->whereNotIn($column, $valArr);
                }
            } elseif ($symbol == 'null') {
                $model = $model->whereNull($column);
            } elseif ($symbol == 'not null') {
                $model = $model->whereNotNull($column);
            } elseif ($symbol == 'range' && $$value1 !== '' || $value2 !== '') {
                $model = $model->whereBetween($column, [$value1, $value2]);
            }
        } else {
            $model = $model->where($column, $value);
        }
        return $model;
    }

    /**
     * 执行真正查询，并返回格式化数据
     * @param $query
     * @param $format
     * @param $limit
     * @return Response
     */
    protected function doFormat($query, $format, $limit,$fields="*"): Response
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];
        if($this->relationSearch){
            $fields="";
        }
        if($limit == 'all'){
            $paginator = $query->field($fields)->select();
            $total = count($paginator);
            $items = $paginator;
        }else{
            //var_dump($query->field($fields)->buildSql());
            $paginator = $query->field($fields)->paginate($limit);
            $total = $paginator->total();
            $items = $paginator->items();
        }
        //var_dump($query->getlastsql());
        if (method_exists($this, "afterQuery")) {
            $items = call_user_func([$this, "afterQuery"], $items);
        }
        $format_function = $methods[$format] ?? 'formatNormal';
        return call_user_func([$this, $format_function], $items, $total);
    }

    /**
     * 插入前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }
        $password_filed = 'trade_password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSuperAdmin()) {
            if ($this->dataLimit === 'personal') {
                $data[$this->dataLimitField] = admin_id();
            } elseif ($this->dataLimit === 'auth') {
                if (!empty($data[$this->dataLimitField])) {
                    $admin_id = $data[$this->dataLimitField];
                    if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                        throw new BusinessException('无数据权限');
                    }
                } else {
                    $data[$this->dataLimitField] = admin_id();
                }
            }
        } elseif ($this->dataLimit && empty($data[$this->dataLimitField])) {
            $data[$this->dataLimitField] = admin_id();
        }
        return $data;
    }

    /**
     * 执行插入
     * @param array $data
     * @return mixed|null
     */
    protected function doInsert(array $data)
    {
        $primary_key = $this->model->getPk();
        $model_class = get_class($this->model);
        // $model = new $model_class;
        // foreach ($data as $key => $val) {
        //     $model->{$key} = $val;
        // }
        // $model->save();

        $model = $model_class::create($data);
        return $primary_key ? $model->$primary_key : null;
    }

    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getPk();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }

        if (!Auth::isSuperAdmin()) {
            if ($this->dataLimit == 'personal') {
                if ($model->{$this->dataLimitField} != admin_id()) {
                    throw new BusinessException('无数据权限');
                }
            } elseif ($this->dataLimit == 'auth') {
                $scopeAdminIds = Auth::getScopeAdminIds(true);
                $admin_ids = [
                    $data[$this->dataLimitField] ?? false, // 检查要更新的数据admin_id是否是有权限的值
                    $model->{$this->dataLimitField} ?? false // 检查要更新的记录的admin_id是否有权限
                ];
                foreach ($admin_ids as $admin_id) {
                    if ($admin_id && !in_array($admin_id, $scopeAdminIds)) {
                        throw new BusinessException('无数据权限');
                    }
                }
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }
        $password_filed = 'trade_password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 执行更新
     * @param $id
     * @param $data
     * @return void
     */
    protected function doUpdate($id, $data)
    {
        $model = $this->model->find($id);
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
    }

    /**
     * 对用户输入表单过滤
     * @param array $data
     * @return array
     * @throws BusinessException
     */
    protected function inputFilter(array $data): array
    {
        $table = config('plugin.admin.database.connections.mysql.prefix') . $this->model->getTable();
        $allow_column = Db::getFields($this->model->getTable());
        if (!$allow_column) {
            throw new BusinessException('表不存在', 2);
        }
        //$columns = array_column($allow_column, 'Type', 'Field');
        //echo json_encode($allow_column);
        foreach ($data as $col => $item) {
            if (!isset($allow_column[$col])) {
                unset($data[$col]);
                continue;
            }
            // 非字符串类型传空则为null
            if ($item === '' && strpos(strtolower($allow_column[$col]['type']), 'varchar') === false && strpos(strtolower($allow_column[$col]['type']), 'text') === false) {
                $data[$col] = null;
            }
            $data[$col] = $item;
            // if (is_array($item)) {
            //     $data[$col] = implode(',', $item);
            // }
        }
        if (empty($data['created_at'])) {
            unset($data['created_at']);
        }
        if (empty($data['updated_at'])) {
            unset($data['updated_at']);
        }
        return $data;
    }

    /**
     * 删除前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function deleteInput(Request $request): array
    {
        $primary_key = $this->model->getPk();
        if (!$primary_key) {
            throw new BusinessException('该表无主键，不支持删除');
        }
        $ids = $request->post('ids', '');
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        if (!Auth::isSuperAdmin()){
            $admin_ids = [];
            if ($this->dataLimit) {
                $admin_ids = $this->model->whereIn($primary_key, $ids)->column($this->dataLimitField);
            }
            if ($this->dataLimit == 'personal') {
                if (!in_array(admin_id(), $admin_ids)) {
                    throw new BusinessException('无数据权限');
                }
            } elseif ($this->dataLimit == 'auth') {
                if (array_diff($admin_ids, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }
        return $ids;
    }

    /**
     * 执行删除
     * @param array $ids
     * @return void
     */
    protected function doDelete(array $ids)
    {
        if (!$ids) {
            return;
        }
        $primary_key = $this->model->getPk();
        $this->model->whereIn($primary_key, $ids)->delete();
    }

    /**
     * 格式化树
     * @param $items
     * @return Response
     */
    protected function formatTree($items): Response
    {
        $format_items = [];
        //$primary_key = $this->model->getPk();
        $primary_key = $this->model->getPk();
        foreach ($items as $item) {
            $item->name = $this->guessName($item) ?: $item->$primary_key;
            $item->value = (string)$item->$primary_key;
            $item->id = $item->$primary_key;
            //$item->pid = $item->pid;
            $format_items[] = $item;
        }
        $tree = new Tree($format_items);
        return $this->success('ok', $tree->getTree());
    }

    /**
     * 格式化表格树
     * @param $items
     * @return Response
     */
    protected function formatTableTree($items): Response
    {
        $tree = new Tree($items);
        return $this->success('ok', $tree->getTree());
    }

    /**
     * 格式化下拉列表
     * @param $items
     * @return Response
     */
    protected function formatSelect($items): Response
    {
        $formatted_items = [];
        $primary_key = $this->model->getPk();
        foreach ($items as $item) {
            $formatted_items[] = [
                'name' => $this->guessName($item) ?: $item->$primary_key,
                'value' => $item->$primary_key
            ];
        }
        return  $this->success('ok', $formatted_items);
    }

    /**
     * 通用格式化
     * @param $items
     * @param $total
     * @return Response
     */
    protected function formatNormal($items, $total): Response
    {
        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }

    /**
     * 查询数据库后置方法，可用于修改数据
     * @param mixed $items 原数据
     * @return mixed 修改后数据
     */
    protected function afterQuery($items)
    {
        return $items;
    }

    /**
     * 猜测记录名称
     * @param $item
     * @return mixed
     */
    protected function guessName($item)
    {
        return $item->title ?? $item->name ?? $item->nickname ?? $item->username ?? $item->id;
    }
    /**
     * 批量操作
     * @param $item
     * @return mixed
     */
    function multi(){
        $ids = Request()->post('ids');
        $params = Request()->post('params');
        parse_str($params,$s);
        if(!is_array($ids)){
            $ids = explode(',',$ids);
        }
        $this->model->whereIn('id', $ids)->update($s);
        return $this->success('操作成功');
    }
}
