<?php

namespace app\admin\controller\coupon;

use app\admin\service\coupon\CouponService;
use app\admin\service\member\MemberService;
use app\controller\Curd;
use app\model\Coupon;
use app\model\CouponDetail;
use app\model\CouponGoods;
use app\model\CouponPacket;
use app\model\CouponPacketSequence;
use app\model\MemberRole;
use app\model\SysCategory;
use app\model\SysDept;
use support\Request;
use support\Response;

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

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

        $couponPacketName = $request->get('coupon_packet_name', '');
        if (!empty($couponPacketName)) {
            $packetIds = CouponPacket::where('coupon_packet_name', 'like', '%' . $couponPacketName . '%')->pluck('coupon_packet_id')->toArray();
            $where['join_sequence_coupon_packet_id'] = ['in', $packetIds];
        }
        $addTimes = $request->get('coupon_packet_sequence_addtimes', []);
        if (!empty($addTimes)) {
            $addTimes[0] = isset($addTimes[0]) ? strtotime($addTimes[0]) : time();
            $addTimes[1] = isset($addTimes[1]) ? strtotime($addTimes[1]) : time();

            $where['coupon_packet_sequence_addtimes'] = $addTimes;
        }
        $usedTime = $request->get('coupon_packet_sequence_used_datetime', []);
        if (!empty($usedTime)) {
            $usedTime[0] = isset($usedTime[0]) ? strtotime($usedTime[0]) : time();
            $usedTime[1] = isset($usedTime[1]) ? strtotime($usedTime[1]) : time();

            $where['coupon_packet_sequence_used_datetime'] = $usedTime;
        }

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

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        if (!empty($where['coupon_packet_sequence_used_datetime'])) {
            $usedTime = $where['coupon_packet_sequence_used_datetime'];
            unset($where['coupon_packet_sequence_used_datetime']);
        }
        $model = $this->model->with([
            'packet' => function ($query) {
                $query->select('coupon_packet_id', 'coupon_packet_name');
            },
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'info' => function ($query) {
                $query->select('join_info_member_id', 'member_info_nickname');
            }
        ]);
        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 (!empty($usedTime)) {
            $model = $model->whereRaw("UNIX_TIMESTAMP(coupon_packet_sequence_used_datetime) >= ? AND UNIX_TIMESTAMP(coupon_packet_sequence_used_datetime) <= ?", [$usedTime[0], $usedTime[1]]);
        }
