<?php
/**
 * Created by PhpStorm.
 * User: pengfei@yidian-inc.com
 * Date: 2021/8/20 2:23 下午
 */

namespace App\Services\marketing;

use App\Exception\custom\MarketingException;
use App\Models\marketing\mysql\ColonelDistributorColonel;
use App\Models\marketing\mysql\ColonelDistributorColonelApply;
use App\Models\marketing\mysql\TakePlace;
use App\Models\user\mysql\UserWechatBind;
use App\Models\marketing\mysql\Marketing;
use Exception;

class ColonelService
{
    /**
     * Notes: 申请成为团长
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/20 4:29 下午
     * @param array $params
     * @return int $applyId
     * @throws MarketingException
     */
    public static function apply(array $params): int
    {
        if (ColonelDistributorColonelApply::existUser($params['user_id'])) {
            throw new MarketingException(MarketingException::COLONEL_APPLY_EXIST);
        }
        $colonelData = [
            'user_id'         => $params['user_id'],
            'life_account_id' => MarketingService::getPublicLifeAccountId(),
            'phone'           => $params['phone'],
            'contact_name'    => $params['contact_name'],
            'take_place_name' => $params['take_place_name'],
            'take_place_pic'  => $params['take_place_pic'] ?? '',
            'longitude'       => $params['longitude'] ?? 0,
            'latitude'        => $params['latitude'] ?? 0,
            'location'        => $params['location'] ?? '',
            'address'         => $params['address'] ?? '',
            'province'        => $params['province'] ?? '',
            'city'            => $params['city'] ?? '',
            'area'            => $params['area'] ?? '',
        ];
        try {
            if (!empty($colonelData['take_place_name'])) {
                $colonelData['take_place_name'] = "【团长】{$colonelData['take_place_name']}";
            }
            if (!$applyId = ColonelDistributorColonelApply::insertRecord($colonelData)) {
                throw new Exception(MarketingException::COLONEL_APPLY_FAILED);
            }
            return $applyId;
        } catch (Exception $e) {
            throw new MarketingException($e->getMessage());
        }
    }

    /**
     * Notes: 查看用户是否已申请
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/25 11:42 上午
     * @param $userId
     * @return array
     */
    public static function isApply($userId): array
    {
        $applyInfo = ColonelDistributorColonelApply::getRecord(['user_id' => $userId],
            ['colonel_apply_id', 'audit_status']);
        return [
            // -1.未申请  0.未审核  1.审核通过  2.审核未通过
            'apply_status' => isset($applyInfo['audit_status']) ? intval($applyInfo['audit_status']) : -1
        ];
    }


    /**
     * Notes: 团长申请列表-后台管理
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/20 8:15 下午
     * @param array $params
     * @return array
     */
    public static function getManageApplyList(array $params): array
    {
        $params = self::getPageParams($params);
        $result = ColonelDistributorColonelApply::getPages([], ColonelDistributorColonelApply::DEFAULT_COLUMN,
            $params['page'], $params['page_size']);
        if (empty($result['count'])) {
            return $result;
        }
        $userMap = self::getUserMap(array_column($result['result'], 'user_id'));
        $takePlaceMap = self::getColonelTakePlaceMap(array_column($result['result'], 'colonel_apply_id'));
        foreach ($result['result'] as &$applyVal) {
            $applyVal['user_avatar'] = !empty($userMap[$applyVal['user_id']]['user_avatar']) ? $userMap[$applyVal['user_id']]['user_avatar'] : '';
            // take_place_status 是否可以添加自提点  - 已审核通过并且未添加过自提点
            $applyVal['take_place_status'] = 2;
            if ($applyVal['audit_status'] == ColonelDistributorColonelApply::STATUS_PASS) {
                if (empty($takePlaceMap[$applyVal['colonel_apply_id']])) {
                    $applyVal['take_place_status'] = 1;
                }
            }
        }
        unset($applyVal);
        return $result;
    }


