<?php

namespace app\admin\controller\member;

use app\admin\service\order\OrderService;
use app\controller\Curd;
use app\model\Appointment;
use app\model\Member;
use app\model\MemberBenefit;
use app\model\Order;
use app\model\SysDept;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Redis;
use support\Request;
use Webman\Event\Event;

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

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with('member', 'goods');
        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 my(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $id = $request->get('member_id','');
        $benefit = MemberBenefit::with([
            'package' => function ($query) {
                $query->select('goods_id', 'goods_name');
            },
            'goods' => function ($query) {
                $query->select('goods_id', 'goods_name');
            },
            'order'
        ])
            ->where('join_benefit_member_id', $id)
            ->where('join_benefit_package_id', '<>', '');
        $total = $benefit->count('*');
        $rows = $benefit->orderBy('member_benefit_addtimes','DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach ($rows as &$item){
            $item['member_benefit_limit_count'] = intval($item['member_benefit_limit_count']);
            $item['member_benefit_used_count'] = intval($item['member_benefit_used_count']);
        }

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

    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $data['member_benefit_valid_datetimes'] = date('Y-m-d H:i:s', strtotime($data['member_benefit_valid_datetimes']));

        unset($data[$primary_key]);
        return [$id, $data];
    }

    public function writeOff(Request $request)
    {
        $memberId = $request->post('member_id', '');
        $benefitId = $request->post('benefit_id', '');
        $nbr = $request->post('nbr');
        $times = $request->post('times', '');
        $code = $request->post('sms_code', '');

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

        $benefit = MemberBenefit::where('member_benefit_id', $benefitId)
            ->where('join_benefit_member_id', $memberId)
            ->first();
        if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $nbr) {
            return json_fail('可核销数量不足');
        }

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

        Db::beginTransaction();
        try {
            // 减额度
            $benefitUsed = [];
            $appointmentIds = [];
            $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $nbr;
            if($benefit->member_benefit_used_count >= $benefit->member_benefit_limit_count){
                $benefit->member_benefit_status = 'DONE';
                if(!empty($benefit->join_benefit_order_id)){
                    $benefitUsed[$benefit->join_benefit_order_id][] = $benefitId;
//                    Order::where('order_id',$benefit->join_benefit_order_id)->update(['order_is_complete'=>'Y','order_status_system'=>'DONE']);
                }
            }
            $benefit->save();
            // 记录核销
            $params = [
                'dept_premises_id' => $request->post('dept_premises_id',''),
                'order_remark'=>$request->post('remark',''),
                'write_off_member_id' => $request->post('write_off_member_id',''),
                'join_order_member_id' => $memberId,
                'charge_waiter' => $request->post('charge_waiter'),
            ];
            $writeOffData = OrderService::generateWriteOffData($params);

            $appointments = Appointment::where('join_appointment_member_benefit_id', $benefitId)
                ->whereIn('appointment_status', ['INIT','WAITING','PENDING','DOING'])
                ->limit($nbr)
                ->get();
            foreach ($appointments as $appointment) {
                Appointment::where('appointment_id', $appointment->appointment_id)->update([
                    'appointment_status' => 'DONE',
                    'appointment_datetime' => $times,
                    'appointment_apply_datetime' => $times,
                    'appointment_doing_datetime' => $times,
                    'appointment_done_datetime' => $times,
                    'appointment_done_json' => json_encode($writeOffData)
                ]);
            }
            // 订单服务是否用完了
            foreach ($benefitUsed as $key => $item) {
                $orderUsedComplete = 'Y';
                $orderBenefits = MemberBenefit::where('join_benefit_order_id', $key)->get()->toArray();
                foreach ($orderBenefits as $orderBenefit) {
                    if ($orderBenefit['member_benefit_used_count'] >= $orderBenefit['member_benefit_limit_count']) {
                        continue;
                    }
                    if (!in_array($orderBenefit['member_benefit_id'], $item)) {
                        $orderUsedComplete = 'N';
                    }
                }
                if ($orderUsedComplete == 'Y') {
                    Order::where('order_id', $key)->update(['order_is_complete' => 'Y', 'order_status_system' => 'DONE']);
                }
            }

            // 核销服务回写process
            $dept = [];
            if (!empty($request->post('dept_premises_id'))) {
                $dept = SysDept::where('dept_id', $request->post('dept_premises_id'))
                    ->orWhere('dept_name', $request->post('dept_premises_id'))
                    ->select('dept_id', 'dept_name', 'dept_status', 'dept_category', 'dept_super_id', 'dept_super_path')
                    ->first();
            }
            $params['charge_amount'] = $nbr;
            $params['goods_id'] = !empty($benefit->join_benefit_goods_id) ? $benefit->join_benefit_goods_id : (!empty($benefit->join_benefit_package_id) ? $benefit->join_benefit_package_id : '');
            $params['goods_sku_id'] = $benefit->join_benefit_goods_sku_id;
            $params['order_id'] = $benefit->join_benefit_order_id;
            $params['appointment_ids'] = $appointmentIds;
            $params['dept'] = $dept;
            $params['write_off_data'] = OrderService::generateWriteOffDataByOrderProcess($params);
            // 触发事件
            Event::dispatch('order.write_off', $params);

            Redis::del($key);

            Db::commit();

            _syslog("核销","核销成功");
            return json_success('核销成功');
        } catch (\Exception $e) {
            dump($e->getMessage().$e->getLine());
            Db::rollBack();
            _syslog("核销","核销失败");
            return json_fail('核销失败');
        }
    }

    public static function doWriteOff($paramsData,$appointmentNofee)
    {
        $benefit = MemberBenefit::where('member_benefit_id', $paramsData['benefit_id'])
            ->where('join_benefit_member_id', $paramsData['member_id'])
            ->first();
        if ($benefit->member_benefit_limit_count - $benefit->member_benefit_used_count < $paramsData['nbr']) {
            throw new BusinessException('可核销数量不足');
            // return json_fail('可核销数量不足');
        }

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

        Db::beginTransaction();
        try {
            // 减额度
            $benefit->member_benefit_used_count = $benefit->member_benefit_used_count + $paramsData['nbr'];
            if($benefit->member_benefit_used_count == $benefit->member_benefit_limit_count){
                $benefit->member_benefit_status = 'DONE';
                if(!empty($benefit->join_benefit_order_id)){
                    Order::where('order_id',$benefit->join_benefit_order_id)->update(['order_is_complete'=>'Y','order_status_system'=>'DONE']);
                }
            }
            $benefit->save();
            // 记录核销
            $params = [
                'dept_premises_id' => $paramsData['dept_premises_id'],
                'order_remark'=>$paramsData['remark'],
                'write_off_member_id' => $paramsData['write_off_member_id'],
                'join_order_member_id' => $paramsData['member_id']
            ];
            $writeOffData = OrderService::generateWriteOffData($params);

            $appointments = Appointment::where('join_appointment_member_benefit_id', $paramsData['benefit_id'])
                ->whereIn('appointment_status', ['INIT','WAITING','PENDING','DOING'])
                ->limit($paramsData['nbr'])
                ->get();
            foreach ($appointments as $appointment) {
                Appointment::where('appointment_id', $appointment->appointment_id)->update([
                    'appointment_status' => 'DONE',
                    'appointment_datetime' => $times,
                    'appointment_apply_datetime' => $times,
                    'appointment_doing_datetime' => $times,
                    'appointment_done_datetime' => $times,
                    'appointment_done_json' => json_encode($writeOffData),
                    'appointment_apply_json'=>$appointmentNofee->appointment_apply_json,
                    'appointment_process_json'=>$appointmentNofee->appointment_process_json,
                    'settlement_mode'=>$appointmentNofee->settlement_mode
                ]);
            }

            Db::commit();

            _syslog("核销","核销成功");
            return json_success('核销成功');
        } catch (\Exception $e) {
            dump($e->getFile().'---'.$e->getLine());
            Db::rollBack();
            _syslog("核销","核销失败");

            throw new BusinessException('核销失败');
        }
    }


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

        $quotas = Appointment::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
