<?php

namespace app\controller;

use think\App;
use app\AdminBaseController;
use think\facade\Log;
use think\exception\ValidateException;
use app\AppCache;
use think\facade\Cache;
use app\Constant;
use Exception;
use think\facade\Config;

class Admin extends AdminBaseController
{
    function __construct(
        App $app
    ) {
        $this->className = 'V1';
        $this->not_check_action_login = [
            'test',
            'login',
            'login_id',
            'get_code'
        ];
        parent::__construct($app);
    }

    public function test() {
      json_decode('asdfasdf','');
      return ajaxSuccess(json_last_error());
        // return ajaxSuccess($this->user_info);
    }
     public function order_list($current = 1, $pageSize = 10, $order_no = '', $pay_time = '', $buy_type = '', $status = '',$phone='',$name='',$from_user_name='',$create_time=[], $export=0)
    {
        $user_ids = [];
        if($from_user_name){
            $list_user = D('user')->where('real_name','LIKE', '%'.$from_user_name.'%')->select();
            foreach ($list_user as $one) {
                $user_ids[] = $one['id'];
            }
        }
        $model = D('orderx');
        $where = [
            'deleted' => 0,
        ];
        $model = $model->where($where);
        if ($order_no) {
            $model = $model->where('order_no', 'LIKE', '%' . $order_no . '%');
        }
        if ($phone) {
            $model = $model->where('phone', 'LIKE', '%' . $phone . '%');
        }
        if ($name) {
            $model = $model->where('name', 'LIKE', '%' . $name . '%');
        }
        if ($pay_time) {
            $model = $model->whereBetween('pay_time', [$pay_time . ' 00:00:00', $pay_time . ' 23:59:59']);
        }
        if ($buy_type) {
            $model = $model->where('buy_type', $buy_type);
        }
        if ($status) {
            $model = $model->where('status', $status);
        }else{
           $model = $model->where('status', '<>', 'cancel');
        }
        if($from_user_name){
            $model = $model->where('from_user_id','in',$user_ids);
        }
        if($create_time && count($create_time) == 2) {
          $model->where('create_time' ,'>=' ,$create_time[0] . ':00:00:00');
          $model->where('create_time' ,'<=' ,$create_time[1] . '23:59:59');
        }
        $total = 0;
        if($export != 1) {
          $total = $model->count();
          $model->page($current, $pageSize);
        }
        $_list = $model->order('id DESC')->select();
        //
        $list = [];
        foreach ($_list as $one) {
            $user_info = D('user')->where(['id' => $one['from_user_id']])->find();
            $one['from_user_name'] = $user_info['real_name'] ?: '';
            // $one['phone'] = $user_info['phone'];
            $list[] = $one;
        }
        if($export == 1) {
          header('Content-Disposition: attachment; filename=订单列表'. time() . '.xls');
          header('Content-Encoding: UTF-8');
          header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
          echo '<table>';
          $row = [
                  '订单号','支付金额',
                  '支付状态','类型','用户名','用户手机号',
                  '订单时间','支付时间',
                  // '退款时间','退款金额',
                  '分销员','分销员id'
                  ];
          $v = '<tr><td>' . join("</td><td>", $row) . "</td></tr>";
          echo iconv("UTF-8", "GB2312//IGNORE", $v);
          foreach ($list as $row) {
              $t = [];
              $t[] = $row['order_no'];
              $t[] = round($row['price']/100,2);
              
              $t[] = Constant::$ORDER_PAY_STAUS[$row['status']]['text'] ?? $row['status'];
              $t[] = $row['buy_type'];
              $t[] = $row['name'];
              $t[] = '\'' . $row['phone'];

              $t[] = $row['create_time'];
              $t[] = $row['pay_time'];
              
              $t[] = $row['refund_time'];
              // $t[] = round($row['refund_money']/100,2);
              // $t[] = round($row['refund_inner_money']/100,2);
              $t[] = $row['from_user_name'];
              $t[] = $row['from_user_id'];
              
              $v ='<tr><td>' .  join("</td><td>", $t) . "</td></tr>";
              echo iconv("UTF-8", "GB2312//IGNORE", $v);
          }
          echo '</table>';
        }
        else {
          return ajaxSuccessPage($list, $current, $pageSize, $total);
        }
    }
    public function change_share($id,$is_share) {
      D('user')->where(['id'=>$id])->update(['is_share'=>$is_share]);
      return ajaxSuccess();
    }
    public function member_list($current = 1, $pageSize = 10, $is_share='', $real_name='', $create_time=[], $export = 0,$has_phone=0)
    {
        $model = D('user');
        $where = [
            'deleted' => 0,
        ];
        $model = $model->where($where);
        if ($real_name) {
            $model = $model->where('real_name', 'LIKE', '%' . $real_name . '%');
        }
        if($is_share !== '') {
          $model->where(['is_share'=>$is_share]);
        }
        if($create_time && count($create_time) == 2) {
          $model->where('create_time' ,'>=' ,$create_time[0]);
          $model->where('create_time' ,'<=' ,$create_time[1]);
        }
        $total = $model->count();
        if($export == 0) {
           $model->page($current, $pageSize);
        }
        $_list = $model->order('id DESC')->select();
        $list = [];
        foreach ($_list as $one) {
          $list[] = $one;
        }
        if($export == 0) {
          return ajaxSuccessPage(c_filter_property_list($list, ['openid','union_id','session_key','sms_code','deleted'], true), $current, $pageSize, $total);
        }
        else {
            // header('Content-Disposition: attachment; filename=会员列表'. time() . '.xlsx');
            // header('Content-Encoding: UTF-8');
            // header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
            // echo '<table>';
            // $row = [
            //         '内部编号','手机号','姓名/昵称',
            //         '剩余金额','剩余积分','等级积分',
            //         '会员号','性别','出生年月','自评等级','注册时间'
            //         ];
            // $v = '<tr><td>' . join("</td><td>", $row) . "</td></tr>";
            // echo iconv("UTF-8", "GB2312//IGNORE", $v);
            // foreach ($list as $row) {
            //     $t = [];
            //     $t[] = $row['id'];
            //     $t[] = '\'' . $row['phone'];
            //     $t[] = $row['nick_name2'];

            //     $t[] = round($row['money']/100,2);
            //     $t[] = $row['score'];
            //     $t[] = $row['level_score'];
                
            //     $t[] = $row['user_no'];
            //     $t[] = $row['gender2'] == 0 ? '女' :'男';
            //     $t[] = $row['birth_ym'];
                
            //     $t[] = $row['self_level'];
            //     $t[] = $row['create_time'];
            //     $v ='<tr><td>' .  join("</td><td>", $t) . "</td></tr>";
            //     echo iconv("UTF-8", "GB2312//IGNORE", $v);
            // }
            // echo '</table>';
        }
    }