    /**
     * Notes: 团长列表-后台管理
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/24 3:04 下午
     * @param array $params
     * @return array
     */
    public static function getManageList(array $params): array
    {
        $params = self::getPageParams($params);
        $result = ColonelDistributorColonel::getPages([], ColonelDistributorColonel::DEFAULT_COLUMN, $params['page'],
            $params['page_size']);
        if (empty($result['count'])) {
            return $result;
        }
        $userIds = array_column($result['result'], 'user_id');
        $userMap = self::getUserMap($userIds);
        $takePlaceMap = self::getTakePlaceMap(array_column($result['result'], 'take_place_id'));
        $incomeMap = PindanActivityInviteOrderService::incomeStatistics(["user_ids" => $userIds]);
        foreach ($result['result'] as &$colonelVal) {
            $userId = $colonelVal['user_id'];
            $takePlaceInfo = !empty($takePlaceMap[$colonelVal['take_place_id']]) ? $takePlaceMap[$colonelVal['take_place_id']] : [];
            $colonelVal['take_place_name'] = $takePlaceInfo['take_place_name'] ?? '';
            $colonelVal['location'] = $takePlaceInfo['location'] ?? '';
            $colonelVal['address']  = $takePlaceInfo['address'] ?? '';
            $colonelVal['user_avatar'] = !empty($userMap[$userId]['user_avatar']) ? $userMap[$userId]['user_avatar'] : '';
            $colonelVal['no_settlement_income'] = !empty($incomeMap[$userId]['no_settlement']) ? $incomeMap[$userId]['no_settlement'] : 0;
            $colonelVal['total_income'] = !empty($incomeMap[$userId]['all_reward']) ? $incomeMap[$userId]['all_reward'] : 0;
        }
        unset($colonelVal);
        return $result;
    }

    /**
     * Notes: 团长申请审核
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/23 1:54 下午
     * @param $applyId
     * @param $auditStatus
     * @return bool
     * @throws MarketingException
     */
    public static function handleManageAudit($applyId, $auditStatus): bool
    {
        // 审核状态参数检测
        if (!in_array($auditStatus,
            [ColonelDistributorColonelApply::STATUS_PASS, ColonelDistributorColonelApply::STATUS_REJECT])) {
            throw new MarketingException(MarketingException::COLONEL_AUDIT_STATUS);
        }
        // 审核状态数据检测
        $applyInfo = ColonelDistributorColonelApply::getRecord(['colonel_apply_id' => $applyId]);
        if (empty($applyInfo) || $applyInfo['audit_status'] == ColonelDistributorColonelApply::STATUS_PASS) {
            throw new MarketingException(MarketingException::COLONEL_AUDIT_STATUS_USE);
        }
        try {
            ColonelDistributorColonelApply::beginTransaction();
            // 修改申请状态
            $updateStatus = ColonelDistributorColonelApply::updateRecord([
                'audit_status' => $auditStatus,
                'update_time'  => date('Y-m-d H:i:s')
            ],
                ['colonel_apply_id' => $applyId, 'audit_status[!]' => ColonelDistributorColonelApply::STATUS_PASS]
            );
            if (empty($updateStatus)) {
                throw new Exception(MarketingException::COLONEL_AUDIT_STATUS_FAILED);
            }
            // 审核成功
            if ($auditStatus == ColonelDistributorColonelApply::STATUS_PASS) {
                if (!self::handleAuditSuccess((array)$applyInfo)) {
                    throw new Exception(MarketingException::COLONEL_ADD_FAILED);
                }
            }
            if (!ColonelDistributorColonelApply::commit()) {
                throw new Exception(MarketingException::COMMIT_ERROR);
            }
            return true;
        } catch (Exception $e) {
            ColonelDistributorColonelApply::rollback();
            throw new MarketingException($e->getMessage());
        }
    }

    /**
     * Notes: 获取自提点信息
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/24 2:40 下午
     * @param $applyId
     * @return array
     */
    public static function getTakePlaceInfo($applyId): array
    {
        $where = [
            'colonel_apply_id' => $applyId
        ];
        $colonelApply = ColonelDistributorColonelApply::getRecord($where);
        return (array)$colonelApply;
    }

