<?php

/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/12/2
 * Time: 下午3:34
 */

namespace App\Modules\Finance\Services;

use App\Modules\Channel\Services\ChannelService;
use App\Modules\Finance\Models\FinancialPayMerchantBalance;
use App\Modules\Finance\Models\FinancialStat;
use App\Modules\Finance\Models\WithdrawCash;
use App\Modules\Manage\Services\ManageService;
use App\Modules\User\Services\UserService;
use DB;

class WithdrawCashService
{

    /**
     * 自动提现
     * @param unknown_type $request
     */
    public static function auto_add_withdrawCash($distribution_channel_id, $amount, $remark)
    {
        $distribution_channel_name = '';

        if (!is_numeric($amount)) {
            return response()->error("PARAM_ERROR");
        }
        if ($amount < 100) {
            //TODO 渠道14,取消100 金额的判断 大于1一块钱就可以
            if ($distribution_channel_id == 14 || $distribution_channel_id = "14" || $distribution_channel_id = '14') {
                if ($amount < 1) {
                    return response()->error("WITHDRAW_CASH_AMOUNT");
                }
            } else {
                return response()->error("WITHDRAW_CASH_AMOUNT");
            }
        }
        if ($amount >= (20 * 10000)) {
            //TODO 取消单笔提现额度限制
            //return response()->error("WITHDRAW_CASH_AMOUNT_MORE");
        }

        $financialStat = FinancialStatService::getFinancialStatSingle($distribution_channel_id);
        if (empty($financialStat) || $financialStat['enable_withdrawal_amount'] < $amount) {
            //可提现金额不够
            return response()->error("WITHDRAW_CASH_AMOUNT_INSUFFICIEN");
        }

        if (FinancialConfigService::isFrozenDistributionChannel($distribution_channel_id)) {
            //渠道被冻结
            return response()->error("WITHDRAW_CASH_AMOUNT_FROZEN");
        }

        //判断账户是否设置
        if (!CashAccountService::isCashAccountExits($distribution_channel_id)) {
            return response()->error("WITHDRAW_CASH_AMOUNT_ACCOUNT");
        }

        //判断今天是否已经提现
        if (WithdrawCashService::isWithdrawCashChannelToToday($distribution_channel_id)) {
            return response()->error("WITHDRAW_CASH_TODAY_USE");
        }
        $is_company = 0;
        $cashAccount = CashAccountService::getCashAccountSingle($distribution_channel_id);
        if (!empty($cashAccount)) {
            $is_company = $cashAccount['is_company'];
        }
        //一次提现不得超过一个公司主体最大充值金额
        /*$enable_by_company = FinancialPayMerchantBalanceService::getChannelEnableWithdraw($distribution_channel_id,$is_company);
        if(!$enable_by_company){
            return response()->error('WITHDRAW_CASH_AMOUNT_INSUFFICIEN');
        }
        $enable_amount = $enable_by_company->enable_withdrawal_amount;
        if($enable_amount<$amount){
            return ['code'=>101010,'msg'=>'本次最多可提现:'.$enable_amount];
        }*/
        $enable_by_companys = FinancialPayMerchantBalanceService::getChannelEnableWithdrawByCompanyId($distribution_channel_id);
        \Log::info('distribution_channel_id:' . $distribution_channel_id . 'amount:' . $amount);
        \Log::info('distribution_channel_id:' . $distribution_channel_id . 'enable:' . json_encode($enable_by_companys));

        DB::beginTransaction();
        try {
            foreach ($enable_by_companys as $enable_by_company) {
                $with_draw_amount = ($enable_by_company->enable_withdrawal_amount >= $amount) ? $amount : $enable_by_company->enable_withdrawal_amount;
                $pay_company_id = $enable_by_company->pay_merchant_company_id;
                WithdrawCashService::addWithdrawCash($distribution_channel_id, $with_draw_amount, $remark, $pay_company_id);

                $financialStatUp = FinancialStatService::updateFinancialStatByWithdraw($distribution_channel_id, $with_draw_amount);
                FinancialPayMerchantBalanceService::updateBalanceByWithdraw($with_draw_amount, $distribution_channel_id, $pay_company_id);
                $amount = $amount - $with_draw_amount;
                //部分通道公司只能对公打款
                if ($is_company == 0 && in_array($pay_company_id, explode(',', env('ZW_COMPANY_IDS')))) {
                    DB::rollBack();
                    return response()->error('NOT_ALLOWED_PRIVATE_ACCOUNT');
                }
                if ($amount <= 0) {
                    break;
                }
            }
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('withdraw error !' . ($e->getMessage()));
            return response()->error('WITHDRAW_CASHES_FAILED');
        }
        DB::commit();
        //修改可提现总额
        $enable_amount = $financialStatUp['enable_withdrawal_amount'];
        //修改提现中金额
        $withdraw_pending_amount = $financialStatUp['withdraw_pending_amount'];

        return response()->success(compact('enable_amount', 'withdraw_pending_amount'));
    }

