<?php

namespace app\admin\controller\finance;

use app\admin\service\goods\GoodsSkuService;
use app\admin\service\member\MemberService;
use app\controller\Curd;
use app\model\ClientConfig;
use app\model\Member;
use app\model\MemberAccount;
use app\model\MemberAccountList;
use app\model\Order;
use app\model\OrderSheet;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Webman\Event\Event;

class WithdrawalListController extends Curd
{
    public function __construct()
    {
        $this->model = new MemberAccountList();
    }

    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $order = $request->get('order', 'desc');
        $field = $field ?? 'member_account_list_addtimes';

        if (!empty($where['member_account_list_addtimes'])) {
            $where['member_account_list_addtimes'][0] = strtotime($where['member_account_list_addtimes'][0]);
            $where['member_account_list_addtimes'][1] = strtotime($where['member_account_list_addtimes'][1]);
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
            },
            'memberInfo' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
            },
            'memberCert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            }
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        if (!empty($where['member_account_list_status']) && $where['member_account_list_status'] == 'CANCEL') {
            $model = $model->whereJsonDoesntContain('member_account_list_extend_json->reason', '');
        }
        return $model;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            $item['member_mobile'] = isset($item['member']) ? $item['member']['member_mobile'] : '';
            $item['member_info_nickname'] = isset($item['memberInfo']) && !empty($item['memberInfo']['member_info_nickname']) ? $item['memberInfo']['member_info_nickname'] : '';
            $item['member_cert_name'] = isset($item['memberCert']) && !empty($item['memberCert']['member_cert_name']) ? $item['memberCert']['member_cert_name'] : '';
            $item['member_name'] = MemberService::getMemberName($item['member_mobile'], $item['member_cert_name'], $item['member_info_nickname']);
            $item['member_info_headimg'] = isset($item['memberInfo']) && !empty($item['memberInfo']['member_info_headimg']) ? $item['memberInfo']['member_info_headimg'] : "";
            $item['member_is_owner'] = isset($item['member']) ? $item['member']['member_is_owner'] : '';
            $item['member_is_vip'] = isset($item['member']) ? $item['member']['member_is_vip'] : '';
            $item['member_is_partner'] = isset($item['member']) ? $item['member']['member_is_partner'] : '';
            $item['member_is_referrer'] = isset($item['member']) ? $item['member']['member_is_referrer'] : '';

            unset($item['member'], $item['memberInfo'], $item['memberCert']);
            if (!empty($item['member_account_list_extend_json'])) {
                $memberAccountListExtendJson = json_decode($item['member_account_list_extend_json'], true);
                if (isset($memberAccountListExtendJson['reason'])) {
                    $item['reason'] = $memberAccountListExtendJson['reason'];
                }
            }
            if (!empty($item['member_account_list_json'])) {
                $accountListJson = json_decode($item['member_account_list_json'], true);
                $item['out_rate'] = !empty($accountListJson['out_rate']) ? 0.6 : 0;
                $item['out_rate_amount'] = $accountListJson['out_rate'] ?? 0;
                $item['to_account'] = sprintf('%.2f', $item['member_account_list_amount'] - $item['out_rate_amount']);
            }
        }

        return $items;
    }

    /**
     * @Desc 提现顶部统计
     * @Author Gorden
     * @Date 2024/10/31 10:49
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $memberAccountListAddtimes = $request->get('member_account_list_addtimes');
        $memberId = $request->get('join_member_account_list_member_id');
        $status = $request->get('member_account_list_status');

        if (!empty($memberAccountListAddtimes)) {
            $memberAccountListAddtimes[0] = strtotime($memberAccountListAddtimes[0]);
            $memberAccountListAddtimes[1] = strtotime($memberAccountListAddtimes[1]);
        }

        $withdrawalModel = MemberAccountList::where('member_account_list_attr', 'OUT')
            ->when(!empty($memberAccountListAddtimes), function ($query) use ($memberAccountListAddtimes) {
                $query->whereBetween('member_account_list_addtimes', $memberAccountListAddtimes);
            })->when(!empty($memberId), function ($query) use ($memberId) {
                $query->where('join_member_account_list_member_id', $memberId);
            })->when(!empty($status), function ($query) use ($status) {
                $query->where('member_account_list_status', $status);
            });

        $totalModel = clone $withdrawalModel;
        $total = $totalModel->selectRaw("SUM(member_account_list_amount) as amount,count(member_account_list_id) as total")
            ->first()
            ->toArray();
        $pendingTotalModel = clone $withdrawalModel;
        $pendingTotal = $pendingTotalModel->where('member_account_list_status', 'PENDING')
            ->selectRaw("SUM(member_account_list_amount) as amount,count(member_account_list_id) as total")
            ->first()
            ->toArray();
        $waitingTotalModel = clone $withdrawalModel;
        $waitingTotal = $waitingTotalModel->where('member_account_list_status', 'WAITING')
            ->selectRaw("SUM(member_account_list_amount) as amount,count(member_account_list_id) as total")
            ->first()
            ->toArray();
        $activedTotalModel = clone $withdrawalModel;
        $activedTotal = $activedTotalModel->where('member_account_list_status', 'ACTIVED')
            ->selectRaw("SUM(member_account_list_amount) as amount,count(member_account_list_id) as total")
//            ->selectRaw("SUM(member_account_list_amount) as amount,SUM(JSON_UNQUOTE(JSON_EXTRACT(member_account_list_json,'$.surplus')) * JSON_UNQUOTE(JSON_EXTRACT(member_account_list_json,'$.out_rate')) / 1000) as rate_amount,count(member_account_list_id) as total")
            ->first()
            ->toArray();
        // 实际打款是总额减去手续费
        if (!empty($activedTotal['amount']) && !empty($activedTotal['rate_amount'])) {
            $activedTotal['amount'] = sprintf('%.2f', $activedTotal['amount'] - $activedTotal['rate_amount']);
        }

        $rejectTotalModel = clone $withdrawalModel;
        $rejectTotal = $rejectTotalModel->where('member_account_list_status', 'CANCEL')
            ->whereJsonDoesntContain('member_account_list_extend_json->reason', '')
            ->selectRaw("SUM(member_account_list_amount) as amount,count(member_account_list_id) as total")
            ->first()
            ->toArray();

        return json_success('success', [
            'total' => $total,
            'pendingTotal' => $pendingTotal,
            'waitingTotal' => $waitingTotal,
            'activedTotal' => $activedTotal,
            'rejectTotal' => $rejectTotal
        ]);
    }

    /**
     * @Desc 记录详情
     * @Author Gorden
     * @Date 2024/9/28 17:15
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $id = $request->get('member_account_list_id');
        if (!$id) {
            return json_fail("参数异常");
        }

        $info = MemberAccountList::where('member_account_list_id', $id)->first();
        $infoMember = Member::with([
            'role' => function ($query) {
                $query->select('member_role_id', 'member_role_name');
            }
        ])->where('member_id', $info->join_member_account_list_member_id)
            ->first();
        $info->member_role_name = !empty($infoMember->role) ? $infoMember->role->member_role_name : '';
        // 获取银行卡信息
        if (!empty($info->member_account_list_json)) {
            $accountListJson = json_decode($info->member_account_list_json, true);
            $info->out_rate = !empty($accountListJson['out_rate']) ? 0.6 : 0;
            $info->out_rate_amount = $accountListJson['out_rate'] ?? 0;
            $info->to_account = sprintf('%.2f', $info->member_account_list_amount - $info->out_rate_amount);
            $info->banks = [
                [
                    'bank_name' => $accountListJson['bank_name'] ?? '',
                    'username' => $accountListJson['bank_acount'] ?? '',
                    'cardno' => $accountListJson['bank_cardno'] ?? ''
                ]
            ];
        }
        if (!empty($info->member_account_list_extend_json)) {
            $memberAccountListExtendJson = json_decode($info->member_account_list_extend_json, true);
            if (isset($memberAccountListExtendJson['reason'])) {
                $info->reason = $memberAccountListExtendJson['reason'];
            }
            if (isset($memberAccountListExtendJson['resulttime'])) {
                $info->resulttime = $memberAccountListExtendJson['resulttime'];
            }
        }

//        $info->banks = ClientConfig::where('join_client_config_member_id',$info->join_member_account_list_member_id)->where('client_config_key','client-bank')->get()->toArray();

        return json_success('success', $info);
    }

    public function changeStatus(Request $request)
    {
        $memberAccountListId = $request->post('member_account_list_id');
        $status = $request->post('status');
        $password = $request->post('pay_pwd');
        if ($status == 'ACTIVED' && $password != '888666') {
            return json_fail('密码错误');
        }

        Db::beginTransaction();
        try {
            $withdraw = MemberAccountList::where('member_account_list_id', $memberAccountListId)->first();
            $withdraw->member_account_list_status = $status;
            $memberAccountListJson = [];
            if (!empty($withdraw->member_account_list_json)) {
                $memberAccountListJson = json_decode($withdraw->member_account_list_json, true);
            }
            $memberAccountListExtendJson = [];
            if (!empty($withdraw->member_account_list_extend_json)) {
                $memberAccountListExtendJson = json_decode($withdraw->member_account_list_extend_json, true);
            }
            if ($status == 'ACTIVED') {
                $memberAccountListJson['resulttime'] = date('Y-m-d H:i:s');
                $memberAccountListExtendJson['resulttime'] = date('Y-m-d H:i:s');
                // 扣账户余额
                $account = MemberAccount::where('join_account_member_id', $withdraw->join_member_account_list_member_id)
                    ->where('member_account_classify', 'CASH')
                    ->where('member_account_status', 'ACTIVED')
                    ->first();
                if (empty($account)) {
                    throw new BusinessException("账户异常");
                }
                if ($account->member_account_surplus < $withdraw->member_account_list_amount) {
                    throw new BusinessException("账户余额不足");
                }
                $account->member_account_surplus = $account->member_account_surplus - $withdraw->member_account_list_amount;
                $account->member_account_expend = $account->member_account_expend + $withdraw->member_account_list_amount;
                $account->save();
            } else if ($status == 'CANCEL') {
                $memberAccountListExtendJson['resulttime'] = date('Y-m-d H:i:s');
                $memberAccountListExtendJson['reason'] = $request->post('reason', '');
            }
            $withdraw->member_account_list_extend_json = json_encode($memberAccountListExtendJson);
            $withdraw->member_account_list_outed = 'Y';
            $withdraw->save();

            _syslog('提现', '修改状态成功');

            Db::commit();

            if ($status == 'ACTIVED') {
                // 入收支记录
                $params['account_list_id'] = $memberAccountListId;
                $params['type'] = 'withdraw';
                Event::dispatch('statistics.inout.out', $params);
            }

            return json_success('success');
        } catch (BusinessException $e) {

            Db::rollBack();
            return json_fail($e->getMessage());
        } catch (\Exception $e) {

            Db::rollBack();
            return json_fail("修改状态失败");
        }
    }

    /**
     * @Desc 提现导出
     * @Author Gorden
     * @Date 2024/11/1 17:12
     *
     * @param Request $request
     * @return Response
     */
    public function export(Request $request)
    {
        $memberAccountListAddtimes = $request->get('member_account_list_addtimes');
        $memberId = $request->get('join_member_account_list_member_id');
        $memberAccountListStatus = $request->get('member_account_list_status');
        $memberAccountListIds = $request->get('member_account_list_ids');
        $withdrawal = MemberAccountList::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'memberCert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            }
        ])->where('member_account_list_attr', 'OUT');
        if (!empty($memberId)) {
            $withdrawal = $withdrawal->where('join_member_account_list_member_id', $memberId);
        }
        if (!empty($memberAccountListStatus)) {
            $withdrawal = $withdrawal->where('member_account_list_status', $memberAccountListStatus);
        }
        if (!empty($memberAccountListAddtimes)) {
            $memberAccountListAddtimes[0] = strtotime($memberAccountListAddtimes[0]);
            $memberAccountListAddtimes[1] = strtotime($memberAccountListAddtimes[1]);
            $withdrawal = $withdrawal->whereBetween('member_account_list_addtimes', $memberAccountListAddtimes);
        }
        if (!empty($memberAccountListIds)) {
            $withdrawal = $withdrawal->whereIn('member_account_list_id', $memberAccountListIds);
        }
        $withdrawal = $withdrawal->orderBy("member_account_list_addtimes", 'DESC')->get()->toArray();

        $data = [];
        foreach ($withdrawal as $item) {
            $mobile = !empty($item['member']) ? $item['member']['member_mobile'] : '';
            $certName = !empty($item['member_cert']) ? $item['member_cert']['member_cert_name'] : '';
            $rateAmount = 0;
            if (!empty($item['member_account_list_json'])) {
                $memberAccountListJson = json_decode($item['member_account_list_json'], true);
                if (isset($memberAccountListJson['out_rate'])) {
                    $item['out_rate'] = ($memberAccountListJson['out_rate'] / 10);
                    $rateAmount = round($item['member_account_list_amount'] * $item['out_rate'] / 100, 2);
                    $item['out_rate'] = $item['out_rate'] . '%';
                }
            }
            $item['to_account'] = sprintf('%.2f', $item['member_account_list_amount'] - $rateAmount);
            if (!empty($item['member_account_list_extend_json']) && $item['member_account_list_status'] == 'CANCEL') {
                $extendJson = json_decode($item['member_account_list_extend_json'], true);
                if (!empty($extendJson['reason'])) {
                    $item['member_account_list_status'] = 'REJECT';
                }
            }

            $data[] = [
                'member_account_list_addtimes' => $item['member_account_list_addtimes'],
                'member_name' => MemberService::getMemberCertName($mobile, $certName, ''),
                'member_account_list_category' => $item['member_account_list_category'],
                'member_account_list_amount' => $item['member_account_list_amount'],
                'out_rate' => $item['out_rate'] ?? '0',
                'to_account' => $item['to_account'],
                'member_account_list_status' => self::$status[$item['member_account_list_status']]
            ];
        }

        return json_success('success', $data);
    }

    public static $status = [
        'PENDING' => '待处理',
        'WAITING' => '处理中',
        'ACTIVED' => '已完成',
        'REJECT' => '已驳回',
        'CANCEL' => '已取消'
    ];
}