    /**
     * Notes: 添加自提点
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/24 2:41 下午
     * @param array $params
     * @return int
     * @throws MarketingException
     */
    public static function handleAddTaskPlace(array $params): int
    {
        // 自提点名称检测
        if (TakePlace::existTakePlaceName($params['take_place_name'])) {
            throw new MarketingException(MarketingException::COLONEL_TAKE_PLACE_EXIST);
        }
        $where = [
            'colonel_apply_id' => $params['colonel_apply_id']
        ];
        // 自提点信息检测
        if (!$colonelApply = ColonelDistributorColonelApply::getRecord($where)) {
            throw new MarketingException(MarketingException::COLONEL_TAKE_PLACE_PARAMS);
        }
        $params['life_account_id'] = $colonelApply['life_account_id'];
        $params['name'] = $params['take_place_name'];
        try {
            ColonelDistributorColonel::beginTransaction();
            // 添加自提点
            if (!$takePlaceId = TakePlaceService::add($params)) {
                throw new Exception(MarketingException::COLONEL_TAKE_PLACE_FAILED);
            }
            // 修改自提点id
            if (!ColonelDistributorColonel::updateRecord(['take_place_id' => $takePlaceId], $where)) {
                throw new Exception(MarketingException::COLONEL_TAKE_PLACE_EDIT_FAILED);
            }
            if (!ColonelDistributorColonel::commit()) {
                throw new Exception(MarketingException::COMMIT_ERROR);
            }
            return (int)$takePlaceId;
        } catch (Exception $e) {
            ColonelDistributorColonel::rollback();
            throw new MarketingException($e->getMessage());
        }
    }

    /**
     * Notes: 团长审核成功
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/24 11:24 上午
     * @param array $applyInfo
     * @return int
     */
    private static function handleAuditSuccess(array $applyInfo): int
    {
        // 入库团长表
        $colonelData = [
            'user_id'          => $applyInfo['user_id'],
            'colonel_apply_id' => $applyInfo['colonel_apply_id'],
            'take_place_id'    => 0,
            'life_account_id'  => $applyInfo['life_account_id'],
            'phone'            => $applyInfo['phone'],
            'contact_name'     => $applyInfo['contact_name'],
            'colonel_source'   => ColonelDistributorColonel::COLONEL_SOURCE_APPLY
        ];
        return ColonelDistributorColonel::insertRecord($colonelData);
    }

    /**
     * Notes: 获取用户信息
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/20 8:16 下午
     * @param array $userIds
     * @return array
     */
    private static function getUserMap(array $userIds): array
    {
        $userWechatList = UserWechatBind::getRecords(['user_id' => $userIds], ['user_id', 'user_nick', 'user_avatar']);
        return array_column((array)$userWechatList, null, 'user_id');
    }

    /**
     * Notes: 获取团长自提点
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/20 8:16 下午
     * @param array $colonelApplyIds
     * @return array
     */
    private static function getColonelTakePlaceMap(array $colonelApplyIds): array
    {
        $colonels = ColonelDistributorColonel::getRecords(['colonel_apply_id' => $colonelApplyIds],
            ['colonel_apply_id', 'take_place_id']);
        return array_column((array)$colonels, 'take_place_id', 'colonel_apply_id');
    }

    /**
     * Notes: 获取默认页码
     * User: pengfei@yidian-inc.com
     * Date: 2021/8/20 8:16 下午
     * @param array $params
     * @return int[]
     */
    private static function getPageParams(array $params = []): array
    {
        $params['page'] = !empty($params['page']) ? $params['page'] : 1;
        $params['page_size'] = !empty($params['page_size']) ? $params['page_size'] : 20;
        return $params;
    }

    /**
     * Notes: 获取自提点信息
     * User: pengfei@yidian-inc.com
     * Date: 2021/9/8 6:16 下午
     * @param array $takePlaceId
     * @return array
     */
    private static function getTakePlaceMap(array $takePlaceId): array
    {
        $takePlaces = TakePlace::getRecords(['take_place_id' => $takePlaceId]);
        return array_column((array)$takePlaces, null, 'take_place_id');
    }

    /**
     * Notes: 获取团长分销活动
     * User: pengfei@yidian-inc.com
     * Date: 2021/9/9 6:06 下午
     * @return array
     */
    public static function getMarketingInfo(): array
    {
        $where = [
            'marketing_type' => Marketing::MARKETING_TYPE_TUANZHANG,
            'ORDER'          => ['marketing_id' => 'DESC'],
        ];
        $where['ORDER'] = ["create_time" => "DESC"];
        $marketing = Marketing::getRecord($where, ['marketing_id', 'capital_pool_id']);
        return (array)$marketing;
    }
}
