<?php

namespace app\controller\manager\mall\activity;

use app\controller\manager\Base;
use app\exception\RepositoryException;
use app\model\Log;
use app\model\mall\SpuLimitTime;
use app\model\Order;
use app\model\Sku;
use app\model\Spu as SpuModel;
use app\model\SpuActivity;
use app\repository\SpuRepository;
use app\service\Math;
use Exception;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;
use think\response\View;

class LimitTime extends Base
{
    protected $noNeedLogin = ['getOrder'];

    /**
     * 列表
     *
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $keyword = input('keyword/s');
            $page    = input('page/d', 1);
            $size    = input('size/d', 20);

            $where = [];
            if (!empty($keyword)) {
                $where[] = ['keyword', 'like', '%'.$keyword.'%'];
            }
            $where[] = ['deleted_at', 'exp', Db::raw('is null')];
            $order   = ['sort' => 'desc', 'id' => 'desc'];
            $res     = SpuLimitTime::fetchList($where, [], $page, $size, null, $order);

            return $this->json(0, 'success', $res);
        }

        return $this->view();
    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $item  = $this->request->param('item/a', []);
            $skus  = input('post.skus');//规格数据
            $spuId = $this->request->param('spu_id/d', 0);

            $rules = [
                'name|活动名称'     => 'require',
                'cover|封面图'     => 'require',
                'begin_at|开始时间' => 'require|date',
                'end_at|结束时间'   => 'require|date',
            ];

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

            try {
                $item['spu_id'] = $spuId;
                SpuRepository::getInstance()->addLimitTime($item, $skus);
            } catch (RepositoryException $e) {
                return $this->json(4002, $e->getMessage());
            } catch (Exception $e) {
                SpuRepository::log('限时折扣创建失败', $e);
                return $this->json(5000, '限时折扣创建失败');
            }

            return $this->json();
        }

        return $this->view();
    }

    /**
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function edit()
    {
        $id = $this->request->param('id/d', 0);

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

            $rules = [
                'name|活动名称'     => 'require',
                'cover|封面图'     => 'require',
                'begin_at|开始时间' => 'require|date',
                'end_at|结束时间'   => 'require|date',
            ];

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

            try {
                SpuRepository::getInstance()->editLimitTime($id, $item, $skus);
            } catch (RepositoryException $e) {
                return $this->json(4002, $e->getMessage());
            } catch (Exception $e) {
            }

            return $this->json();
        }

        $limitTime = SpuLimitTime::findById($id);
        if (empty($limitTime)) {
            return $this->json(4000, '没有相关记录！');
        }
        if (!$spuInfo = SpuModel::findById($limitTime['spu_id'], ['id', 'name', 'multi_spec', 'spu_type_id'])) {
            return $this->json(4000, '基础商品不存在！');
        }

        $this->data['item'] = $limitTime;
        $this->data['id']   = $id;
        $this->data['spu']  = $spuInfo;
        return $this->view();
    }

    /**
     * @throws RepositoryException
     * @throws Exception
     */
    protected function checkSku(array $sku)
    {
        // sku验证
        if (empty($sku)) {
            throw new RepositoryException('规格信息不能为空');
        }

        foreach ($sku as $k) {
            $validate = $this->validateByApi($k, [
                'title'      => 'require',
                'stock'      => 'require|number|gt:0',
                'price'      => 'number',
                'score'      => 'number',
                'is_default' => 'require|in:0,1',
            ]);

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

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @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 = SpuActivity::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);
        }
        try {
            if (count($ids)) {
                SpuRepository::getInstance()->restoreLimitTime($ids, true);
                Log::write(get_class(), 'del', '删除了活动商品，涉及到的ID为：'.implode(',', $ids));
            }
        } catch (Exception $e) {
            return $this->json(4001, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 结束-还原为普通商品 暂停
     *
     * @return Json
     */
    public function end(): 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);
        }

        try {
            if (count($ids)) {
                SpuRepository::getInstance()->restoreLimitTime($ids);
                Log::write(get_class(), 'del', '结束了活动商品，涉及到的ID为：'.implode(',', $ids));
            }
        } catch (Exception $e) {
            return $this->json(4001, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 重新启动
     *
     * @return Json
     */
    public function restart(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        try {
            $ids = input('ids');
            SpuRepository::getInstance()->restart($ids[0]);
            Log::write(get_class(), 'restart', '重启了活动商品，涉及到的ID为：'.$ids[0]);
        } catch (Exception $e) {
            return $this->json(4001, $e->getMessage());
        }

        return $this->json();
    }


    /**
     * 活动商品详情
     *
     * @return View
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     */
    public function info(): View
    {
        $id   = input('id/d', 0);
        $item = SpuActivity::findById($id);

        $status = '';
        $now    = date('Y-m-d H:i:s');
        if ($item['begin_at'] > $now) {
            $status = '未开始';
        }

        if ($item['begin_at'] < $now && $now < $item['end_at']) {
            $status = '进行中';
        }

        if ($item['status'] == 0 || $item['end_at'] < $now) {
            $status = '已结束';
        }

        $item->status_text = $status;


        $orderList = SpuRepository::getInstance()->getActivityOrderList($id);

        $totalPriceList      = $orderList['list']->where('is_paid', SpuActivity::COMMON_ON)->column('total_price');
        $codingList          = $orderList['list']->column('coding');
        $accountList         = $orderList['list']->column('account_id');
        $codingCount         = count(array_unique($codingList));
        $accountCount        = count(array_unique($accountList));
        $totalPrice          = array_sum($totalPriceList);
        $item->total_money   = Math::fen2Yuan($totalPrice) ?? 0;
        $item->order_count   = $codingCount;
        $item->account_count = $accountCount;

        $this->data['item']         = $item;
        $this->data['statusList']   = Order::statusTextList();
        $this->data['activityList'] = SpuModel::activityTextList();
        $this->data['limitList']    = SpuModel::limitList();//限购天数展示

        return $this->view();
    }

    /**
     * 获取活动商品的订单列表
     *
     * @return Json
     * @throws Exception
     */
    public function getOrder(): Json
    {
        $id   = input('id/d', 0);
        $page = input('page/d', 1);
        $size = input('size/d', 20);

        $res = SpuRepository::getInstance()->getActivityOrderList($id, $page, $size);

        return $this->json(0, '操作成功', $res);
    }
}