<?php

namespace app\controller\manager\mall;

use app\controller\manager\Base;
use app\model\Log;
use app\model\Express as ExpressModel;
use app\repository\OrderRepository;
use app\service\Math;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

/**
 * 快递配送管理
 * Class Express
 * @package app\controller\manager\mall
 */
class Express extends Base
{
    public function index()
    {
        if ($this->request->isPost()) {
            $items = OrderRepository::getInstance()->allExpress();
            $items->each(function ($item) {
                $item->default_price = Math::fen2Yuan($item->default_price);
            });
            $data  = [
                'total' => $items->count(),
                'list'  => $items,
            ];

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

        return $this->view();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param('item/a', []);
            $validate = $this->validateByApi($data, [
                'code|快递代号' => 'require|unique:express',
            ]);

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

            if ($data['is_default'] == ExpressModel::COMMON_ON) {
                if (ExpressModel::where('is_default', ExpressModel::COMMON_ON)->count() > 0) {
                    return $this->json(4001, '默认快递已存在');
                }
            }

            OrderRepository::getInstance()->addExpress($data);

            return $this->json();
        }

        return $this->view();
    }

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

        if (!$express = ExpressModel::findById($id)) {
            return $this->json(4004, '没有相关的快递公司记录');
        }

        if ($this->request->isPost()) {
            $data = $this->request->param('item/a', []);
            $validate = $this->validateByApi($data, [
                'code|快递代号' => 'require|unique:express,code,'.$id,
            ]);

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

            if ($data['is_default'] == ExpressModel::COMMON_ON) {
                if (ExpressModel::where('id', '<>', $id)->where('is_default', ExpressModel::COMMON_ON)->count() > 0) {
                    return $this->json(4001, '默认快递已存在');
                }
            }

            $express->save($data);

            return $this->json();
        }

        $express->default_price = Math::fen2Yuan($express->default_price);
        $this->data['item'] = $express;
        $this->data['id']   = $id;
        return $this->view();
    }

    /**
     * @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)) {
            ExpressModel::deleteByIds($ids);
            Log::write(get_class(), 'del', '删除了快递记录，涉及到的ID为：'.implode(',', $ids));
        }

        return $this->json();
    }
}