<?php

namespace app\admin\controller\wechat;

use app\common\controller\Backend;
use app\admin\model\WechatResponse;

/**
 * 微信模版列表
 *
 * @icon fa fa-circle-o
 */
class Plan extends Backend
{

    protected $model = null;
    protected $noNeedRight = ['check_text_unique'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\WechatPlan;
        $this->view->assign("hidedataList", $this->model->getHidedataList());
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                $data = $this->selectpage()->getData();
                return $data;
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            /**
             * 获取企业信息
             */
            $where1  = is_sys_admin();
            $list = $this->model
                ->where($where)->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $row->save($params);
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 判断模版编号是否唯一
     * @internal
     */
    public function check_text_unique()
    {
        $row = $this->request->post("row/a");
        $except = $this->request->post("except");
        $text = isset($row['plan_id']) ? $row['plan_id'] : '';
        if ($this->model->where('plan_id', $text)->where(function ($query) use ($except) {
                if ($except) {
                    $query->where('plan_id', '<>', $except);
                }
            })->count() == 0) {
            $this->success();
        } else {
            $this->error(__('Text already exists'));
        }
    }

}
