<?php

namespace app\admin\controller\user;

use app\admin\controller\AuthController;
use app\admin\model\user\UserChannel as ChannelModel;
use crmeb\services\JsonService;
use crmeb\services\UtilService;
use crmeb\services\FormBuilder as Form;
use think\facade\Route as Url;

/**
 * Class UserGroup
 * @package app\admin\controller\user
 */
class UserChannel extends AuthController
{
    /**
     * 会员分组页面
     * @return string
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * 分组列表
     */
    public function channelList()
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 20],
        ]);
        return JsonService::successlayui(ChannelModel::getList($where));
    }

    /**
     * 添加/修改分组页面
     * @param int $id
     * @return string
     */
    public function addChannel($id = 0)
    {
        $group = ChannelModel::get($id);
        $f = [];
        if (!$group) {
            $f[] = Form::input('name', '渠道名称', '')->col(30);
            $f[] = Form::input('code', '渠道代码', '')->col(30);
            $f[] = Form::textarea('desc', '说明', '')->col(512)->rows(10);
        } else {
            $f[] = Form::input('name', '渠道名称', $group->getData('name'))->col(30);
            $f[] = Form::input('code', '渠道代码', $group->getData('code'))->col(30);
            $f[] = Form::textarea('desc', '说明', $group->getData('desc'))->col(512)->rows(10);
        }
        $form = Form::make_post_form('会员渠道', $f, Url::buildUrl('saveChannel', ['id' => $id]));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * 添加/修改
     * @param int $id
     */
    public function saveChannel($id = 0)
    {
        $data = UtilService::postMore([
            ['name', ''],
            ['code', ''],
            ['desc', ''],
        ]);
        if ($id) {
            if (ChannelModel::where('id', $id)->update($data)) {
                return JsonService::success('修改成功');
            } else {
                return JsonService::fail('修改失败或者您没有修改什么！');
            }
        } else {
            if ($res = ChannelModel::create($data)) {
                return JsonService::success('保存成功', ['id' => $res->id]);
            } else {
                return JsonService::fail('保存失败！');
            }
        }
    }

    /**
     * 删除
     * @param $id
     * @throws \Exception
     */
    public function delete($id)
    {
        if (!$id) return $this->failed('数据不存在');
        if (!ChannelModel::be(['id' => $id])) {
            return $this->failed('渠道数据不存在');
        }
        if (!ChannelModel::where('id', $id)->delete()) {
            return JsonService::fail(ChannelModel::getErrorInfo('删除失败,请稍候再试!'));
        } else {
            return JsonService::successful('删除渠道成功!');
        }
    }
}