    /**
     * 保存提现信息
     * @param $channelId 渠道ID
     * @param $amount 提现金额
     * @param $remark 备注
     * @return mixed
     */
    public static function addWithdrawCash($channelId, $amount, $remark, $pay_company_id)
    {
        $tallage = FinanceService::getWithdrawCashTallage($channelId, $amount);
        $is_company = 0;
        $channelName = ChannelService::getChannelNicknameById($channelId);
        $cashAccount = CashAccountService::getCashAccountSingle($channelId);
        if (!empty($cashAccount)) {
            $is_company = $cashAccount['is_company'];
            $dataWithdrawCash['account_bank'] = $cashAccount->account_bank;
            $dataWithdrawCash['bank_account'] = $cashAccount->card_number;
            $dataWithdrawCash['account_name'] = $cashAccount->account_name;
        }
        $dataWithdrawCash['distribution_channel_id'] = $channelId;
        $dataWithdrawCash['distribution_channel_name'] = $channelName;
        $dataWithdrawCash['amount'] = $amount;
        $dataWithdrawCash['tallage'] = $tallage;
        $dataWithdrawCash['status'] = self::getWithdrawCashStatusStr(0);
        $dataWithdrawCash['remark'] = $remark;
        $dataWithdrawCash['is_company'] = $is_company;
        $dataWithdrawCash['pay_merchant_company_id'] = $pay_company_id;
        $withdrawCash = WithdrawCash::create($dataWithdrawCash);
        return $withdrawCash;
    }

    /**
     * 更新提现信息状态
     * @param $id
     * @param $userId
     * @param $statusIn 状态 查看接口 WithdrawCashService::getWithdrawCashStatusList
     * @param $remark
     * @param string $serialNumber
     * @return mixed
     */
    public static function updateWithdrawCashStatus($id, $userId = '', $statusIn, $remark = '', $serialNumber = '')
    {
        //TODO 对于一个提现记录只有一条打款是没有Bug的。
        //TODO 一个提现记录对应多个支付通道打款,存在逻辑bug
        $withdrawCash = WithdrawCash::where('id', $id)->first();

        if (!empty($withdrawCash) && is_numeric($statusIn)) {

            if (WithdrawCashService::isWithdrawCashStatusPaymentIngStr($withdrawCash['status'])) {
                //当前状态是 打款中 可以修改状态
            } else {
                if (WithdrawCashService::isEditWithdrawCashStatus($id)) {
                    return $withdrawCash;
                }
            }
            $userName = "";
            if ($userId) {
                $manage = ManageService::getById($userId);
                if (!empty($manage)) {
                    $userName = $manage['nickname'];
                }
            }

            $statusStr = WithdrawCashService::getWithdrawCashStatusStr($statusIn);
            if (empty($statusStr)) {
            } else {
                if ($statusStr) {
                    $withdrawCash['status'] = $statusStr;
                }
            }
            if (WithdrawCashService::isWithdrawCashStatusCodeSuccess($statusIn)) {
                //成功提现

                $financialStat = FinancialStat::getByDistributionChannel($withdrawCash['distribution_channel_id']);
                //修改累计提现金额
                $financialStat['accumulative_withdrawal_amount'] = (float)$financialStat['accumulative_withdrawal_amount'] + (float)$withdrawCash['amount'];
                //修改提现中金额
                $financialStat['withdraw_pending_amount'] = (float)$financialStat['withdraw_pending_amount'] - (float)$withdrawCash['amount'];
                $financialStat->save();
                //
                $financePayMerchantBalanceInfo = FinancialPayMerchantBalance::getOne($withdrawCash['distribution_channel_id'], $withdrawCash['pay_merchant_company_id']);
                \Log::info('financePayMerchantBalanceInfo:channel_id:' . $withdrawCash['distribution_channel_id'] . 'pay_merchant_company_id:' . $withdrawCash['pay_merchant_company_id'] . json_encode($financePayMerchantBalanceInfo));
                //修改累计提现金额
                $financePayMerchantBalanceInfo->accumulative_withdrawal_amount = (float)$financePayMerchantBalanceInfo->accumulative_withdrawal_amount + (float)$withdrawCash['amount'];
                //修改提现中金额
                $financePayMerchantBalanceInfo->withdraw_pending_amount = (float)$financePayMerchantBalanceInfo->withdraw_pending_amount - (float)$withdrawCash['amount'];
                $financePayMerchantBalanceInfo->save();
            }
            if ($userId) {
                $withdrawCash['check_user_id'] = $userId;
            }
            if ($userName) {
                $withdrawCash['check_user_name'] = $userName;
            }
            if ($remark) {
                $withdrawCash['remark'] = $remark;
            }
            if ($serialNumber) {
                if (strpos($withdrawCash['serial_number'], $serialNumber) !== false) {
                    //包含
                } else {
                    $serialNumber = $withdrawCash['serial_number'] . "," . $serialNumber;
                }
                $withdrawCash['serial_number'] = $serialNumber;
            }
            $withdrawCash->save();
        }
        return $withdrawCash;
    }

