<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\PointLog as pointLogModel;
use think\Db;

class PointLog extends Permissions
{

    public function index()
    {
        if ($this->request->isAjax()) {

            $post = $this->request->param();

            $where = [];
            if (isset($post['user_id']) and !empty($post['user_id'])) {
                $where['user_id'] = $post['user_id'];
            }
            if (isset($post['type']) and !empty($post['type'])) {
                $where['type'] = $post['type'];
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $timerang = explode(' - ', $post['create_time']);
                $min_time = strtotime($timerang[0]);
                $max_time = strtotime($timerang[1]);
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $model = new pointLogModel();
            $count = $model->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('create_time desc')->select();

            foreach ($data as $k => $v) {
                $v['type_text'] = $v->type_text;
                $data[$k] = $v;
            }

            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            $this->assign("types", pointLogModel::TYPES);
            return $this->fetch();
        }
    }

    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];

            // 启动事务
            Db::startTrans();
            try {
                $model = new pointLogModel();
                if ($model->where('id', 'in', $ids)->delete()) {
                }
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('删除失败');
            }
            $this->success('删除成功');
        }
    }
}