<?php

namespace app\admin\controller\coupon;

use app\admin\service\coupon\CouponDetailService;
use app\admin\service\coupon\CouponService;
use app\admin\validate\coupon\CouponValidate;
use app\admin\validate\device\DeviceValidate;
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\Device;
use app\model\Member;
use app\model\SysDept;
use app\model\SysSerial;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

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

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/3/28 15:01
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        if (!empty($where['coupon_packet_addtimes'])) {
            $where['coupon_packet_addtimes'][0] = strtotime($where['coupon_packet_addtimes'][0]);
            $where['coupon_packet_addtimes'][1] = strtotime($where['coupon_packet_addtimes'][1]);
        }
        $order = $request->get('order', 'desc');
        $field = $field ?? 'coupon_packet_addtimes';
        $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([
            'category' => function ($query) {
                $query->select('category_id', 'category_name');
            },
            'user',
            'dept'
//            'detail'
        ]);
        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 afterQuery($items)
    {
        foreach ($items as &$item) {
            if (empty($item['dept'])) {
                $item['dept_all'] = [
                    'dept_id' => 0,
                    'dept_name' => "所有门店"
                ];
            }
            $item['used_total'] = CouponPacketSequence::where('join_sequence_coupon_packet_id',$item['coupon_packet_id'])
                ->where('coupon_packet_sequence_status','USED')
                ->count();
            $item['unused_total'] = $item->coupon_packet_issue_num - $item['used_total'];
        }

        return $items;
    }

    public function selectList()
    {
        $coupons = Coupon::where('coupon_status', 'ACTIVED')
            ->select('coupon_id', 'coupon_name')
            ->orderBy('coupon_addtimes', 'DESC')
            ->get()
            ->toArray();

        return json_success('', $coupons);
    }