    /**
     * 获取一个提现信息
     * @param $id
     * @return mixed
     */
    public static function getWithdrawCash($id)
    {
        $withdrawCash = WithdrawCash::where('id', $id)->first();
        return $withdrawCash;
    }


    /**
     * 获取提现列表
     * @param string $channel_id 可不传
     * @param string $channel_name 可不传
     * @param string $start_date 可不传
     * @param string $end_date 可不传
     * @param string $statusIn 状态 查看接口 WithdrawCashService::getWithdrawCashStatusList  可不传
     * @param bool $is_all 可不传
     * @return mixed
     */
    public static function getList($channel_id = '', $channel_name = '', $start_date = '', $end_date = '', $statusIn = '', $is_all = false)
    {
        $status = false;
        if (is_numeric($statusIn)) {
            $status = self::getWithdrawCashStatusStrList($statusIn);
        }
        return WithdrawCash::getListByDistributionChannel($channel_id, $channel_name, $start_date, $end_date, $status, $is_all);
    }

    /**
     * 财务对账
     * @param $params[]
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  account_name: 打款人姓名
     *                  search_name: 搜索名称
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     *                  is_frozen:冻结  0:正常状态; -1:冻结状态 可选
     *                  is_company: 0:私人; 1:公司
     * @param string $statusIn 状态 查看接口 WithdrawCashService::getWithdrawCashStatusList  可不传
     * @param $isAll
     * @return mixed
     */
    public static function getFinancialCounting($params = [], $statusIn = '', $isAll = '')
    {
        if (is_numeric($statusIn)) {
            $params['status'] = self::getWithdrawCashStatusStrList($statusIn);
        }
        return WithdrawCash::getFinancialCountingParam($params, $isAll);
    }

    /**
     * 财务审核
     * @param $params[]
     *                  channel_id:渠道ID 可选
     *                  channel_name:渠道名称 可选
     *                  account_name: 打款人姓名
     *                  search_name: 搜索名称 可选
     *                  start_date:开始时间 可选
     *                  end_date:结束时间 可选
     *                  is_frozen:冻结  0:正常状态; -1:冻结状态 可选
     *                  is_company: 0:私人; 1:公司
     * @param string $statusIn 状态 查看接口 WithdrawCashService::getWithdrawCashStatusList  可不传
     * @param $isAll
     * @return mixed
     */
    public static function getFinancialAudit($params = [], $statusIn = '', $isAll = false)
    {
        if (is_numeric($statusIn)) {
            $params['status'] = self::getWithdrawCashStatusStrList($statusIn);
        }
        return WithdrawCash::getFinancialAuditParam($params, $isAll);
    }

    /**
     * 判断当前渠道今天有没有提现
     * @param $channelId
     * @return bool  true:今天已经提现
     */
    public static function isWithdrawCashChannelToToday($channelId)
    {
        $withdrawCash = WithdrawCash::getWithdrawCashLastRecord($channelId);
        if (empty($withdrawCash)) {
            return false;
        }
        $todayStart = strtotime(date('Y-m-d', time()) . ' 00:00:00');
        $createTime = strtotime($withdrawCash['created_at']);
        if ($createTime > $todayStart) {
            return true;
        }
        return false;
    }

    /**
     * 是否能修改提现状态
     * @param $withdrawCashId
     * @return bool true:不能修改
     */
    public static function isEditWithdrawCashStatus($withdrawCashId)
    {
        $withdrawCash = WithdrawCash::where('id', $withdrawCashId)->first();
        if (empty($withdrawCash)) {
            return false;
        }
        if (
            $withdrawCash['status'] == "打款中"
            || $withdrawCash['status'] == "自动打款中"
            || $withdrawCash['status'] == "人工打款中"
            || $withdrawCash['status'] == "打款成功"
            || $withdrawCash['status'] == "自动打款成功"
            || $withdrawCash['status'] == "人工打款成功"
        ) {
            return true;
        }
        return false;
    }

