<?php

namespace app\admin\controller\member;

use app\admin\service\member\MemberService;
use app\controller\Curd;
use app\model\Appointment;
use app\model\Member;
use app\model\MemberBenefit;
use app\model\MemberQuota;
use app\model\RuleAddedComponent;
use app\model\SysUser;
use support\Db;
use support\Request;
use support\Response;

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

    public function list(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 50);
        $keywords = $request->get('keywords', '');
        $userId = $request->get('user_id', '');
        $premises = $request->get('premises', '');
        $date = $request->get('date', []);
        $memberId = $request->get('member_id', '');

        $appointmentList = Db::table('appointment')
            ->leftJoin('member', 'member.member_id', '=', 'appointment.join_appointment_member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'appointment.join_appointment_member_id')
            ->select('appointment.appointment_id as quota_id', 'appointment.join_appointment_member_id as member_id', 'appointment.appointment_classify as classify', 'appointment.appointment_done_json as used_json', 'appointment.appointment_done_datetime as used_time', 'appointment.join_appointment_member_benefit_id as benefit_id',
                'member.member_mobile', 'member_cert.member_cert_name', 'appointment_extend_json as extend_json'
            )
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('member.member_mobile', 'like', '%' . $keywords . '%');
            })->when(!empty($date), function ($query) use ($date) {
                $date[0] = date('Y-m-d', strtotime($date[0])) . ' 00:00:00';
                $date[1] = date('Y-m-d', strtotime($date[1])) . ' 23:59:59';
                $query->whereBetween('appointment.appointment_done_datetime', $date);
            })->when($userId != '', function ($query) use ($userId) {
                $query->whereJsonContains('appointment.appointment_done_json->charge->charge_user_id', $userId);
            })->when($premises != '', function ($query) use ($premises) {
                $query->whereJsonContains('appointment.appointment_done_json->charge->charge_premises', $premises);
            })->when(!empty($memberId), function ($query) use ($memberId) {
                $query->where('join_appointment_member_id', $memberId);
            })
            ->where('appointment_status', 'DONE');
        $quotaList = Db::table('member_quota')
            ->leftJoin('member', 'member.member_id', '=', 'member_quota.join_quota_member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'member_quota.join_quota_member_id')
            ->select('member_quota.member_quota_id as quota_id', 'member_quota.join_quota_member_id as member_id', 'member_quota.member_quota_category as classify', 'member_quota.member_quota_used_json as used_json', "member_quota.member_quota_extend_json->writeOffTime as used_time", "member_quota.join_member_rule_added_component_id as benefit_id",
                'member.member_mobile', 'member_cert.member_cert_name', 'member_quota_extend_json as extend_json')
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('member.member_mobile', 'like', '%' . $keywords . '%');
            })->when(!empty($date), function ($query) use ($date) {
                $date[0] = date('Y-m-d', strtotime($date[0])) . ' 00:00:00';
                $date[1] = date('Y-m-d', strtotime($date[1])) . ' 23:59:59';
                $query->whereBetween('member_quota.member_quota_extend_json->writeOffTime', $date);
            })
            ->when($userId != '', function ($query) use ($userId) {
                $query->whereJsonContains('member_quota.member_quota_used_json->charge->charge_user_id', $userId);
            })
            ->when($premises != '', function ($query) use ($premises) {
                $query->whereJsonContains('member_quota.member_quota_used_json->charge->charge_premises', $premises);
            })
            ->where('member_quota_status', 'USED')
            ->union($appointmentList);
        $total = $quotaList->count('*');

        $quotaList = $quotaList->orderBy('used_time', 'DESC')
            ->forPage($page, $pageSize)
            ->get();

        $rows = [];
        foreach ($quotaList as $item) {
            $username = '';
            $premises = '';
            $benefitName = '';
            if (!empty($item->used_json)) {
                $usedJson = json_decode($item->used_json, true);
                if (isset($usedJson['charge']) && isset($usedJson['charge']['charge_user_id'])) {
                    $username = SysUser::where('user_id', $usedJson['charge']['charge_user_id'])->value('user_name');
                }
                if (isset($usedJson['charge']) && isset($usedJson['charge']['charge_premises'])) {
                    $premises = $usedJson['charge']['charge_premises'];
                }
                if (substr($item->quota_id, 0, 2) == 'AP') {
                    $benefitName = MemberBenefit::where('member_benefit_id', $item->benefit_id)->value('member_benefit_name');
                } elseif (substr($item->quota_id, 0, 2) == 'MQ') {
                    $benefitName = RuleAddedComponent::where('rule_added_component_id', $item->benefit_id)->value('rule_added_component_name');
                }
            }
            $remark = [];
            if (!empty($item->extend_json)) {
                $extendJson = json_decode($item->extend_json, true);
                if (isset($extendJson['remark'])) {
                    $remark = $extendJson['remark'];
                }
            }
            $classify = "SERVICE";
            if (substr($item->quota_id, 0, 2) == "MQ") {
                $classify = "QUOTA";
            } elseif (!empty($item->classify) && $item->classify == 'PACKAGE') {
                $classify = "PACKAGE";
            }
            $rows[] = [
                'quota_id' => $item->quota_id,
                'username' => $username,
                'premises' => $premises,
                'benefit_name' => $benefitName,
                'used_time' => $item->used_time,
                'member_name' => $item->member_cert_name ? $item->member_cert_name : '',
                'member_mobile' => $item->member_mobile ? $item->member_mobile : '',
                'classify' => $classify,
                'nbr' => 1,
                'remark' => $remark
            ];

        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    /**
     * @Desc 核销详情
     * @Author Gorden
     * @Date 2024/10/10 14:00
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $quotaId = $request->get('quota_id');
        if (!$quotaId) {
            return json_fail("参数异常");
        }

        if (substr($quotaId, 0, 2) == 'AP') {
            $quota = Appointment::where('appointment_id', $quotaId)
                ->select('appointment_id', 'join_appointment_member_id as member_id')
                ->first();
        } elseif (substr($quotaId, 0, 2) == 'MQ') {
            $quota = MemberQuota::where('member_quota_id', $quotaId)
                ->select('member_quota_id', 'join_quota_member_id as member_id')
                ->first();
        } else {
            return json_fail("参数异常");
        }

        $member = Member::with([
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'info' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname', 'member_info_headimg');
            }
        ])->where('member_id', $quota['member_id'])
            ->select('member_id', 'member_mobile', 'join_member_role_id', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer', 'member_is_franchisee')
            ->first();
        if (!$member){
            return json_fail('数据异常');
        }
        $member = $member->toArray();
        $certName = $member['cert']['member_cert_name'] ?? '';
        $nickname = $member['info']['member_info_nickname'] ?? MemberService::getMemberNickname($member['member_mobile'] ?? '');
        $mobile = $member['member_mobile'] ?? '';
        $member['member_name'] = MemberService::getMemberCertName($mobile, $certName, $nickname);
        $member['info']['member_info_headimg'] = MemberService::getAvatarUrl($member['info']['member_info_headimg'] ?? '');
        $member['level'] = MemberService::getRoleName($member['join_member_role_id']);

        $data = [
            'member'=>$member
        ];

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

    /**
     * @Desc 核销备注
     * @Author Gorden
     * @Date 2024/9/4 17:05
     *
     * @param Request $request
     * @return \support\Response
     */
    public function remark(Request $request)
    {
        $quotaId = $request->post('quota_id', '');
        if (!$quotaId) {
            return json_fail('参数异常');
        }
        $extendJson = [];
        if (substr($quotaId, 0, 2) == 'AP') {
            $appointment = Appointment::where('appointment_id', $quotaId)->first();
            if (!empty($appointment->appointment_extend_json)) {
                $extendJson = json_decode($appointment->appointment_extend_json, true);
            }
        } elseif (substr($quotaId, 0, 2) == 'MQ') {
            $quota = MemberQuota::where('member_quota_id', $quotaId)->first();
            if (!empty($quota->member_quota_extend_json)) {
                $extendJson = json_decode($quota->member_quota_extend_json, true);
            }
        }
        if (empty($appointment) && empty($quota)) {
            return json_fail("数据异常");
        }
        try {
            $extendJson['remark'] = [
                'premises_id' => $request->post('premises_id', ''),
                'premises_name' => $request->post('premises_name', ''),
                'business' => $request->post('business', ''),
                'service' => $request->post('service', '')
            ];
            if (!empty($appointment)) {
                $appointment->appointment_extend_json = json_encode($extendJson, JSON_UNESCAPED_UNICODE);
                $appointment->save();
            } elseif (!empty($quota)) {
                $quota->member_quota_extend_json = json_encode($extendJson, JSON_UNESCAPED_UNICODE);
                $quota->save();
            }

            return json_success('success');
        } catch (\Exception $e) {
            return json_fail('备注保存失败');
        }
    }
}