<?php

namespace app\controller\manager;

use app\model\BusinessCircle as BusinessCircleModel;

use app\repository\BusinessRepository;
use Exception;
use think\facade\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\response\Json;
use think\response\View;

/**
 * 商圈管理
 *
 * Class BusinessCircle
 * @package app\controller\manager
 */
class BusinessCircle extends Base
{
    /**
     * 编辑
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function edit()
    {
        $id = input('id/d', 0);

        if (!$info = BusinessCircleModel::findById($id)) {
            return $this->json(4001, '记录不存在');
        }

        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'sort|排序'  => 'require|number',
                'name|标题'  => 'require|max:100',
                'province|省市区'  => 'require',
                'city|省市区'  => 'require',
                'county|省市区'  => 'require',
                'business_address|详细地址'  => 'require',
                'lng|经度'  => 'require',
                'lat|纬度'  => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            Db::startTrans();
            try {
                $info->save($item);
                Db::commit();
                return $this->json();
            } catch (ValidateException $e) {
                Db::rollback();
                return $this->json(4001, $e->getError());
            }
        }
        $disabled[]              = $id;
        $this->data['item']      = $info;

        return $this->view();
    }

    /**
     * 添加
     *
     * @return Json|View
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'name|标题' => 'require|max:100',
            ]);

            if ($validate !== true) {
                return $validate;
            }
            $item['create_time'] = date("Y-m-d H:i:s");
            try {
                BusinessCircleModel::create($item);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }

        return $this->view();
    }


    /**
     * 删除
     * @return Json
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }
        $ids = $this->request->param('ids/a', []);
        foreach ($ids as $item){
            if(count(BusinessRepository::getInstance()->getByCircleId($item)->toArray())){
                return $this->json("4002","该商圈存在绑定商家  不能删除");
            }
        }
        BusinessCircleModel::destroy($ids);
        return $this->json();
    }

    /**
     * 单个字段编辑
     *
     * @return Json
     * @throws Exception
     */
    public function modify(): Json
    {
        if ($this->request->isPost()) {
            $item     = input('post.');
            $validate = $this->validateByApi($item, [
                'field' => 'require',
                'value' => 'require',
            ]);

            if ($validate !== true) {
                return $validate;
            }

            if (!$info = BusinessCircleModel::findById($item['id'])) {
                return $this->json(4001, '记录不存在');
            }

            $update = [$item['field'] => $item['value']];

            try {
                $info->save($update);
                return $this->json();
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getError());
            }
        }
        return $this->json(4000, '非法请求');
    }
    /**
     * 列表
     *
     * @return Json|View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $menus = BusinessCircleModel::getList();
            $res   = [
                'code'  => 0,
                'msg'   => 'success',
                'count' => $menus->count(),
                'data'  => $menus->toArray(),
            ];
            return json($res);
        }
        return $this->view();
    }


}