    /**
     * 判断当前提现记录是否 已打款  打款成功 状态
     * @param $withdrawCashId
     * @return bool true:已经打款 打款成功
     */
    public static function isWithdrawCashStatusSuccess($withdrawCashId)
    {
        $withdrawCash = WithdrawCash::where('id', $withdrawCashId)->first();
        if (empty($withdrawCash)) {
            return false;
        }
        if (
            $withdrawCash['status'] == "打款成功"
            || $withdrawCash['status'] == "自动打款成功"
            || $withdrawCash['status'] == "人工打款成功"
        ) {
            return true;
        }
        return false;
    }

    /**
     * 待打款状态
     * @param string $statusStr
     * @return bool
     */
    public static function isWithdrawCashStatusPaymentWaitStr($statusStr = '')
    {
        if (
            $statusStr == "待打款"
            || $statusStr == "自动待打款"
            || $statusStr == "人工待打款"
        ) {
            return true;
        }
        return false;
    }

    /**
     * 打款中状态
     * @param string $statusStr
     * @return bool
     */
    public static function isWithdrawCashStatusPaymentIngStr($statusStr = '')
    {
        if (
            $statusStr == "打款中"
            || $statusStr == "自动打款中"
            || $statusStr == "人工打款中"
        ) {
            return true;
        }
        return false;
    }

    /**
     * 成功打款Code
     * @param string $statusIn
     * @return bool
     */
    public static function isWithdrawCashStatusCodeSuccess($statusIn = '')
    {
        if ($statusIn == 30 || $statusIn == 31 || $statusIn == 32) {
            return true;
        }
        return false;
    }
    /**
     * 成功打款
     * @param string $statusStr
     * @return bool
     */
    public static function isWithdrawCashStatusStrSuccess($statusStr = '')
    {
        if (
            $statusStr == "打款成功"
            || $statusStr == "自动打款成功"
            || $statusStr == "人工打款成功"
        ) {
            return true;
        }
        return false;
    }

    /**
     * 获取成功和失败的状态
     * @return array
     */
    public static function getWithdrawCashStatusStrSuccessAndFailList()
    {
        $status = [];
        $status[] = "打款成功";
        $status[] = "自动打款成功";
        $status[] = "人工打款成功";
        $status[] = "打款失败";
        $status[] = "自动打款失败";
        $status[] = "人工打款失败";
        return $status;
    }

    /**
     * 获取 审核失败 打款成功 打款失败 状态
     * @return array
     */
    public static function getWithdrawCashStatusStrSuccessFailCheckedSuccessList()
    {
        $status = [];
        $status[] = "审核通过";
        $status[] = "审核不通过";
        $status[] = "待打款";
        $status[] = "自动待打款";
        $status[] = "人工待打款";
        $status[] = "打款中";
        $status[] = "自动打款中";
        $status[] = "人工打款中";
        $status[] = "打款成功";
        $status[] = "自动打款成功";
        $status[] = "人工打款成功";
        $status[] = "打款失败";
        $status[] = "自动打款失败";
        $status[] = "人工打款失败";
        return $status;
    }

    public static function getWithdrawCashStatusList($type)
    {
        if ($type == 10) {
            //channel
            $params = [
                ['code' => 0, 'name' => "待审核",        'show' => 1],
                //                ['code' => 1 ,'name' => "审核中",        'show' => 0],
                //                ['code' => 2 ,'name' => "审核通过",        'show' => 0],
                ['code' => 9, 'name' => "审核不通过",       'show' => 1],

                ['code' => 10, 'name' => "待打款",         'show' => 1],
                //                ['code' => 11,'name' => "自动待打款",      'show' => 0],
                //                ['code' => 13,'name' => "人工待打款",      'show' => 0],

                ['code' => 20, 'name' => "打款中",         'show' => 1],
                //                ['code' => 21,'name' => "自动打款中",      'show' => 0],
                //                ['code' => 22,'name' => "人工打款中",      'show' => 0],

                ['code' => 30, 'name' => "打款成功",       'show' => 1],
                //                ['code' => 31,'name' => "自动打款成功",    'show' => 0],
                //                ['code' => 32,'name' => "人工打款成功",    'show' => 0],

                ['code' => 40, 'name' => "打款失败",       'show' => 1],
                //                ['code' => 41,'name' => "自动打款失败",    'show' => 0],
                //                ['code' => 42,'name' => "人工打款失败",    'show' => 0],

                //                ['code' => -1,'name' => "其他错误",       'show' => 0],
            ];
            return $params;
        }
        if ($type == 20) {
            //manage
            $params = [
                ['code' => 0, 'name' => "待审核",        'show' => 1],
                ['code' => 1, 'name' => "审核中",        'show' => 0],
                ['code' => 2, 'name' => "审核通过",        'show' => 0],
                ['code' => 9, 'name' => "审核不通过",       'show' => 1],

                ['code' => 10, 'name' => "待打款",         'show' => 1],
                ['code' => 11, 'name' => "自动待打款",      'show' => 0],
                ['code' => 13, 'name' => "人工待打款",      'show' => 0],

                ['code' => 20, 'name' => "打款中",         'show' => 1],
                ['code' => 21, 'name' => "自动打款中",      'show' => 0],
                ['code' => 22, 'name' => "人工打款中",      'show' => 0],

                ['code' => 30, 'name' => "打款成功",       'show' => 1],
                ['code' => 31, 'name' => "自动打款成功",    'show' => 0],
                ['code' => 32, 'name' => "人工打款成功",    'show' => 0],

                ['code' => 40, 'name' => "打款失败",       'show' => 1],
                ['code' => 41, 'name' => "自动打款失败",    'show' => 0],
                ['code' => 42, 'name' => "人工打款失败",    'show' => 0],

                ['code' => -1, 'name' => "其他错误",       'show' => 0],
            ];
            return $params;
        }
    }