//            'goods' => function ($query) {
//                $query->select('goods_id', 'goods_name');
//            },
            'benefit' => function ($query) {
                $query->select('member_benefit_id', 'member_benefit_name');
            }
        ])->where('join_appointment_member_id', $memberId)
            ->where('join_appointment_member_benefit_id', $benefitId)
            ->where('appointment_status', 'DONE');
            $total = $quotas->count('*');
        
            $rows = $quotas->orderBy('appointment_done_datetime','DESC')
                ->forPage($page, $pageSize)
                ->get()
                ->toArray();

        foreach ($rows as &$quota) {
            $quota['premises'] = '';
            $quota['username'] = '';
            if (!empty($quota['appointment_done_json'])) {
                $doneJson = json_decode($quota['appointment_done_json'], true);
                $quota['premises'] = $doneJson['charge']['charge_premises'] ?? '';
                $quota['remark'] = $doneJson['charge']['charge_content'] ?? '';
                $quota['charge_waiter'] = $doneJson['charge']['charge_waiter'] ?? '';
                if (isset($doneJson['charge']['charge_user_id'])) {
                    $user = SysUser::where('user_id', $doneJson['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);
    }

    public function service(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 20);
        $memberId = $request->get('member_id', '');
        $benefit = MemberBenefit::with([
            'goods' => function ($query) {
                $query->select('goods_id', 'goods_name');
            },
//            'order'
        ])
            ->where('join_benefit_member_id', $memberId)
            ->where('join_benefit_package_id', '');
            // ->where('member_benefit_category','SERVICE')

            
        $total = $benefit->count('*');
        $rows = $benefit->orderBy('member_benefit_addtimes','DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        foreach ($rows as &$item){
            $item['member_benefit_limit_count'] = intval($item['member_benefit_limit_count']);
            $item['member_benefit_used_count'] = intval($item['member_benefit_used_count']);
        }

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