
namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use think\Db;

class {$humpName} extends Permissions
{
    private function getModel()
    {
        return new \app\common\model\{$humpName}();
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [];
            {volist name="$fieldsInfo" id="vo"}
                {php}
                    if(empty($vo['ShowSearch'])){
                        continue;
                    }
                {/php}

                {if condition="$vo['Field'] == 'id'"}
                    if (isset($post['ids']) and !empty($post['ids'])) {
                        $where['id'] = ['in', $post['ids']];
                    }
                    {php}continue;{/php}
                {/if}

                {if condition="in_array($vo['Component'],[0,3,4,7])"}
                    {php}//输入框,文章段落,图片,复选框{/php}
                    if (!empty($post["{$vo['Field']}"])) {
                        $where["{$vo['Field']}"] = ['like', '%' . $post["{$vo['Field']}"] . '%'];
                    }
                    {php}continue;{/php}
                {/if}

                {if condition="in_array($vo['Component'],[1,5,6,8])"}
                    {php}//数字,开关,下拉框,单选{/php}
                    if (isset($post["{$vo['Field']}"]) and ""!=$post["{$vo['Field']}"]) {
                        $where["{$vo['Field']}"] = $post["{$vo['Field']}"];
                    }
                    {php}continue;{/php}
                {/if}

                {if condition="$vo['Component'] == 2"}
                    {php}//时间{/php}
                    if (isset($post["{$vo['Field']}"]) and !empty($post["{$vo['Field']}"])) {
                        $timerang = explode(' - ', $post["{$vo['Field']}"]);
                        $min_time = strtotime($timerang[0]);
                        $max_time = $timerang[0] == $timerang[1] ? $min_time + 24 * 3600 - 1 : strtotime($timerang[1]??'');
                        $where["{$vo['Field']}"] = [['>=', $min_time], ['<=', $max_time]];
                    }
                    {php}continue;{/php}
                {/if}
            {/volist}

            $model = $this->getModel();
            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order({if condition="array_key_exists('sort',$fieldsInfo)"}'sort desc'{else/}'id desc'{/if})->select();

            {volist name="$fieldsInfo" id="vo"}
                {if condition="$vo['Component'] == 4"}
                    foreach ($data as $key => $value) {
                        $value['{$vo['Field']}_url'] = geturl($value['{$vo['Field']}']);
                        $data[$key] = $value;
                    }
                {/if}
            {/volist}
            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            return $this->fetch();
        }
    }


{if condition="array_key_exists('update',$crud) or array_key_exists('create',$crud)"}
    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $model = $this->getModel();
        $post = $this->request->post();
        if ($this->request->isPost()) {

            {volist name="$fieldsInfo" id="vo"}
                {php}
                    if(empty($vo['ShowEdit'])){
                        continue;
                    }
                    if(in_array($vo['Field'],['id'])){
                        continue;
                    }
                {/php}
                {if condition="$vo['Component'] == 2"}
                    if (isset($post['{$vo['Field']}']) && !empty($post['{$vo['Field']}'])) {
                        $post['{$vo['Field']}'] = strtotime($post['{$vo['Field']}']);
                    }
                {/if}
                {if condition="$vo['Component'] == 7"}
                    if (isset($post['{$vo['Field']}']) && !empty($post['{$vo['Field']}'])) {
                        $post['{$vo['Field']}'] = implode(',',$post['{$vo['Field']}']);
                    }
                {/if}
            {/volist}

            //验证
            $validate = new \think\Validate([
                {volist name="$fieldsInfo" id="vo"}
                    {php}
                        if(empty($vo['ShowEdit'])){
                            continue;
                        }
                        $field_key = $vo['Field'];
                        if(in_array($field_key,['id','create_time','update_time'])){
                            continue;
                        }
                        if(!empty($vo['Comment'])){
                            $comment = $vo['Comment'];
                            if(in_array($vo['Component'],[5,6,7,8])){
                                $arr = explode(':',$vo['Comment']);
                                $comment = count($arr)==2 ? $arr[0] : $vo['Field'];
                            }
                            $field_key.= "|" . $comment;
                        }
                        $field_val = "";
                        if($vo['Default'] === null){
                            $field_val.= "require";
                        }
                        if(startWith($vo["Type"],'int') || startWith($vo["Type"],'tinyint')){
                            $field_val .= empty($field_val) ? "number" : "|number";
                        }
                        if(startWith($vo["Type"],'varchar')){
                            $maxLen = str_replace(['varchar(',')'],['',''],$vo["Type"]);
                            $field_val .= empty($field_val) ? "max:".$maxLen : "|max:".$maxLen;
                        }
                    {/php}
                    {notempty name="$field_val"}
                    ['{$field_key}', '{$field_val}'],
                    {/notempty}
                {/volist}
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
        }

        if ($id > 0) {
            {if condition="array_key_exists('update',$crud)"}
                //修改
                $data = $model->where('id', $id)->find();
                if (empty($data)) {
                    $this->error('id不正确');
                }
                if ($this->request->isPost()) {
                    if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                        $this->error('修改失败');
                    } else {
                        $this->success('修改成功');
                    }
                } else {
                    $this->assign('data', $data);
                    return $this->fetch();
                }
            {/if}
        } else {
            {if condition="array_key_exists('create',$crud)"}
                //新增
                if ($this->request->isPost()) {
                    if (false == $model->allowField(true)->save($post)) {
                        $this->error('添加失败');
                    } else {
                        $this->success('添加成功', 'index');
                    }
                } else {
                    return $this->fetch();
                }
            {/if}
        }
    }
{/if}

{if condition="array_key_exists('delete',$crud)"}
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            if (false == $this->getModel()->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            if ($this->getModel()->where('id', 'in', $ids)->delete()) {
                $this->success('删除成功');
            }
        }
    }
{/if}


{volist name="$fieldsInfo" id="vo"}
    {if condition="$vo['Component'] == 5"}
        public function {$vo['Field']}()
        {
            if ($this->request->isPost()) {
                $post = $this->request->post();
                if (false == $this->getModel()->where('id', $post['id'])->update(['{$vo['Field']}' => $post['status']])) {
                    $this->error('设置失败');
                } else {
                    $this->success('设置成功', 'index');
                }
            }
        }
    {/if}
{/volist}


{if condition="array_key_exists('sort',$fieldsInfo)"}
    public function sort()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $i = 0;
            foreach ($post['ids'] as $k => $id) {
                $sort = Db::name('{$underLineName}')->where('id', $id)->value('sort');
                $newsort = $post['sorts'][$k]??$sort;
                if ($sort != $newsort) {
                    if (false == Db::name('{$underLineName}')->where('id', $id)->update(['sort' => $newsort])) {
                        $this->error('更新失败');
                    } else {
                        $i++;
                    }
                }
            }
            $this->success('成功更新' . $i . '个数据', 'index');
        }
    }
{/if}

}