    public static function getWithdrawCashStatusStr($statusIn = '')
    {
        $status = '';
        if (is_numeric($statusIn)) {
            if ($statusIn == 0) {
                $status = "待审核";
            } else if ($statusIn == 1) {
                $status = "审核中";
            } else if ($statusIn == 2) {
                $status = "审核通过";
            } else if ($statusIn == 9) {
                $status = "审核不通过";
            } else if ($statusIn == 10) {
                $status = "待打款";
            } else if ($statusIn == 11) {
                $status = "自动待打款";
            } else if ($statusIn == 12) {
                $status = "人工待打款";
            } else if ($statusIn == 20) {
                $status = "打款中";
            } else if ($statusIn == 21) {
                $status = "自动打款中";
            } else if ($statusIn == 22) {
                $status = "人工打款中";
            } else if ($statusIn == 30) {
                $status = "打款成功";
            } else if ($statusIn == 31) {
                $status = "自动打款成功";
            } else if ($statusIn == 32) {
                $status = "人工打款成功";
            } else if ($statusIn == 40) {
                $status = "打款失败";
            } else if ($statusIn == 41) {
                $status = "自动打款失败";
            } else if ($statusIn == 42) {
                $status = "人工打款失败";
            } else if ($statusIn == -1) {
                $status = "其他错误";
            } else {
                $status = "";
            }
        }
        return $status;
    }

    public static function getWithdrawCashStatusStrList($statusIn = '')
    {
        $status = '';
        if (is_numeric($statusIn)) {
            $status = [];
            if ($statusIn == 0) {
                $status[] = "待审核";
            } else if ($statusIn == 1) {
                $status[] = "审核中";
            } else if ($statusIn == 2) {
                $status[] = "审核通过";
            } else if ($statusIn == 9) {
                $status[] = "审核不通过";
            } else if ($statusIn == 10) {
                $status[] = "待打款";
                $status[] = "自动待打款";
                $status[] = "人工待打款";
            } else if ($statusIn == 11) {
                $status[] = "自动待打款";
            } else if ($statusIn == 12) {
                $status[] = "人工待打款";
            } else if ($statusIn == 20) {
                $status[] = "打款中";
                $status[] = "自动打款中";
                $status[] = "人工打款中";
            } else if ($statusIn == 21) {
                $status[] = "自动打款中";
            } else if ($statusIn == 22) {
                $status[] = "人工打款中";
            } else if ($statusIn == 30) {
                $status[] = "打款成功";
                $status[] = "自动打款成功";
                $status[] = "人工打款成功";
            } else if ($statusIn == 31) {
                $status[] = "自动打款成功";
            } else if ($statusIn == 32) {
                $status[] = "人工打款成功";
            } else if ($statusIn == 40) {
                $status[] = "打款失败";
                $status[] = "自动打款失败";
                $status[] = "人工打款失败";
            } else if ($statusIn == 41) {
                $status[] = "自动打款失败";
            } else if ($statusIn == 42) {
                $status[] = "人工打款失败";
            } else if ($statusIn == -1) {
                $status[] = "其他错误";
            } else {
                $status[] = "未知错误码";
            }
        }
        return $status;
    }

    public static function updateWithdrawCashType($id, $param)
    {
        return WithdrawCash::where('id', $id)->update($param);
    }
}