<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\model\dealer;

use app\api\service\User as UserService;
use app\common\enum\dealer\apply\ApplyStatus as ApplyStatusEnum;
use app\common\enum\dealer\apply\ApplyType as ApplyTypeEnum;
use app\common\model\dealer\Apply as ApplyModel;
use cores\exception\BaseException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 分销商申请模型
 * Class Apply
 * @package app\api\model\dealer
 */
class Apply extends ApplyModel
{
    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'create_time',
        'update_time',
    ];

    /**
     * 是否为分销商申请中
     * @param int $userId
     * @return bool
     */
    public static function isApplying(int $userId): bool
    {
        $detail = self::detail(['user_id' => $userId]);
        return $detail && (int)$detail['apply_status'] === ApplyStatusEnum::WAIT;
    }

    /**
     * 提交申请
     * @param array $data 表单数据
     * @return mixed
     * @throws \cores\exception\BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws BaseException
     */
    public function submit(array $data)
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 成为分销商条件
        $config = Setting::getItem('condition');
        // 数据整理
        $data = [
            'user_id' => $userId,
            'real_name' => trim($data['name']),
            'mobile' => trim($data['mobile']),
            'referee_id' => Referee::getRefereeUserId($userId, 1),
            'apply_type' => $config['become'],
            'apply_time' => time(),
            'store_id' => self::$storeId,
        ];
        if ($config['become'] == ApplyTypeEnum::AUDIT) {
            $data['apply_status'] = ApplyStatusEnum::WAIT;
        } elseif ($config['become'] == ApplyTypeEnum::PASS) {
            $data['apply_status'] = ApplyStatusEnum::PASS;
        }
        return $this->add($data);
    }

    /**
     * @notes:申请服务商
     * @param $data
     * @return bool
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function applyServiceProviders($data): bool
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 成为分销商条件
        $config = Setting::getItem('condition');
        $info = self::get(['user_id' => $userId]);
        if (!empty($info)) {
            throwError('您已申请服务商,请勿重复提交');
        }
        // 数据整理
        $data = [
            'user_id' => $userId,
            'real_name' => trim($data['real_name']),
            'mobile' => trim($data['mobile']),
            'referee_id' => Referee::getRefereeUserId($userId, 1),
            'apply_type' => $config['become'],
            'apply_time' => time(),
            'store_id' => self::$storeId,
            'shop_type' => $data['shop_type'],
            'shop_name' => $data['shop_name'],
            'business' => $data['business'],
            'city' => $data['city'],
        ];
        if ($config['become'] == ApplyTypeEnum::AUDIT) {
            $data['apply_status'] = ApplyStatusEnum::WAIT;
        } elseif ($config['become'] == ApplyTypeEnum::PASS) {
            $data['apply_status'] = ApplyStatusEnum::PASS;
        }
        return $this->add($data);
    }

    /**
     * @notes:更新服务商申请
     * @param $data
     * @return bool
     * @throws BaseException
     * @author: wanghousheng
     */
    public function editApplyServiceProviders($data): bool
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        $info = self::get(['user_id' => $userId]);
        if (empty($info)) {
            throwError('申请记录不存在');
        }
        $info = $info->toArray();
        if ($info['apply_status'] == ApplyStatusEnum::PASS) {
            throwError('您已通过申请,请勿重复提交');
        }
        // 数据整理
        $data = [
            'real_name' => trim($data['real_name']),
            'mobile' => trim($data['mobile']),
            'shop_type' => $data['shop_type'],
            'shop_name' => $data['shop_name'],
            'business' => $data['business'],
            'city' => $data['city'],
        ];
        if ($this->update($data, ['user_id' => $userId])) {
            return true;
        }
        return false;
    }

    /**
     * @notes:申请记录详情
     * @return Apply|array|null
     * @throws BaseException
     * @author: wanghousheng
     */
    public function getApplyInfo()
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        return self::get(['user_id' => $userId]);
    }

    /**
     * 更新分销商申请信息
     * @param array $data
     * @return bool
     * @throws BaseException
     */
    private function add(array $data): bool
    {
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        // 实例化模型
        $model = self::detail(['user_id' => $userId]) ?: $this;
        // 更新记录
        return $this->transaction(function () use ($model, $userId, $data) {
            // 保存申请信息
            $model->save($data);
            // 无需审核,自动通过
            if ($data['apply_type'] == ApplyStatusEnum::PASS) {
                // 新增分销商用户记录
                User::add($userId, [
                    'real_name' => $data['real_name'],
                    'mobile' => $data['mobile'],
                    'referee_id' => $data['referee_id']
                ]);
            }
            return true;
        });
    }
}