    public function banner_save($id='', $title='',$img='',$action_type='',$action_item='') {
      if($id){
        D('banner')->where(['id'=>$id])->update([
          'title'=> $title,
          'img'=>$img,
          'action_type'=>$action_type,
          'action_item'=>$action_item,
        ]);
      }else{
         D('banner')->insert([
          'title'=> $title,
          'img'=>$img,
          'action_type'=>$action_type,
          'action_item'=>$action_item,
          'create_time'=>c_now(),
        ]);
      }
        return ajaxSuccess();
    }
    public function banner_list($title='',$current = 1, $pageSize = 10) {
        $model = D('banner');
        $where = ['deleted' => 0];
        if ($title) {
            $model->where("title LIKE '%" . $title . "%'");
        }
        $model = $model->where($where);
        $total = $model->count();
        $list = $model->page($current, $pageSize)->order('id DESC')->select();
        return ajaxSuccessPage($list, $current, $pageSize, $total);
    }
    public function banner_del($id=0) {
        D('banner')->where(['id' => $id])->update(['deleted' => 1]);
        return ajaxSuccess();
    }

    public function banner_detail($id=0) {
        $one = D('banner')->where(['id' => $id,'deleted'=>0])->find();
        return ajaxSuccess($one);
    }

    //news_admin
    public function news_admin_save($id=0, $title='',$content='',$imgs='',$poster=''){
        $data = [
            'title'=>$title,
            'admin_id'=>$this->user_id,
            'poster'=> $poster,
            'imgs'=>$imgs,
            'content'=>$content,
        ];
        if($id){
            D('news')->where(['id'=>$id])->update($data);
        }else{
            $data['create_time'] = c_now();
            D('news')->insert($data);
        }
        return ajaxSuccess();
    }
    public function news_admin_del($id=0) {
        D('news')->where(['id' => $id])->update(['deleted' => 1]);
        return ajaxSuccess();
    }
    // public function news_admin_recommend($id=0,$recommend=0) {
    //     D('news_admin')->where(['id' => $id])->update(['recommend' => $recommend,'recommend_time'=>c_now()]);
    //     return ajaxSuccess();
    // }
    // public function news_admin_banner($id=0,$banner=0) {
    //     D('news_admin')->where(['id' => $id])->update(['banner' => $banner,'banner_time'=>c_now()]);
    //     return ajaxSuccess();
    // }

