Ticket.php 9.0 KB
<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\api\model\UserTicket;
use app\common\controller\Backend;
use think\Db;
/**
 * 优惠券管理
 *
 * @icon fa fa-ticket
 */
class Ticket extends Backend
{
    
    /**
     * Ticket模型对象
     * @var \app\admin\model\Ticket
     */
    protected $model = null;
    protected $searchFields = 'ch_name,en_name';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Ticket;
        $this->view->assign("settingShareList", $this->model->getSettingShareList());
        $this->view->assign("settingMonthList", $this->model->getSettingMonthList());
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("selectTypeList", ['1'=>'全部','2'=>'普通用户','3'=>'会员','4'=>'员工','5'=>'一级代理','6'=>'二级代理','7'=>'三级代理','8'=>'指定用户']);
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $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 . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if ($params['type'] == 2 && empty($params['fill_price'])) $this->error('使用价格不能为空');
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } 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) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        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");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $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);
                    }
                    if ($params['type'] == 2 && empty($params['fill_price'])) $this->error('使用价格不能为空');
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } 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) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 发放
     */
    public function grant()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $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 . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $userModel = new User();
                    $where = [];
                    $userTicketModel = new UserTicket();
                    if ($params['type'] == 8 && !$params['user_ids']) $this->error('用户不能为空');
                    elseif ($params['type'] == 2) $where['type'] = 1;
                    elseif ($params['type'] == 3) $where['type'] = 2;
                    elseif ($params['type'] == 4) $where['type'] = 3;
                    elseif ($params['type'] == 5) $where['type'] = 4;
                    elseif ($params['type'] == 6) $where['type'] = 5;
                    elseif ($params['type'] == 7) $where['type'] = 6;
                    else $userIds = explode(',',$params['user_ids']);

                    if (empty($userIds)) $userIds = $userModel->where($where)->column('id');
                    if (!$userIds) $this->error('暂无此类型用户');
                    //默认全部用户
                    $ticketInfo = $this->model->where('id',$params['ticket_id'])->find();
                    $data = [];
                    foreach ($userIds as $k => $userId){
                        $date = explode('-',date('Y-m-d',strtotime('+ '.$ticketInfo['days'].'day')));
                        $time = mktime(23,59,00,$date[1],$date[2],$date[0]);
                        $data[] = [
                            'user_id' => $userId,
                            'ticket_id' => $ticketInfo['id'],
                            'fill_price'=>$ticketInfo['fill_price'],
                            'ch_name' => $ticketInfo['ch_name'],
                            'en_name' => $ticketInfo['en_name'],
                            'price' => $ticketInfo['price'],
                            'type' => 1, //获取途径:1=后台发放,2=其他
                            'status' => 1, //状态:1=未使用,2=已使用,3=已过期
                            'pasttime' => $time //过期时间
                        ];
                    }
                    $result = $userTicketModel->saveAll($data);
                    Db::commit();
                } 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) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
}