<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Operators extends Backend
{


    /**
     * Material模型对象
     * @var \app\admin\model\Material
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Operators();

    }


    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $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) = $this->buildparams();
            $admin_id = session::get("admin")["id"] ;
            $admin = [];
            if ($admin_id != 1){
                $admin = ["admin_id"=>$admin_id];
            }
            $list = $this->model
                ->with('role')
                ->where($where)
                ->where($admin)
                ->order($sort, $order)
                ->paginate($limit);
                
            $list_one = collection($list->items())->toArray();

            $result = array("total" => $list->total(), "rows" => $list_one);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     *  添加
     */
    public function add (){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $data = $_POST["row"];
            $data["salt"] = rand(100000,999999);
            DB::startTrans();
            $insert = $this->model->insertGetId($data);
            $admin = [
                "username" => $data["mobile"],
                "password" => "f274c2edbba265dd836e090e238bcb09",
                "salt" => "0706d7",
                "avatar" => "/assets/img/avatar.png",
                "status" => "normal",
                "nickname" => $data["name"],
            ];
            $admin_id = DB::name("admin")->insertGetId($admin);
            $access = [
                "uid" => $admin_id,
                "group_id" => 3,
                "operators_id" => $insert,
            ];
            $access_id =  DB::name("auth_group_access")->insert($access);
            if ($insert > 0 &&  $admin_id > 0 && $access_id) {
                DB::commit();
                $this->success();
            }else{
                DB::rollback();
                $this->error("添加失败");
            }
        }
        return $this->view->fetch();

    }

    /**
     * 删除
     */
    public function  del($ids = ""){
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->field("admin.id as admin_id,fa_operators.id")->join("auth_group_access group","fa_operators.id = group.operators_id")->join("admin admin","admin.id = group.uid")->where("fa_operators.id", 'in', $ids)->find()->toArray();
            $count = 0;
            Db::startTrans();
            $operators = $this->model->where(["id"=>$list["id"]])->delete();
            $admin = DB::name("admin")->where(["id"=>$list["admin_id"]])->delete();
            $access = DB::name("auth_group_access")->where(["uid"=>$list["admin_id"],"operators_id"=>$list["id"]])->delete();

            if ($operators && $admin && $access){
                Db::commit();
                $this->success();
            }else{
                Db::rollback();
                $this->error("删除失败");
            }

        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     *  编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $list = DB::name("operators_deploy")->where(["operators_id"=>$ids])->find();

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $array = $this->request->post("list/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $array = $this->preExcludeFields($array);
                $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(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    if(empty($list)){
                        $array["operators_id"] = $ids;
                        $deploy = DB::name("operators_deploy")->insert($array);
                    }else{
                        $deploy = DB::name("operators_deploy")->where("operators_id",$ids)->update($list);
                    }
                    if($result && $deploy > 0){
                        Db::commit();
                    }else{
                        Db::rollback();
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false && $deploy > 0) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("list", $list);
        return $this->view->fetch();
    }

    /**
     *
     */
    public function profit (){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            $id = $_GET["id"];
            $list = $this->model->find(["id"=>$id])->toArray();
            return json($list);
        }
        return $this->view->fetch();
    }
}
