<?php
/**
 * ----------------------------------------------------------------------------
 * 行到水穷处，坐看云起时
 * 开发软件，找贵阳云起信息科技，官网地址:https://www.56q7.com/
 * ----------------------------------------------------------------------------
 * Author: 老成
 * email：85556713@qq.com
 */
declare (strict_types = 1);

namespace app\admin\controller\user;

use app\common\controller\Backend;
use think\annotation\route\Group;
use app\admin\traits\Actions;
use app\common\model\User;
use app\common\model\UserLog;
use think\annotation\route\Route;
use think\facade\Db;

#[Group("user/index")]
class Index extends Backend
{
    protected $noNeedRight = ['index'];

    use Actions;

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

    /**
     * 添加
     */
    #[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'])? request()->domain().'/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()) {
            $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']);
            }
            $params['avatar']  = empty($params['avatar'])? request()->domain().'/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('POST,GET','recharge')]
    public function recharge($ids)
    {
        if($this->request->isPost()){
            $module_type=$this->request->post('row.module_type');
            $change_type=$this->request->post('row.recharge_type');
            $change=$this->request->post('row.change/d');
            $remark=$this->request->post('row.remark');
            $order_no=time().rand(1000,9999);
            switch ($module_type){
                case 'score':
                    UserLog::addScoreLog($ids,$change_type,$change,$order_no,$remark);
                    break;
                case 'balance':
                    UserLog::addBalanceLog($ids,$change_type,$change,$order_no,$remark);
                    break;
            }
            $this->success();
        }else{
            $user=User::find($ids);
            $this->assign('moduletype',UserLog::TYPE);
            $this->assign('user',$user);
            return $this->fetch();
        }
    }

   

    #[Route('GET,JSON','detail')]
    public function detail($ids)
    {
        if($this->request->isAjax()){
            $this->model=new UserLog();
            $where=[];
            $where[]=['type','=',$this->request->get('type')];
            $where[]=['user_id','=',$ids];
            [$where, $order, $limit, $with] = $this->buildparams($where);
            $list = $this->model
                ->where($where)
                ->order($order)
                ->paginate($limit);
            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
        }else{
            $user=User::find($ids);
            $this->assign('moduletype',UserLog::TYPE);
            $this->assign('user',$user);
            return $this->fetch();
        }
    }
}

