<?php

declare(strict_types=1);

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use app\common\model\GroupUser as GroupUserModel;
use think\facade\Db;

#[Group("user/group_user")]
class GroupUser extends Backend
{

    use Actions{
        index as private _index;
        add as private _add;
        edit as private _edit;
        del as private _del;
        multi as private _multi;
        import as private _import;
        download as private _download;
    }

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new GroupUserModel();
    }

    /**
     * 列表
     */
    #[Route('GET,POST,JSON', 'index')]
    public function index()
    {

        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if ($this->request->post('selectpage')) {
            return $this->selectpage();
        }
        $type = (string)$this->request->get('type', 2);


        [$where, $order, $limit, $with] = $this->buildparams();
        $list=[];
        if ($type == '1'){
             $list = $this->model->alias('g')
            ->join("yun_user u", "g.pid = u.id", "LEFT")
            ->with($with)
            ->where($where)
            ->order($order)
            ->field(['u.*','u.nickname' => 'manage_nickname'])
            ->group('g.pid')
            ->paginate($limit)->each(function ($item, $key) {
                $item['avatar']=$this->startsWithHttp($item['avatar'])?$item['avatar']:request()->domain().'/' . $item['avatar'];
                return $item;
            });
        }else if($type == '2'){
             $list = $this->model->alias('g')
            ->join("yun_user u", "g.pid = u.id", "INNER")
            ->with($with)
            ->where($where)

            ->order($order)
            ->field(['g.*'])
            ->paginate($limit)->each(function ($item, $key) {
                $item['avatar']=$this->startsWithHttp($item['avatar'])?$item['avatar']:request()->domain().'/' . $item['avatar'];
                return $item;
            });
        }

       

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }



    /**
     * 添加
     */
    #[Route('GET,POST', 'add')]
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->fetch();
        }
        $params = array_merge($this->request->post("row/a"), $this->postParams);
        if (empty($params)) {
            $this->error(__('提交的参数不能为空'));
        }
        if (!$this->request->checkToken('__token__', ['__token__' => $this->request->post('__token__')])) {
            $this->error(__('token错误，请刷新页面重试'));
        }
        foreach ($params as &$value) {
            if (is_array($value)) {
                $value = implode(',', $value);
            }
            if ($value === '') {
                $value = null;
            }
        }
        $result = false;
        Db::startTrans();
        try {
            $params['salt']   = str_rand(4);
            $params['password'] = md5(md5($params['password'] . $params['salt']));
            $params['avatar']  = empty($params['avatar']) ? '/assets/img/logo.jpg' : $params['avatar']; //默认头像
            $result = $this->model->save($params);
            if ($this->callback) {
                $callback = $this->callback;
                $callback($this->model);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('没有新增任何数据'));
        }
        $this->success();
    }
    /**
     * 编辑
     */
    #[Route('GET,POST', 'edit')]
    public function edit(mixed $row = null)
    {
        $ids = $this->request->get('ids');
        if (!$row || is_array($row)) {
            $row = $this->model->find($ids);
        }
        if (!$row) {
            $this->error(__('没有找到记录'));
        }
        if (count($this->volidateFields) > 0) {
            foreach ($this->volidateFields as $field => $value) {
                if ($row[$field] != $value) {
                    $this->error(__('没有操作权限'));
                }
            }
        }
        if (false === $this->request->isPost()) {
            $row['password'] = '';
            $row['avatar']  = startsWithHttp($row['avatar'])?$row['avatar']:request()->domain().'/' . $row['avatar'];
            $this->assign('row', $row);
            return $this->fetch();
        }
        $params = array_merge($this->request->post("row/a"), $this->postParams);
        if (empty($params)) {
            $this->error(__('提交的参数不能为空'));
        }
        if (!$this->request->checkToken('__token__', ['__token__' => $this->request->post('__token__')])) {
            $this->error(__('token错误，请刷新页面重试'));
        }
        foreach ($params as &$value) {
            if (is_array($value)) {
                $value = implode(',', $value);
            }
            if ($value === '') {
                $value = null;
            }
        }
        $result = false;
        Db::startTrans();
        try {
            if (!empty($params['password'])) {
                $params['salt'] = str_rand(4);
                $params['password'] = md5(md5($params['password'] . $params['salt']));
            } else {
                unset($params['password']);
            }
            if ($params['type'] == '1' && empty($params['group_name'])) {
                $this->error(__('管理身份，必须设置组名'));
            }
            $params['avatar']  = empty($params['avatar']) ? '/assets/img/logo.jpg' : $params['avatar']; //默认头像
            $result = $row->save($params);
            if ($this->callback) {
                $callback = $this->callback;
                $callback($row);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('没有数据被更新'));
        }
        $this->success();
    }

    /**
     * 列表
     */
    #[Route('GET,JSON', 'group_list')]
    public function group_list()
    {

        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        $pid = (string)$this->request->get('pid', '0');


        [$where, $order, $limit, $with] = $this->buildparams();
        $where_item = [];
        if ($pid != '0') $where_item[] = ['pid', '=', (string)$pid];
        $list = $this->model
            ->with($with)
            ->where($where_item)
            ->where($where)
            ->order($order)
            ->paginate($limit)->each(function ($item, $key) {
                $item['avatar']=$this->startsWithHttp($item['avatar'])?$item['avatar']:request()->domain().'/' . $item['avatar'];
                return $item;
            });

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    // 方法1.1：使用strpos()精准匹配
    public function startsWithHttp($url)
    {
        return strpos($url, 'https://') === 0
            || strpos($url, 'http://') === 0;
    }
    //删除
    #[Route("GET,POST","del")]
    public function del()
    {
        //通过定义callback回调函数来执行删除后的操作
        $this->callback=function ($ids){};
        return $this->_del();
    }
}
