<?php

namespace app\admin\controller\finance;

use app\admin\service\goods\GoodsSkuService;
use app\admin\service\member\MemberService;
use app\admin\service\order\PayDetailService;
use app\controller\Curd;
use app\model\Member;
use app\model\MemberAccountList;
use app\model\Order;
use app\model\OrderSheet;
use app\model\PayDetail;
use support\Request;
use support\Response;

class CommissionListController 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';
        $where['member_account_list_classify'] = ['in', ['PARTNER', 'REFERRER', 'FRANCHISEE']];
        $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);
        }
        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_json'])) {
                $memberAccountListJson = json_decode($item['member_account_list_json'], true);
                $member = Member::with([
                    'cert' => function ($query) {
                        $query->select('join_cert_member_id', 'member_cert_name');
                    }
                ])->where('member_id', $memberAccountListJson['master_member_id'])
                    ->first();
                $mobile = !empty($member->member_mobile) ? $member->member_mobile : '';
                $certName = !empty($member->cert) ? $member->cert->member_cert_name : '';
                $item['master_name'] = MemberService::getMemberCertName($mobile, $certName, '');
            }

        }

        return $items;
    }

    /**
     * @Desc 佣金管理顶部统计
     * @Author Gorden
     * @Date 2024/10/31 15:33
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $todayTimeUnixStart = strtotime(date('Y-m-d'));
        $todayTimeUnixEnd = strtotime(date('Y-m-d 23:59:59'));
        $yesterdayStart = strtotime(date('Y-m-d', strtotime("-1 days")));
        $yesterdayEnd = strtotime(date('Y-m-d 23:59:59', strtotime("-1 days")));
        $monthStart = strtotime(date('Y-m-01'));
        $monthEnd = strtotime(date('Y-m-t 23:59:59'));

        $commissionModel = MemberAccountList::where('member_account_list_attr', 'IN')
            ->where('member_account_list_status', 'ACTIVED')
            ->selectRaw("SUM(member_account_list_amount) as amount, COUNT(member_account_list_id) as total");

        $totalModel = clone $commissionModel;
        $total = $totalModel->first()->toArray();

        $todayTotalModel = clone $commissionModel;
        $todayTotal = $todayTotalModel->whereBetween('member_account_list_addtimes', [$todayTimeUnixStart, $todayTimeUnixEnd])
            ->first()
            ->toArray();
        $yesterdayTotalModel = clone $commissionModel;
        $yesterdayTotal = $yesterdayTotalModel->whereBetween('member_account_list_addtimes', [$yesterdayStart, $yesterdayEnd])
            ->first()
            ->toArray();
        $monthTotalModel = clone $commissionModel;
        $monthTotal = $monthTotalModel->whereBetween('member_account_list_addtimes', [$monthStart, $monthEnd])
            ->first()
            ->toArray();

        return json_success('success', [
            'total' => $total,
            'todayTotal' => $todayTotal,
            'yesterdayTotal' => $yesterdayTotal,
            'monthTotal' => $monthTotal
        ]);
    }

    /**
     * @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);
            // 下单人
            if (isset($accountListJson['master_member_id'])) {
                $member = Member::with([
                    'info' => function ($query) {
                        $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
                    },
                    'cert' => function ($query) {
                        $query->select('join_cert_member_id', 'member_cert_name');
                    },
                    'role' => function ($query) {
                        $query->select('member_role_id', 'member_role_name');
                    }
                ])->where('member_id', $accountListJson['master_member_id'])
                    ->first();
                $info->master_nickname = isset($member->info) && !empty($member->info->member_info_nickname) ? $member->info->member_info_nickname : MemberService::getMemberNickname($member->member_mobile ?? '');
                $info->master_headimg = MemberService::getAvatarUrl(!empty($member->info) ? $member->info->member_info_headimg : '');
                $info->master_certname = isset($member->cert) && !empty($member->cert->member_cert_name) ? $member->cert->member_cert_name : '';
                $info->master_mobile = isset($member) && !empty($member->member_mobile) ? $member->member_mobile : '';
                $info->master_member_name = MemberService::getMemberName($info->master_mobile, $info->master_certname, $info->master_nickname);
                $info->master_role_name = !empty($member->role) ? $member->role->member_role_name : '';
                $info->join_member_role_id = $member->join_member_role_id ?? '';
                $info->member_is_owner = $member->member_is_owner ?? '';
                $info->member_is_vip = $member->member_is_vip ?? '';
                $info->member_is_partner = $member->member_is_partner ?? '';
                $info->member_is_referrer = $member->member_is_referrer ?? '';
                $info->member_is_franchisee = $member->member_is_franchisee ?? '';
            }
            // 订单
            if (isset($accountListJson['order_id'])) {
                $info->order = Order::where('order_id', $accountListJson['order_id'])
                    ->select('order_id', 'order_groupby', 'order_amount_total', 'order_amount_pay', 'order_addtimes')
                    ->first();
                $sheets = OrderSheet::with([
                    'goods' => function ($query) {
                        $query->select('goods_id', 'goods_name', 'goods_sales_price', 'goods_cover');
                    },
                    'sku' => function ($query) {
                        $query->select('goods_sku_id', 'goods_sku_specs_json');
                    }
                ])->where('join_sheet_order_id', $accountListJson['order_id'])
                    ->select('join_sheet_order_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id', 'order_sheet_num', 'order_sheet_price', 'order_sheet_amount', 'order_sheet_addtimes')
                    ->get()
                    ->toArray();
                foreach ($sheets as &$sheet) {
                    if (!empty($sheet['goods']) && !empty($sheet['goods']['goods_cover'])) {
                        $sheet['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $sheet['goods']['goods_cover'];
                    }
                    if (!empty($sheet['sku'])) {
                        $sheet['sku']['sku_title'] = GoodsSkuService::getSkuTitle($sheet['sku']['goods_sku_specs_json']);
                    }
                }
                $info->sheet = $sheets;

                // 支付记录
                $payDetails = PayDetail::whereJsonContains('join_pay_object_json->order_id', $accountListJson['order_id'])
                    ->select('pay_amount', 'pay_status', 'pay_paytimes', 'pay_prepayid')
                    ->where('pay_status', 'SUCCESS')
                    ->orderBy('pay_addtimes', 'DESC')
                    ->get()
                    ->toArray();
                foreach ($payDetails as &$detail) {
                    $detail['pay_category'] = PayDetailService::getPayWayByPrepayId($detail['pay_prepayid']);
                }

                $info->payDetails = $payDetails;
            }
        }

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