<?php
namespace app\controller\api;

use app\exception\RepositoryException;
use app\repository\AccountRepository;
use app\repository\BusinessRepository;
use app\repository\DictionaryRepository;
use app\validate\BusinessValidate;
use think\exception\ValidateException;
use app\model\Business as BusinessModel;

/**
 * 商家端:商家
 *
 * Class Business
 * @package app\controller\api
 */
class Business extends Base
{
    /**
     * 商家注册
     *
     * 方式1:注册为自然商家
     * 由系统后台工作人员审核
     *
     * 重新编辑注册则覆盖之前的审核信息,并重新进行审核
     */
    public function registerByNormal()
    {
        $params = [
            'type'=> $this->request->param('type/d', 0),
            'business_name'=> $this->request->param('business_name', ''),
            'business_subtitle'=> $this->request->param('business_subtitle', ''),
            'business_license'=> $this->request->param('business_license', ''),
            'contact_name'=> $this->request->param('contact_name', ''),
            'contact_phone'=> $this->request->param('contact_phone', ''),
            'lat'=> $this->request->param('lat', ''),
            'lng'=> $this->request->param('lng', ''),
            'province'=> $this->request->param('province', ''),
            'city'=> $this->request->param('city', ''),
            'county'=> $this->request->param('county', ''),
            'business_address' => $this->request->param('business_address', ''),
            'business_circle_id' => $this->request->param('business_circle_id/d', 0),
        ];

        $accountId  = $this->request->user['user_id'] ?? 0;


        try {
            $validate   = new BusinessValidate();
            $busRepo    = BusinessRepository::getInstance();
            $dicRepo    = DictionaryRepository::getInstance();
            $accountRepo    = AccountRepository::getInstance();

            $account = $accountRepo->findById($accountId);
            if (empty($account)) {
                throw new ValidateException('无效请求!');
            }

            if (!$validate->scene('registerByNormal')->check($params)) {
                throw new ValidateException($validate->getError());
            }

            $businessCategory   = $dicRepo->findBusinessTypeById($params['type']);
            if (empty($businessCategory)) {
                throw new ValidateException('请选择正确的商家分类信息!');
            }

            if ($params['business_circle_id'] > 0) {
                $businessCircle = $dicRepo->findBusinessCircleById($params['business_circle_id']);
                if (empty($businessCircle)) {
                    throw new ValidateException('请选择正确的商圈信息!');
                }
                $params['business_circle']  = $businessCircle['name'];
            }

            $business = null;
            if (isset($account['business_code']) && !empty($account['business_code'])) {
                $business = $busRepo->findOneByWhere(['code'=> $account['business_code']]);
            }

            $params['create_time']   = date('Y-m-d H:i:s');
            $params['is_delete']    = 0;
            $params['state']        = BusinessModel::state_reviewing;
            $params['enable']       = 0;
            $params['type_name']    = $businessCategory['name'];

            if ($business) {
                if ($business['state'] == BusinessModel::state_reviewing) {
                    throw new ValidateException('商户认证审批中,请勿重复提交!');
                }

                // 更新审批信息,重新审批
                $params['update_time']  = date('Y-m-d H:i:s');
                $business = $business->save($params);

            } else {
                // 添加审批记录
                $businessCode   = createUuid();
                $params['code'] = $businessCode;
                $business = $busRepo->create($params);
                if (!$business) {
                    throw new RepositoryException('服务器繁忙!商户认证申请提交失败!');
                }

                $account->save(['business_code' => $businessCode]);
            }

            $result = $busRepo->formatFrontBusinessInfo($business->toArray());
            return $this->json(0, 'success', $result);
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (RepositoryException | \Exception $e) {
            return $this->json(5001, '服务器繁忙!商户认证申请提交失败!');
        }
    }

    /**
     * 商家注册
     *
     * 方式2:注册为平台代理商下的商家
     * 由平台代理商工作人员审核
     *
     * 重新编辑注册则覆盖之前的审核信息,并重新进行审核
     */
    public function registerByAgency()
    {
        $params = [
            'type'=> $this->request->param('type/d', 0),
            'business_name'=> $this->request->param('business_name', ''),
            'business_subtitle'=> $this->request->param('business_subtitle', ''),
            'business_license'=> $this->request->param('business_license', ''),
            'contact_name'=> $this->request->param('contact_name', ''),
            'contact_phone'=> $this->request->param('contact_phone', ''),
            'lat'=> $this->request->param('lat', ''),
            'lng'=> $this->request->param('lng', ''),
            'province'=> $this->request->param('province', ''),
            'city'=> $this->request->param('city', ''),
            'county'=> $this->request->param('county', ''),
            'business_address' => $this->request->param('business_address', ''),
            'business_circle_id' => $this->request->param('business_circle_id/d', 0),
            'agency_code'   => $this->request->param('agency_code', ''),
        ];

        $accountId  = $this->request->user['user_id'] ?? 0;

        try {
            $validate   = new BusinessValidate();
            $busRepo    = BusinessRepository::getInstance();
            $dicRepo    = DictionaryRepository::getInstance();
            $accountRepo    = AccountRepository::getInstance();

            $account = $accountRepo->findById($accountId);
            if (empty($account)) {
                throw new ValidateException('无效请求!');
            }

            if (!$validate->scene('registerByAgency')->check($params)) {
                throw new ValidateException($validate->getError());
            }

            $businessCategory   = $dicRepo->findBusinessTypeById($params['type']);
            if (empty($businessCategory)) {
                throw new ValidateException('请选择正确的商家分类信息!');
            }

            if ($params['business_circle_id'] > 0) {
                $businessCircle = $dicRepo->findBusinessCircleById($params['business_circle_id']);
                if (empty($businessCircle)) {
                    throw new ValidateException('请选择正确的商圈信息!');
                }
                $params['business_circle']  = $businessCircle['name'];
            }

            $agencyBusiness = $busRepo->findOneByWhere(['code'=> $params['agency_code'], 'is_agency'=> self::BOOL_TRUE, 'state' => BusinessModel::state_on]);
            if (empty($agencyBusiness) || $agencyBusiness['is_delete'] == self::BOOL_TRUE) {
                throw new ValidateException('没有相关的平台商记录!');
            } elseif ($agencyBusiness['enable'] == self::BOOL_TRUE) {
                throw new ValidateException('该平台商已被封禁!');
            }

            $business = null;
            if (isset($account['business_code']) && !empty($account['business_code'])) {
                $business = $busRepo->findOneByWhere(['code'=> $account['business_code']]);
            }

            $params['create_time']  = date('Y-m-d H:i:s');
            $params['is_delete']    = 0;
            $params['state']        = BusinessModel::state_reviewing;
            $params['enable']       = 0;
            $params['type_name']    = $businessCategory['name'];

            if ($business) {
                if ($business['state'] == BusinessModel::state_reviewing) {
                    throw new ValidateException('商户认证审批中,请勿重复提交!');
                }

                // 更新审批信息,重新审批
                $params['update_time']  = date('Y-m-d H:i:s');
                $business = $business->save($params);

            } else {
                // 添加审批记录
                $businessCode   = createUuid();
                $params['code'] = $businessCode;
                $business = $busRepo->create($params);
                if (!$business) {
                    throw new RepositoryException('服务器繁忙!商户认证申请提交失败!');
                }

                $account->save(['business_code' => $businessCode]);
            }

            $result = $busRepo->formatFrontBusinessInfo($business->toArray(), [2]);
            return $this->json(0, 'success', $result);
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (RepositoryException | \Exception $e) {
            return $this->json(5001, '服务器繁忙!商户认证申请提交失败!');
        }
    }


}