<?php

namespace app\admin\logic;

use app\model\CommonModel;
use app\model\ServiceModel;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class ServiceLogic extends BaseLogic
{

    //获取服务列表
    public static function list(array $data = []): Json
    {
        $db = ServiceModel::alias('a')
            ->leftJoin('company b', 'b.id=a.company_id AND b.is_del=' . CommonModel::$del_normal)
            ->leftJoin('card c', 'c.id=a.card_id AND c.is_del=' . CommonModel::$del_normal)
            ->where('a.is_del', CommonModel::$del_normal);

        if ($data['status'] != '') $db->where('a.status', $data['status']);
        if ($data['activity_status'] != '') $db->where('a.activity_status', $data['activity_status']);
        if ($data['company_title'] != '') $db->whereLike('b.title', '%' . $data['company_title'] . '%');
        if ($data['card_title'] != '') $db->whereLike('c.title', '%' . $data['card_title'] . '%');

        $count = $db->count('a.id');

        $list = $db->field('a.id,b.title company_title,c.title card_title,a.title,a.original_price,a.activity_price,a.starttime,a.endtime,a.status,a.addtime')
            ->page($data['page'], $data['size'])
            ->order(['a.id' => 'desc'])
            ->select()
            ->toArray();

        return json_show(CommonModel::$success, '获取服务列表成功', ['count' => $count, 'list' => $list]);
    }

    //添加服务
    public static function add(array $data = []): Json
    {
        $rs = ServiceModel::field('id')
            ->where([
                'is_del' => CommonModel::$del_normal,
                'title' => $data['title'],
            ])
            ->findOrEmpty()
            ->isEmpty();
        if (!$rs) return json_show(CommonModel::$error_param, '该服务已存在');

        $date = date('Y-m-d H:i:s');

        $data = array_merge($data, [
            'activity_status' => ServiceModel::$activity_status_not_started,
            'status' => CommonModel::$status_normal,
            'is_del' => CommonModel::$del_normal,
            'createrid' => self::$uid,
            'creater' => self::$uname,
            'addtime' => $date,
            'updaterid' => self::$uid,
            'updater' => self::$uname,
            'updatetime' => $date,
            'endtime' => date('Y-m-d 23:59:59', strtotime($data['endtime'])),
            'expiretime' => date('Y-m-d 23:59:59', strtotime($data['expiretime'])),
        ]);

        $res = ServiceModel::create($data)->save();

        return $res ? json_show(CommonModel::$success, '添加服务成功') : json_show(CommonModel::$error_param, '添加服务失败');

    }

    //获取服务详情
    public static function read(int $id = 0): Json
    {
        $res = ServiceModel::alias('a')
            ->field('a.*,b.title company_title,c.title card_title')
            ->leftJoin('company b', 'b.id=a.company_id AND b.is_del=' . CommonModel::$del_normal)
            ->leftJoin('card c', 'c.id=a.card_id AND c.is_del=' . CommonModel::$del_normal)
            ->where(['a.id' => $id, 'a.is_del' => CommonModel::$del_normal])
            ->findOrEmpty()
            ->toArray();

        return empty($res) ? json_show(CommonModel::$error_param, '该服务为空') : json_show(CommonModel::$success, '获取服务详情成功', $res);
    }

    //编辑服务
    public static function edit(array $data = []): Json
    {
        $rs = ServiceModel::field('id,title')
            ->where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
            ->findOrEmpty();
        if ($rs->isEmpty()) return json_show(CommonModel::$error_param, '该服务不存在');

        if (($rs->title != $data['title'])) {
            $temp = ServiceModel::field('id')
                ->where(['is_del' => CommonModel::$del_normal, 'title' => $data['title']])
                ->findOrEmpty()
                ->isEmpty();
            if (!$temp) return json_show(CommonModel::$error_param, '该分组名称已存在');
        }

        $date = date('Y-m-d H:i:s');

        $res = ServiceModel::where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
            ->save(array_merge($data, ['updatetime' => $date, 'updaterid' => self::$uid, 'updater' => self::$uname]));

        return $res ? json_show(CommonModel::$success, '编辑服务成功') : json_show(CommonModel::$success, '编辑服务失败');

    }

    //服务启禁用
    public static function status(array $data = []): Json
    {
        $res = ServiceModel::where('id', $data['id'])
            ->where('status', '<>', $data['status'])
            ->save([
                'status' => $data['status'],
                'updatetime' => date('Y-m-d H:i:s'),
                'updaterid' => self::$uid,
                'updater' => self::$uname
            ]);

        return $res ? json_show(CommonModel::$success, '操作成功') : json_show(CommonModel::$success, '该服务不存在或重复操作');

    }

    //删除服务
    public static function delete(array $ids = []): Json
    {

        Db::startTrans();
        try {

            $res = ServiceModel::whereIn('id', $ids)
                ->where('is_del', CommonModel::$del_normal)
                ->save([
                    'is_del' => CommonModel::$del_deleted,
                    'updatetime' => date('Y-m-d H:i:s'),
                    'updaterid' => self::$uid,
                    'updater' => self::$uname
                ]);

            if (!$res) throw new Exception('该服务不存在');

            Db::name('good_group_item')
                ->whereIn('good_group_id', $ids)
                ->where('is_del', CommonModel::$del_normal)
                ->update([
                    'is_del' => CommonModel::$del_deleted,
                    'updatetime' => date('Y-m-d H:i:s')
                ]);

            Db::commit();
            return json_show(CommonModel::$success, '删除成功');

        } catch (Exception $exception) {
            Db::rollback();
            return json_show(CommonModel::$error_param, '删除失败,' . $exception->getMessage());

        }
    }


}