<?php


namespace app\badminapi\controller\merchant;


use app\badminapi\controller\AuthController;
use app\models\article\ArticleCategory;
use app\models\merchant\Industry as IndustryModel;
use crmeb\services\FormBuilder as Form;
use crmeb\basic\BaseModel;
use crmeb\services\UtilService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Route as Url;
use think\Exception;
use think\Response;

class Industry extends AuthController
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 获取行业列表
     * @return mixed
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function get_list()
    {
        $search = UtilService::getMore([
            ['name', ''],
            ['pid', ''],
            ['is_show', ''],
            ['page', 1],
            ['limit', 10],
            ['type', 0]
        ], $this->request, false);
        if ($search['type']) {
            $list = IndustryModel::getList();
            $list['list'] = ArticleCategory::tidyTree($list['list']);
        } else {
            $list = IndustryModel::getList($search);
            $list['list'] = array_slice(ArticleCategory::tidyTree($list['list']), ((int)$search['page'] - 1) * $search['limit'], $search['limit']);
        }
        return $this->success($list);
    }

    /**
     * 树形列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function tree_list($type)
    {
        $list = IndustryModel::getTierList(null, $type);
        return $this->success($list);
    }

    /**
     * 修改状态
     * @param string $is_show
     * @param string $id
     * @return Response
     */
    public function set_show($id = '', $is_show = '')
    {
        ($is_show == '' || $id == '') && $this->fail('缺少参数');
        if (IndustryModel::setIndustryShow($id, (int)$is_show)) {
            return $this->success($is_show == 1 ? '显示成功' : '隐藏成功');
        } else {
            return $this->fail(IndustryModel::getErrorInfo($is_show == 1 ? '显示失败' : '隐藏失败'));
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $field = [
            Form::select('pid', '父级')->setOptions(function () {
                $list = IndustryModel::getTierList(null, 0);
                $menus = [['value' => 0, 'label' => '顶级菜单']];
                foreach ($list as $menu) {
                    $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['name']];
                }
                return $menus;
            })->filterable(1),
            Form::input('name', '行业名称'),
            Form::textarea('info', '详细描述'),
            Form::number('sort', '排序')->value(0),
            Form::radio('is_show', '状态', 1)->options([['label' => '显示', 'value' => 1], ['label' => '隐藏', 'value' => 0]])
        ];
        return $this->makePostForm('添加行业', $field, Url::buildUrl('/badminapi/industry/add/0'), 'POST');
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $c = IndustryModel::get($id);
        if (!$c) return $this->fail('数据不存在!');
        $field = [
            Form::select('pid', '父级', (string)$c->getData('pid'))->setOptions(function () use ($id) {
                $list = IndustryModel::getTierList(IndustryModel::where('id', '<>', $id), 0);
                $menus = [['value' => 0, 'label' => '顶级菜单']];
                foreach ($list as $menu) {
                    $menus[] = ['value' => $menu['id'], 'label' => $menu['html'] . $menu['name']];
                }
                return $menus;
            })->filterable(1),
            Form::input('name', '行业名称', $c->getData('name')),
            Form::textarea('info', '详细描述', $c->getData('info')),
            Form::number('sort', '排序', $c->getData('sort')),
            Form::radio('is_show', '状态', $c->getData('is_show'))->options([['label' => '显示', 'value' => 1], ['label' => '隐藏', 'value' => 0]])
        ];
        return $this->makePostForm('编辑行业', $field, Url::buildUrl('/badminapi/industry/add/' . $id), 'POST');
    }

    /**
     * 快速编辑
     * @param string $id
     * @return Response
     * @throws \Exception
     */
    public function set_industry($id)
    {
        $data = UtilService::postMore([
            ['field', 'name', '', '', 'empty_check', '缺少参数'],
            ['value', '', '', '', 'empty_check', '缺少参数']
        ]);
        if (!$id) return $this->fail('缺少参数');
        if (IndustryModel::where('id', $id)->update([$data['field'] => $data['value'], 'update' => time()]))
            return $this->success('保存成功');
        else
            return $this->fail('保存失败');
    }

    /**
     * 新增/修改行业
     * @param int $id
     * @return mixed
     * @throws DbException
     */
    public function add_industry($id = 0)
    {
        $data = UtilService::postMore([
            ['name', '', '', '', 'empty_check', '请输入行业名'],
            ['pid', 0],
            ['info', ''],
            ['is_show', 0],
            ['sort', 0]
        ]);
        if ($id) {
            if (!IndustryModel::vaildWhere()->where('id', $id)->find()) {
                return $this->fail('所选行业不存在');
            }
        }
        if ($data['pid'] != 0) {
            if (!IndustryModel::vaildWhere()->where('id', $data['pid'])->find()) {
                return $this->fail('上级行业不存在');
            }
        }
        BaseModel::beginTrans();
        try {
            $data['update'] = time();
            if ($id) {
                $res = IndustryModel::edit($data, $id);
            } else {
                $data['add_time'] = time();
                $res = IndustryModel::create($data);
            }
            if ($res) {
                BaseModel::commitTrans();
                return $this->success('操作成功');
            } else {
                BaseModel::rollbackTrans();
                return $this->fail('操作失败');
            }
        } catch (Exception $e) {
            BaseModel::rollbackTrans();
            return $this->fail($e->getMessage());
        } catch (DbException $e) {
            BaseModel::rollbackTrans();
            return $this->fail($e->getMessage());
        }
    }

    /**
     * 获取指定资源
     *
     * @param int $id
     * @return Response
     */
    public function get_industry($id)
    {
        return $this->success('ok', IndustryModel::get($id) ? IndustryModel::get($id)->toArray() : []);
    }


    /**
     * 删除指定资源
     *
     * @param int $id
     * @return Response
     */
    public function delete($id)
    {
        if (!IndustryModel::delIndustry($id))
            return $this->fail(IndustryModel::getErrorInfo('删除失败,请稍候再试!'));
        else
            return $this->success('删除成功!');
    }
}