<?php

namespace app\admin\controller\member;

use app\admin\service\added\AddedService;
use app\admin\validate\member\RuleAddedValidate;
use app\admin\validate\member\RulePricingValidate;
use app\controller\Curd;
use app\model\Member;
use app\model\MemberQuota;
use app\model\RuleAdded;
use app\model\RuleAddedComponent;
use app\model\RulePricing;
use app\model\SysSerial;
use app\model\SysUser;
use support\Db;
use support\Log;
use support\Redis;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use support\view\Raw;
use Tinywan\Jwt\JwtToken;

class QuotaController extends Curd
{
    public function __construct()
    {
        $this->model = new MemberQuota();
//        $this->validate = true;
//        $this->validateClass = new RuleAddedValidate();
    }

    public function select(Request $request): Response
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $keywords = $request->get('keywords', '');
        $memberId = $request->get('member_id', '');
        $memberIds = [];
        if (!empty($keywords)) {
            $memberIds = Member::leftJoin('member_cert', 'member_cert.join_cert_member_id', '=', 'member.member_id')
                ->where('member.member_mobile', 'like', '%' . $keywords . '%')
                ->orWhere('member_cert.member_cert_name', 'like', '%' . $keywords . '%')
                ->pluck('member.member_id')
                ->toArray();
            if (empty($memberIds)) {
                return json_success('', []);
            }
        }

        if (!empty($memberId)) {
            if (is_array($memberId)) {
                $memberIds = $memberId;
            } else {
                $memberIds = [$memberId];
            }
        }

        foreach ($memberIds as &$id) {
            $id = "'" . $id . "'";
        }

        $rows = MemberQuota::select('join_quota_member_id', 'join_member_rule_added_component_id', Db::raw('MAX(`member_quota_addtimes`) as `new_addtimes`'))
            ->when(!empty($memberIds), function ($query) use ($memberIds) {
                $query->whereIn('join_quota_member_id', $memberIds);
            })
            ->groupBy('join_member_rule_added_component_id', 'join_quota_member_id');

        $bindings = $rows->getBindings();
        $sql = str_replace('?', '%s', $rows->toSql());
        $sql = sprintf($sql, ...$bindings);
        $total = MemberQuota::from(Db::raw("({$sql}) t"))->count();

        $rows = MemberQuota::from(Db::raw("({$sql}) t"))
            ->orderBy('new_addtimes', 'desc')
            // ->orderByDesc('new_addtimes')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach ($rows as &$row) {
            $quota = MemberQuota::with([
                'member' => function ($query) {
                    $query->select('member_id', 'member_mobile');
                },
                'cert' => function ($query) {
                    $query->select('join_cert_member_id', 'member_cert_name');
                },
                'component' => function ($query) {
                    $query->select('rule_added_component_id', 'rule_added_component_name');
                }
            ])->where('join_quota_member_id', $row['join_quota_member_id'])
                ->where('join_member_rule_added_component_id', $row['join_member_rule_added_component_id'])
                ->first()
                ->toArray();
            $quotaUsed = MemberQuota::where('join_quota_member_id', $row['join_quota_member_id'])
                ->where('join_member_rule_added_component_id', $row['join_member_rule_added_component_id'])
                ->where('member_quota_status', 'USED')
                ->count();
            $quota['used'] = $quotaUsed;
            if ($quota['member_quota_nbr'] == '-99.00') {
                $quota['total'] = '不限次';
                $quota['unused'] = '不限次';
            } else {
                $quotaTotal = MemberQuota::where('join_quota_member_id', $row['join_quota_member_id'])
                    ->where('join_member_rule_added_component_id', $row['join_member_rule_added_component_id'])
                    ->count();
                $quota['total'] = $quotaTotal;
                $quota['unused'] = $quotaTotal - $quotaUsed;
            }
            if (!empty($quota['member']) && !empty($quota['member']['member_mobile'])) {
                $quota['member']['member_mobile'] = substr_replace($quota['member']['member_mobile'], '****', 3, 4);
            }


            $addedId = RuleAddedComponent::where('rule_added_component_id', $row['join_member_rule_added_component_id'])->value('join_component_rule_added_id');
            $addedName = RuleAdded::where('rule_added_id', $addedId)->value('rule_added_name');
            $quota['added_name'] = $addedName;

            $row = $quota;
        }

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

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'component' => function ($query) {
                $query->select('rule_added_component_id', 'rule_added_component_name');
            }
        ]);
        $model = $model->groupBy('join_member_rule_added_component_id');
        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;
    }