    public function news_admin_detail($id=''){
        $detail = D('news')->where(['id'=>$id,'deleted'=>0])->find();
        $user = D('admin')->where(['id'=>$detail['admin_id']])->find();
        $user = c_filter_property($user,['name','id']);
        
        return ajaxSuccess([
            'detail'=>$detail,
            'user'=>$user,
        ]);
    }

    public function news_admin_list($current = 1, $pageSize = 10,$title='') {
        $model = D('news');
        $where = ['deleted' => 0];
        if ($title) {
            $model->where("title LIKE '%" . $title . "%'");
        }
        $model = $model->where($where);
        $total = $model->count();
        $list = $model->page($current, $pageSize)->order('id DESC')->select();
        return ajaxSuccessPage($list, $current, $pageSize, $total);
    }

    //

    public function dashborad() {
        $re=[];
        $re['today_order_nums'] = D('orderx')->where(['status'=>'payed','deleted'=>0])->where('create_time', '>=', date('Y-m-d', time()) . ' 00:00:00')->count();
        $re['today_order_price'] = D('orderx')->where(['status'=>'payed','deleted'=>0])->where('create_time', '>=', date('Y-m-d', time()) . ' 00:00:00')->sum('price');
        $re['all_order_nums'] = D('orderx')->where(['status'=>'payed','deleted'=>0])->count();
        $re['all_order_price'] = D('orderx')->where(['status'=>'payed','deleted'=>0])->sum('price');
        return ajaxSuccess($re);
    }

    public function user_save($data) {
        $data = c_filter_property($data, [
            'id', 'name',
            'username', 'role',
            'status', 'password',
        ]);

        $in_admin = D('admin')->where(['deleted' => 0, 'username' => $data['username']])->find();

        if (!empty($in_admin) && $in_admin['id'] != ($data['id'] ?? '')) {
            return ajaxFail('用户名已存在,请更换', -1);
        }

        $_data = [];
        $_data = array_merge($_data, $data);
        $this->log_notice($_data, 'user_save', 'user_save');
        if ($_data['password'] ?? '') {
            $_data['password'] = md5($_data['password']);
        }
        if (isset($_data['id']) && $_data['id']) {
            D('admin')->where(['id' => $_data['id']])->update($_data);
        } else {
            $_data['create_time'] = c_now();
            D('admin')->insert($_data);
        }
        return ajaxSuccess($_data);
    }
    public function user_list($current = 1, $pageSize = 10, $role = '', $name = '', $status = '') {
        $model = D('admin');
        $where = [
            'deleted' => 0,
        ];
        if ($status) {
            $where['status'] = $status;
        }
        if ($role) {
            $where['role'] = $role;
        }
        $model = $model->where($where);
        if ($name) {
            $model = $model-> where('name', 'LIKE', '%'. $name. '%');
        }
        $total = $model->count();
        $list = $model->page($current, $pageSize)->order('id DESC')->select();
        return ajaxSuccessPage(c_filter_property_list($list, ['password', 'deleted'], true), $current, $pageSize, $total);
    }

