<?php

namespace app\admin\controller;

use app\admin\AdminBaseController;
use app\admin\validate\SmsTemplateValidate;
use app\common\model\ArticleModel;
use app\common\model\ArticleCateModel;
use app\admin\validate\ArticleCateValidate;
use app\admin\validate\ArticleValidate;
use app\common\model\SmsTemplateModel;
use think\exception\ValidateException;

class SmsTemplate extends AdminBaseController
{
    /**
     * 列表
     */
    public function index()
    {
        return view();
    }

    public function templateForm()
    {
        $id   = input('id/d, 0');
        $info = SmsTemplateModel::find($id);
        return view('', [
            'info' => $info,
        ]);
    }

    public function listTemplate()
    {
        $list  = SmsTemplateModel::limit(input('limit'))
            ->page(input('page'))
            ->select();
        $count = SmsTemplateModel::count();
        if ($count == 0) {
            ajax_return(1, '未查询到数据');
        }
        list_return($list, $count);
    }

    public function delTemplate()
    {
        $id = input('id/d', 0);
        SmsTemplateModel::destroy($id);
        ajax_return();
    }

    public function editTemplate()
    {
        $data = input('post.');
        try {
            validate(SmsTemplateValidate::class)->check($data);
        } catch (ValidateException $e) {
            ajax_return(1, $e->getError());
        }

        if (empty($data['id'])) {
            $check = SmsTemplateModel::where('code', $data['code'])->find();
            if (!empty($check)) {
                ajax_return(1, '该编号已存在');
            }
            SmsTemplateModel::create($data);
        } else {
            $check = SmsTemplateModel::where('code', $data['code'])->where('id', '<>', $data['id'])->find();
            if (!empty($check)) {
                ajax_return(1, '该编号已存在');
            }
            SmsTemplateModel::update($data, ['id' => $data['id']]);
        }

        ajax_return();
    }
}