//    protected function insertInput(Request $request): array
//    {
//        $data = $this->inputFilter($request->post());
//        $data['rule_added_id'] = "RA" . str_pad(SysSerial::getSerial(), 16, '0', STR_PAD_LEFT) . random_string(6, 'up');
//
//        return $data;
//    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
//        if (!empty($data['rule_pricing_goods_json'])) {
//            $data['rule_pricing_goods_json'] = json_encode(explode(',', $data['rule_pricing_goods_json']));
//        } else {
//            $data['rule_pricing_goods_json'] = '[]';
//        }
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    public function writeOffList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $memberId = $request->get('member_id', '');
        $componentId = $request->get('component_id', '');

        $quotas = MemberQuota::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'component' => function ($query) {
                $query->select('rule_added_component_id', 'rule_added_component_name');
            }
        ])->where('join_quota_member_id', $memberId)
            ->where('join_member_rule_added_component_id', $componentId)
            ->where('member_quota_status', 'USED');
        $total = $quotas->count('*');
        $rows = $quotas->orderBy('member_quota_used_json->charge->charge_write_off_time', 'desc')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();

        foreach ($rows as &$quota) {
            $quota['premises'] = '';
            $quota['username'] = '';
            if (!empty($quota['member_quota_used_json'])) {
                $usedJson = json_decode($quota['member_quota_used_json'], true);
                $quota['premises'] = $usedJson['charge']['charge_premises'] ?? '';
                $quota['remark'] = $usedJson['charge']['charge_content'] ?? '';
                $quota['charge_waiter'] = $usedJson['charge']['charge_waiter'] ?? '';
                if (isset($usedJson['charge']['charge_user_id'])) {
                    $user = SysUser::where('user_id', $usedJson['charge']['charge_user_id'])
                        ->select('user_id', 'user_name')
                        ->first();
                    if ($user) {

                        $quota['username'] = $user->user_name;
                    }
                }
            }
            if (!empty($quota['member']) && !empty($quota['member']['member_mobile'])) {
                $quota['member']['member_mobile'] = substr_replace($quota['member']['member_mobile'], '****', 3, 4);
            }
        }

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

    /**
     * @Desc 额度核销
     * @Author Gorden
     * @Date 2024/6/4 8:32
     *
     * @param Request $request
     * @return Response
     */
    public function writeOff(Request $request)
    {
        $params = $request->post();
        $memberId = $params['member_id'] ?? [];
        $componentId = $params['component_id'] ?? [];
        $nbr = $params['nbr'];
        $times = $params['times'] ?? '';
        $code = $params['sms_code'] ?? '';

        if (!$memberId || !$componentId) {
            return json_fail("参数异常");
        }

        $quotas = MemberQuota::where('join_quota_member_id', $memberId[0])
            ->where('join_member_rule_added_component_id', $componentId[0])
            ->where('member_quota_status', 'PENDING')
            ->limit($nbr)
            ->get()
            ->toArray();
        if ($quotas[0]['member_quota_nbr'] != '-99.00' && count($quotas) < intval($nbr)) {
            return json_fail("可核销数量不足");
        }

        $member = Member::find(current($memberId));
        $mobile = $member->member_mobile;
        $key = "SMS:CODE:QUOTA:" . $mobile;
        $redisCode = Redis::get($key);
        if ($redisCode != $code) {
            return json_fail("验证码错误，请重新输入");
        }

        if (!$times) {
            $params['times'] = date('Y-m-d H:i:s');
        } else {
            $params['times'] = date('Y-m-d H:i:s', strtotime($times));
        }

        try {
            // 生成核销数据
            $writeOffData = AddedService::generateWriteOffData($params);
            if ($quotas[0]['member_quota_nbr'] != '-99.00') {
                foreach ($quotas as $quota) {
                    $writeOffData['member_quota_id'] = $quota['member_quota_id'];

                    MemberQuota::where('member_quota_id', $quota['member_quota_id'])->update([
                        'member_quota_status' => 'USED',
                        'member_quota_used_json' => json_encode($writeOffData)
                    ]);
                }
            } else {
                $quota = $quotas[0];
                for ($i = 0; $i < $nbr; $i++) {
                    $quota['member_quota_id'] = 'MQ' . date('ymdHi') . random_string(4, 'up');
                    $quota['member_quota_status'] = 'USED';
                    $quota['member_quota_used_json'] = json_encode($writeOffData);
                    $quota['member_quota_addtimes'] = strtotime($quota['member_quota_addtimes']);
                    $quota['member_quota_nbr'] = 1;
                    MemberQuota::insert($quota);
                }
            }
            // 清除验证码
            Redis::del($key);

            _syslog("核销", "核销成功");

            Log::error("核销成功", $request->all());
            return json_success("核销成功");
        } catch (\Exception $e) {
            _syslog("核销", "核销失败");
            Log::error("核销失败", ['msg' => $e->getMessage(), 'params' => $request->all()]);
            return json_fail("核销失败");
        }
    }

    /**
     * @Desc 额度核销-批量
     * @Author Gorden
     * @Date 2024/6/4 8:32
     *
     * @param Request $request
     * @return Response
     */
    public function writeOffBatch(Request $request)
    {
        $params = $request->post();
        $memberId = $params['member_id'] ?? '';
        $times = $params['times'] ?? '';
        $code = $params['sms_code'] ?? '';

        if (!$memberId || !$code) {
            return json_fail("参数异常");
        }

        // 验证码核验
        $member = Member::find($memberId);
        $mobile = $member->member_mobile;
        $key = "SMS:CODE:WRITE_OFF:" . $mobile;
        $redisCode = Redis::get($key);
        if ($redisCode != $code) {
            return json_fail("验证码错误，请重新输入");
        }

        if (!$times) {
            $params['times'] = date('Y-m-d H:i:s');
        } else {
            $params['times'] = date('Y-m-d H:i:s', strtotime($times));
        }

        Db::beginTransaction();
        try {
            foreach ($params['quotaList'] as $quota) {
                if (!isset($quota['nbr']) || intval($quota['nbr']) == 0) {
                    continue;
                }
                $nbr = intval($quota['nbr']);

                $quotas = MemberQuota::where('join_quota_member_id', $memberId)
                    ->where('join_member_rule_added_component_id', $quota['rule_added_component_id'])
                    ->where('member_quota_status', 'PENDING')
                    ->limit($nbr)
                    ->get()
                    ->toArray();

                if ($quotas[0]['member_quota_nbr'] != '-99.00' && count($quotas) < intval($nbr)) {
                    Db::rollBack();
                    return json_fail("可核销数量不足");
                }
                // 生成核销数据
                $param = [
                    'component_id' => $quota['rule_added_component_id'],
                    'member_id' => $memberId,
                    'write_off_member_id' => $params['write_off_member_id'],
                    'dept_premises_id' => $params['dept_premises_id'] ?? '',
                    'times' => $params['times'],
                    'remark' => $params['remark'] ?? '',
                    'charge_waiter' => $params['charge_waiter'] ?? ''
                ];
                $writeOffData = AddedService::generateWriteOffData($param);
                if ($quotas[0]['member_quota_nbr'] != '-99.00') {
                    foreach ($quotas as $quota) {
                        $writeOffData['member_quota_id'] = $quota['member_quota_id'];

                        MemberQuota::where('member_quota_id', $quota['member_quota_id'])->update([
                            'member_quota_status' => 'USED',
                            'member_quota_used_json' => json_encode($writeOffData)
                        ]);
                    }
                } else {
                    $quota = $quotas[0];
                    for ($i = 0; $i < $nbr; $i++) {
                        $quota['member_quota_id'] = 'MQ' . date('ymdHi') . random_string(4, 'up');
                        $quota['member_quota_status'] = 'USED';
                        $quota['member_quota_used_json'] = json_encode($writeOffData);
                        $quota['member_quota_addtimes'] = strtotime($quota['member_quota_addtimes']);
                        $quota['member_quota_nbr'] = 1;
                        MemberQuota::insert($quota);
                    }
                }
            }

            _syslog("核销", "核销成功");

            //  清除验证码
            Redis::del($key);

            Db::commit();

            return json_success("核销成功");
        } catch (\Exception $e) {
            Db::rollBack();

            dump($e->getMessage());
            _syslog("核销", "核销失败");

            return json_fail("核销失败");
        }
    }

    public static function doWriteOff($params)
    {
        $quotas = MemberQuota::where('join_quota_member_id', $params['member_id'])
            ->where('join_member_rule_added_component_id', $params['component_id'])
            ->where('member_quota_status', 'PENDING')
            ->limit($params['nbr'])
            ->get()
            ->toArray();
        if (count($quotas) < intval($params['nbr'])) {
            throw new BusinessException('可核销数量不足');
        }
        if (!$params['times']) {
            $params['times'] = date('Y-m-d H:i:s');
        } else {
            $params['times'] = date('Y-m-d H:i:s', strtotime($params['times']));
        }

        try {
            // 生成核销数据
            $writeOffData = AddedService::generateWriteOffData($params);
            foreach ($quotas as $quota) {
                $writeOffData['member_quota_id'] = $quota['member_quota_id'];

                MemberQuota::where('member_quota_id', $quota['member_quota_id'])->update([
                    'member_quota_status' => 'USED',
                    'member_quota_used_json' => json_encode($writeOffData)
                ]);
            }

            _syslog("核销", "核销成功");
            return json_success("核销成功");

        } catch (\Exception $e) {
            _syslog("核销", "核销失败");

            throw new BusinessException('核销失败');
            // return json_fail("核销失败");
        }

    }

    /**
     * 会员账户，批量核销选择的权益
     */
    public function chooseList(Request $request)
    {
        $memberId = $request->get('member_id', '');
        $componentIds = $request->get('component_ids', []);

        if (empty($componentIds) || !$memberId) {
            return json_fail("参数异常");
        }

        $components = RuleAddedComponent::whereIn('rule_added_component_id', $componentIds)
            ->select('rule_added_component_name', 'rule_added_component_id')
            ->get();
        foreach ($components as &$component) {
            $component->unused = MemberQuota::where('join_quota_member_id', $memberId)
                ->where('join_member_rule_added_component_id', $component->rule_added_component_id)
                ->where('member_quota_status', 'PENDING')
                ->count();
        }

        $member = Member::where('member_id', $memberId)->select('member_id', 'member_mobile')->first();

        return json_success('', ['member' => $member, 'quotas' => $components]);
    }

}