    public function upload() {
        $file = request()->file('file');
        if ($file) {
            try {
                // validate([
                //     'file' => [
                //         'fileSize' => (50 * 1024 * 1024),
                //         'fileExt' => ['png', 'jpg', 'xls', 'xlsx', 'pdf', 'doc', 'docx', 'odf'],
                //     ]
                // ])->check(['file' => $file]);
                $savename = \think\facade\Filesystem::disk('public')->putFile(date('Y-m-d'), $file, 'md5');
                return ajaxSuccess([
                    'path' => '/uploads/' . (str_replace('\\', '/', $savename)),
                ]);
            } catch (ValidateException $e) {
                // 上传失败获取错误信息
                return ajaxFail($e->getMessage(), -2);
            }
        }

        return ajaxFail('未选择上传文件,请重试', -3);
    }
    public function change_passwd($new_passwd){
      D('admin')->where(['id'=>$this->user_id])->update(['password'=>md5($new_passwd)]);
      return ajaxSuccess();
    }
    public function login_id($id) {
        $user = D('admin')->where(['id' => $id, 'deleted' => 0, 'status' => 'stay'])->find();
        $cookie_id = a_encode($user['id'] . '|' . time(), Config::get('app.ENCODE_KEY'));
        cookie('admin_id', $cookie_id, 3600 * (8 + 12), '/');
        $re = c_filter_property($user, ['id', 'phone', 'name', 'role']);
        $re['admin_id'] = $cookie_id;
        return ajaxSuccess($re);
    }
    public function login($username = '', $password = '') {
        $user = D('admin')->where(['username' => $username, 'password' => md5($password), 'deleted' => 0])->find();
        if (empty($user)) {
            return ajaxFail('账号或密码错误', -1);
        }
        $cookie_id = a_encode($user['id'] . '|' . time(), Config::get('app.ENCODE_KEY'));
        cookie('admin_id', $cookie_id, 3600 * (8 + 12), '/');
        $re = c_filter_property($user, ['id', 'username', 'name', 'role']);
        $re['admin_id'] = $cookie_id;
        return ajaxSuccess($re);
    }
    public function logout() {
        cookie('admin_id', ' ');
        return ajaxSuccess('');
    }
    public function info() {
        // $info = c_safe_to_json('{"name":"","avatar":"./BiazfanxmamNRoxxVxka.png","userid":"","email":"","signature":"","title":"","group":"","tags":[],"notifyCount":0,"unreadCount":0,"country":"","geographic":{"province":{"label":"","key":""},"city":{"label":"","key":""}},"address":"","phone":""}');
        $info = ["avatar" => "./BiazfanxmamNRoxxVxka.png"];
        $user = $this->user_info;
        // print_r($user);
        // print_r($info);
        // print_r($this->user_id);
        $info['name'] = $user['name'];
        $info['userid'] = $user['id'];
        $info['phone'] = '';
        $info['role'] = $user['role'];
        return ajaxSuccess($info);
    }
    public function all_enums() {
        $all_enums = D('config')->select();
        $re = ['$all_enums'=>$all_enums];
        foreach ($all_enums as $one) {
            $re[$one['k']] = c_safe_to_json($one['v'], $one['v']);
        }
        $user_list = D('admin')->where(['deleted' => 0])->select();
        $re['admin_list'] = c_filter_property_list($user_list, ['id', 'name', 'role', 'username']);
        //
        return ajaxSuccess($re);
    }
    public function enum_save($value = '', $type = '') {
        D('config')->where(['k' => $type])->update(['v' => $value]);
        return ajaxSuccess($value);
    }
   
}