<?php

namespace app\controller\manager\mall;

use app\controller\manager\Base;
use app\model\Account;
use app\model\AccountCoupon as AccountCouponModel;
use app\model\Coupon as CouponModel;
use app\model\Log;
use app\service\Math;
use Exception;
use think\exception\ValidateException;
use think\response\Json;

class Coupon extends Base
{
    /**
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 20);

            $startAt = $this->request->param('begin_at/s', '');
            $endAt   = $this->request->param('end_at/s', '');

            $whereMap[] = ['deleted_at', '=', null];
            $order      = ['sort' => 'desc', 'id' => 'desc'];

            if (!empty($startAt) && strtotime($startAt)) {
                $whereMap[] = ['begin_at', '>=', $startAt];
            }
            if (!empty($endAt) && strtotime($endAt)) {
                $whereMap[] = ['end_at', '<=', $endAt];
            }

            $res = CouponModel::findList($whereMap, [], $page, $size, null, $order);

            $res['list'] = $res['list']->each(function ($item) {
                $item->type_text = CouponModel::typeTextList()[$item->type] ?? '';
            });
            return $this->json(0, 'success', $res);
        }

        return $this->view();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $item = $this->request->param('item/a', []);

            try {
                $rules = [
                    'name|优惠券名称'     => 'require',
                    'condition|消费额度' => 'float',
                    'amount|优惠额度'    => 'float',
                    'total|发行总量'     => 'require|integer|gt:0',
                    'begin_at|开始时间'  => 'require|date',
                    'end_at|截止时间'    => 'require|date',
                ];

                $validate = $this->validateByApi($item, $rules);
                if ($validate !== true) {
                    return $validate;
                }

                if ($item['end_at'] <= $item['begin_at']) {
                    throw new ValidateException('优惠期限的截止时间必须大于开始时间！');
                }

                if ($item['is_home'] == CouponModel::COMMON_ON && empty($item['cover'])) {
                    throw new ValidateException('推荐首页时必传封面图');
                }

                $data = arrayKeysFilter($item, [
                    'name', 'cover', 'type', 'condition', 'amount', 'begin_at', 'end_at', 'is_home', 'total'
                ]);

                $data['created_at'] = date('Y-m-d H:i:s');
                $data['remain']     = $data['total'];
                CouponModel::create($data);
            } catch (ValidateException $e) {
                return $this->json(4001, $e->getMessage());
            } catch (Exception $e) {
                return $this->json(5000, '新增优惠卷失败！');
            }

            return $this->json();
        }

        $this->data['typeList'] = CouponModel::typeTextList();

        return $this->view();
    }

    /**
     * @throws Exception
     */
    public function modify()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $item     = input('post.');
        $validate = $this->validateByApi($item, [
            'field' => 'require',
            'value' => 'require',
        ]);

        if ($validate !== true) {
            return $validate;
        }

        if (!$info = CouponModel::findById($item['id'])) {
            return $this->json(4001, '记录不存在');
        }

        $update = [$item['field'] => $item['value']];

        try {
            $info->save($update);
            return $this->json();
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            return $this->json(5000, '修改失败');
        }
    }


    /**
     * 软删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids   = array_filter($ids);
        }

        if (count($ids)) {
            CouponModel::where('id', 'in', $ids)->save(['deleted_at' => date('Y-m-d H:i:s')]);
            Log::write(get_class(), 'del', '删除了优惠卷信息，涉及到的ID为：'.implode(',', $ids));
        }

        return $this->json();
    }

    //用户持有优惠券的列表
    public function accountHasList()
    {
        $id = input("id/d", 0);
        if ($this->request->isPost()) {
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 20);

            $order = ['id' => 'desc'];
            $res = AccountCouponModel::findList(["coupon_id" => $id], [], $page, $size, function ($q) {
                return $q->with(["coupon", "account"]);
            }, $order);
            $res['list'] = $res['list']->each(function ($item) {
                $item->type_text = CouponModel::typeTextList()[$item->type] ?? '';
                $item->check_by_account = Account::findOne(["id" => $item->check_by,], ["nickname"]);
            });
            return $this->json(0, 'success', $res);
        }
        $this->data["id"] = $id;
        return $this->view();
    }


}