//    public function afterQuery($items)
//    {
//        foreach ($items as &$item) {
//            $item->coupon_begindate = date('Y-m-d H:i:s', $item->coupon_begindate);
//            $item->coupon_enddate = date('Y-m-d H:i:s', $item->coupon_enddate);
//        }
//
//        return $items;
//    }

    /**
     * @Desc 添加优惠券
     * @Author Gorden
     * @Date 2024/8/14 15:16
     *
     * @param Request $request
     * @return Response
     */
    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }
        Db::beginTransaction();
        try {
            $data = $this->insertInput($request);
            $data['join_coupon_packet_user_id'] = JwtToken::getCurrentId();
            $data['coupon_packet_status'] = 'PENDING';
            $this->doInsert($data);
            Db::commit();

            return json_success('success');
        } catch (BusinessException $customException) {
            Db::rollBack();
            dump($customException->getMessage());
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getMessage());
            return json_fail('数据写入失败');
        }
    }

    /**
     * @Desc 关联优惠券、产品、规格
     * @Author Gorden
     * @Date 2024/8/14 14:32
     *
     * @param $goods
     * @param $couponId
     * @return void
     * @throws BusinessException
     */
    public function insertCouponGoods($goods, $couponId)
    {
        try {
            foreach ($goods as $good) {
                CouponGoods::insert([
                    'join_goods_coupon_id' => $couponId,
                    'join_coupon_goods_id' => $good['goods_id'],
                    'join_coupon_goods_sku_id' => $good['sku_id'],
                    'coupon_goods_json' => '[]',
                    'coupon_goods_extend_json' => '[]',
                    'coupon_goods_addtimes' => time()
                ]);
            }
        } catch (\Exception $e) {
            throw new BusinessException("关联产品失败");
        }
    }

    protected function insertInput(Request $request): array
    {
        $params = $request->post();
        $data = $this->inputFilter($params);
        $data['coupon_packet_id'] = "CP" . date("ymdHi") . random_string(4, 'up');
        $coupons = [];
        if (!empty($params['coupons'])) {
            foreach ($params['coupons'] as $coupon) {
                $coupons[$coupon['id']]['num'] = $coupon['nbr'];
            }
        }

        $data['coupon_packet_json'] = json_encode(['coupons' => $coupons]);

        dump($data);
        return $data;
    }

    /**
     * @Desc 修改优惠券
     * @Author Gorden
     * @Date 2024/8/14 15:48
     *
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        Db::beginTransaction();
        try {
            [$id, $data] = $this->updateInput($request);

            $this->doUpdate($id, $data);

            Db::commit();

            return json_success('success');
        } catch (BusinessException $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getMessage());
            return json_fail('数据更新失败');
        }

    }

    protected function updateInput(Request $request): array
    {
        $params = $request->post();
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($params);
        $model = $this->model->find($id);
        $coupons = [];
        if (!empty($params['coupons'])) {
            foreach ($params['coupons'] as $coupon) {
                $coupons[$coupon['id']]['num'] = $coupon['nbr'];
            }
        }
        $packetJson = [];
        if (!empty($model->coupon_packet_json)) {
            $packetJson = json_decode($model->coupon_packet_json, true);
        }
        $packetJson['coupons'] = $coupons;

        $data['coupon_packet_json'] = json_encode($packetJson);

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

    /**
     * 优惠券详情
     */
    public function info(Request $request): Response
    {
        $packetId = $request->get('packet_id', '');
        if (!$packetId) {
            return json_fail('参数异常');
        }
        $packet = CouponPacket::where('coupon_packet_id', $packetId)->first();
        if (!$packet) {
            return json_fail('数据异常');
        }
        $coupons = [];
        if (!empty($packet->coupon_packet_json)) {
            $packetJson = json_decode($packet->coupon_packet_json, true);
            if (isset($packetJson['coupons'])) {
                $couponIds = array_keys($packetJson['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 ($packetJson['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'])
                            ];
                        }
                    }
                }
            }
        }

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

        return json_success('', $data);
    }

    /**
     * 删除
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function delete(Request $request): Response
    {
        $ids = $this->deleteInput($request);
        Db::beginTransaction();
        try {
            if (CouponPacket::whereIn('coupon_packet_id', $ids)->where('coupon_packet_status', '=', 'ACTIVED')->exists()) {
                throw new BusinessException("有已发行的券包，无法删除");
            }
            $this->doDelete($ids);
            Db::commit();
            return json_success('success');
        } catch (BusinessException $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            Db::rollBack();
            return json_fail('删除失败');
        }
    }

    /**
     * @Desc 红包发行
     * @Author Gorden
     * @Date 2024/9/12 13:21
     *
     * @param Request $request
     * @return Response
     */
    public function packetIssue(Request $request)
    {
        $packetId = $request->post('packet_id');
        if (!$packetId) {
            return json_fail("参数异常");
        }
        $packet = CouponPacket::where('coupon_packet_id', $packetId)
            ->where('coupon_packet_status', 'PENDING')
            ->first();
        if (!$packet) {
            return json_fail('数据异常');
        }
        Db::beginTransaction();
        try {
            // 生成红包记录
            $this->generatePacket($packet);

            $packet->coupon_packet_status = 'ACTIVED';
            $packet->coupon_packet_issue_datetime = date('Y-m-d H:i:s');
            $packet->save();

            Db::commit();

            return json_success("success");
        } catch (BusinessException $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();

            dump($e->getMessage());
            return json_fail("发行失败");
        }
    }

    private function generatePacket(CouponPacket $couponPacket)
    {
        try {
            $length = $couponPacket->coupon_packet_seq_length;
            $prefixLength = strlen($couponPacket->coupon_packet_seq_prefix);
            $suffixLength = strlen($couponPacket->coupon_packet_seq_suffix);
            $seqBegin = $couponPacket->coupon_packet_seq_begin;
            $realLength = $length - $prefixLength - $suffixLength;
            $data = [];
            for ($i = 0; $i < $couponPacket->coupon_packet_issue_num; $i++) {
                if ($seqBegin > 0) {
                    $seqBegin = $i === 0 ? $seqBegin : $seqBegin + 1;
                    $data[] = $couponPacket->coupon_packet_seq_prefix . str_pad($seqBegin, $realLength, $couponPacket->coupon_packet_seq_fill, STR_PAD_LEFT) . $couponPacket->coupon_packet_seq_suffix;
                } else {
                    $data[] = $this->generateRandomStr($data, $realLength, $couponPacket->coupon_packet_seq_prefix, $couponPacket->coupon_packet_seq_suffi);
                }
            }

            $chunk = collect($data);
            $chunks = $chunk->chunk(100);
            foreach ($chunks as $item) {
                $insertData = [];
                foreach ($item as $k => $value) {
                    $insertData[$k] = [
                        'coupon_packet_sequence_id' => $value,
                        'join_sequence_coupon_packet_id' => $couponPacket->coupon_packet_id,
                        'coupon_packet_sequence_status' => 'PENDING',
                        'coupon_packet_sequence_json' => $couponPacket->coupon_packet_json,
                        'coupon_packet_sequence_addtimes' => time()
                    ];
                }
                CouponPacketSequence::insert($insertData);
            }
        } catch (\Exception $e) {
            dump($e->getMessage());
            throw new BusinessException("发行失败");
        }
    }

    private function generateRandomStr($data, $length, $prefix, $suffix)
    {
        $str = $prefix . random_string($length, 'up') . $suffix;
        if (in_array($str, $data)) {
            $this->generateRandomStr($data, $length, $prefix, $suffix);
        }

        return $str;
    }

    /**
     * @Desc 红包重新发行
     * @Author Gorden
     * @Date 2024/9/12 13:21
     *
     * @param Request $request
     * @return Response
     */
    public function packetReIssue(Request $request)
    {
        $packetId = $request->post('packet_id');
        if (!$packetId) {
            return json_fail("参数异常");
        }
        if (CouponPacketSequence::where('join_sequence_coupon_packet_id',$packetId)->where('coupon_packet_sequence_status','USED')->exists()){
            return json_fail('已有领取记录，无法重新发行');
        }
        $packet = CouponPacket::where('coupon_packet_id', $packetId)
            ->where('coupon_packet_status', 'ACTIVED')
            ->first();
        if (!$packet) {
            return json_fail('数据异常');
        }
        Db::beginTransaction();
        try {
            // 删除旧的记录
            CouponPacketSequence::where('join_sequence_coupon_packet_id',$packetId)->delete();
            // 生成红包记录
            $this->generatePacket($packet);

            $packet->coupon_packet_issue_datetime = date('Y-m-d H:i:s');
            $packet->save();

            Db::commit();

            return json_success("success");
        } catch (BusinessException $e) {
            Db::rollBack();
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            Db::rollBack();

            return json_fail("发行失败");
        }
    }
}