//        $model = $model->selectRaw('join_detail_coupon_id,join_coupon_detail_member_id,MAX(coupon_detail_addtimes) as coupon_detail_addtimes,COUNT(*) as total');
//        $model = $model->groupBy('join_coupon_detail_member_id', 'join_detail_coupon_id');
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            $mobile = $certName = $nickname = '';
            if (!empty($item['member']) && !empty($item['member']['member_mobile'])) {
                $mobile = $item['member']['member_mobile'];
            }
            if (!empty($item['cert']) && !empty($item['cert']['member_cert_name'])) {
                $certName = $item['cert']['member_cert_name'];
            }
            if (!empty($item['info']) && !empty($item['info']['member_info_nickname'])) {
                $nickname = $item['info']['member_info_nickname'];
            }
            $item['member_name'] = MemberService::getMemberName($mobile, $certName, $nickname);
        }

        return $items;
    }

    /**
     * @Desc 修改状态
     * @Author Gorden
     * @Date 2024/8/22 8:44
     *
     * @param Request $request
     * @return Response
     */
    public function updateStatus(Request $request)
    {
        $detailId = $request->post('coupon_detail_id', '');
        $status = $request->post('status', '');

        $detail = CouponDetail::where('coupon_detail_id', $detailId)->first();
        if (!$detail) {
            return json_fail('数据不存在');
        }
        //状态 INIT|PENDING=等待领取|ACTIVED=可用|WAITING=已占用(待完成)|USED=已使用|DISABLED|CANCEL|EXPIRED
        if (!in_array($status, ['INIT', 'PENDING', 'ACTIVED', 'WAITING', 'USED', 'DISABLED', 'CANCEL', 'EXPIRED'])) {
            return json_fail("状态异常");
        }
        try {
            CouponDetail::where('coupon_detail_id', $detailId)->update(['coupon_detail_status' => $status]);

            return json_success('success');
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据修改失败');
        }
    }

    /**
     * @Desc 详情
     * @Author Gorden
     * @Date 2024/8/22 11:46
     *
     * @param Request $request
     * @return Response
     */
    public function info(Request $request): Response
    {
        $packetSequenceId = $request->get('coupon_packet_sequence_id', '');
        if (empty($packetSequenceId)) {
            return json_fail('参数异常');
        }

        $sequence = CouponPacketSequence::with([
            'packet' => function ($query) {
                $query->select('coupon_packet_id', 'coupon_packet_name', 'join_coupon_packet_category_id', 'join_coupon_packet_dept_id', 'coupon_packet_status', 'coupon_packet_issue_num', 'coupon_packet_issue_datetime');
            },
            'member' => function ($query) {
                $query->select('member_id', 'join_member_role_id', 'member_is_owner', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
            },
            'info' => function ($query) {
                $query->select('join_info_member_id', 'member_info_headimg');
            }
        ])->where('coupon_packet_sequence_id', $packetSequenceId)
            ->first();
        if (!empty($sequence->packet)) {
            if ($sequence->packet->join_coupon_packet_dept_id == 0) {
                $sequence->packet->dept_name = '所有门店';
            } else {
                $sequence->packet->dept_nam = '';
                $dept = SysDept::where('dept_id', $sequence->packet->join_coupon_packet_dept_id)->select('dept_id', 'dept_name')->first();
                if (!empty($dept)) {
                    $sequence->packet->dept_name = $dept->dept_name;
                }
            }
            if (!empty($sequence->packet->join_coupon_packet_category_id)) {
                $category = SysCategory::where('category_id', $sequence->packet->join_coupon_packet_category_id)
                    ->first();
                if (!empty($category->category_name)) {
                    $sequence->packet->category_name = $category->category_name;
                }
            }
        }
        if (!empty($sequence->member) && !empty($sequence->member->join_member_role_id)) {
            $sequence->member->role_name = MemberRole::where('member_role_id', $sequence->member->join_member_role_id)->value('member_role_name');
        }
        if (!empty($sequence->info) && !empty($sequence->info->member_info_headimg)){
            $sequence->info->member_info_headimg = MemberService::getAvatarUrl($sequence->info->member_info_headimg);
        }
        $coupons = [];
        if (!empty($sequence->coupon_packet_sequence_json)) {
            $sequenceJson = json_decode($sequence->coupon_packet_sequence_json, true);
            if (isset($sequenceJson['coupons'])) {
                $couponIds = array_keys($sequenceJson['coupons']);
                $couponModel = Coupon::whereIn('coupon_id', $couponIds)
                    ->select('coupon_id', 'coupon_name', 'coupon_classify', 'coupon_value', 'coupon_minimum_limit', 'coupon_category')
                    ->get()
                    ->toArray();
                foreach ($couponModel as $coupon) {
                    foreach ($sequenceJson['coupons'] as $key => $jsonCoupon) {
                        if ($coupon['coupon_id'] == $key) {
                            $coupons[] = [
                                'id' => $key,
                                'name' => $coupon['coupon_name'],
                                'nbr' => $jsonCoupon['num'],
                                'classify' => $coupon['coupon_classify'],
                                'info' => CouponService::couponClassifyInfo($coupon['coupon_classify'], $coupon['coupon_category'], $coupon['coupon_value'], $coupon['coupon_minimum_limit'])
                            ];
                        }
                    }
                }
            }
        }
        $sequence->coupons = $coupons;

        return json_success('', $sequence);
    }

    public function myCouponGrouping(Request $request)
    {
        $memberId = $request->get('member_id', '');
        $goods = $request->get('goods', []);
        $settlementNow = $request->get('settlement_now', 'N');
        if ($memberId == '') {
            return json_fail("参数异常");
        }

        $goodsIds = array_column($goods, 'goods_id');
        $couponGoods = CouponGoods::whereIn('join_coupon_goods_id', $goodsIds)->get()->toArray();
        $couponIds = [];
        foreach ($couponGoods as $couponGood) {
            foreach ($goods as $good) {
                if ($good['sku_id'] = $couponGood['join_coupon_goods_sku_id']) {
                    $couponIds[] = $couponGood['join_goods_coupon_id'];
                }
            }
        }

        $details = CouponDetail::with([
            'coupon' => function ($query) {
                $query->select('coupon_id', 'coupon_name', 'coupon_classify', 'coupon_value', 'coupon_category', 'coupon_minimum_limit');
            }
        ])->whereIn('join_detail_coupon_id', $couponIds)
            ->where('join_coupon_detail_member_id', $memberId);
        if ($settlementNow == 'Y') {
            $details = $details->whereIn('coupon_detail.coupon_detail_status', ['ACTIVED', 'WAITING']);
        } else {
            $details = $details->where('coupon_detail.coupon_detail_status', 'ACTIVED');
        }
        $details = $details->selectRaw('join_detail_coupon_id,join_coupon_detail_member_id,COUNT(*) as count')
            ->groupBy('join_detail_coupon_id', 'join_coupon_detail_member_id')
            ->get()
            ->toArray();
        $data = [];
        foreach ($details as $detail) {
            if (empty($detail['coupon'])) {
                continue;
            }
            $classify = CouponService::couponClassifyInfo($detail['coupon']['coupon_classify'], $detail['coupon']['coupon_category'], $detail['coupon']['coupon_value'], $detail['coupon']['coupon_minimum_limit']);
            $data[] = [
                'coupon_id' => $detail['coupon']['coupon_id'],
                'coupon_name' => $detail['coupon']['coupon_name'],
                'classify' => $classify,
                'count' => $detail['count'],
                'coupon_classify' => $detail['coupon']['coupon_classify'],
                'coupon_value' => $detail['coupon']['coupon_value'] ?? '',
                'coupon_minimum_limit' => $detail['coupon']['coupon_minimum_limit'] ?? '',
            ];
        }

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