<?php

namespace app\admin\logic;

use app\model\CardModel;
use app\model\CommonModel;
use app\model\CompanyModel;
use app\model\GroupModel;
use think\Exception;
use think\exception\ValidateException;
use think\facade\Db;
use think\response\Json;

class GroupLogic extends BaseLogic
{

    //获取列表
    public static function list(array $data = []): Json
    {
        $db = GroupModel::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['company_title'] != '') $db->whereLike('b.title', '%' . $data['company_title'] . '%');
        if ($data['card_title'] != '') $db->whereLike('c.title', '%' . $data['card_title'] . '%');
        if ($data['combination'] != '') $db->whereLike('a.combination', '%' . $data['combination'] . '%');

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

        $list = $db->field('a.id,b.title company_title,c.title card_title,a.combination,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 = GroupModel::field('id')
            ->where(['is_del' => CommonModel::$del_normal, 'company_id' => $data['company_id'], 'card_id' => $data['card_id']])
            ->findOrEmpty()
            ->isEmpty();
        if (!$rs) return json_show(CommonModel::$error_param, '该分组已存在');

        $company = CompanyModel::field('id,title')
            ->where(['is_del' => CommonModel::$del_normal, 'id' => $data['company_id']])
            ->findOrEmpty();
        if ($company->isEmpty()) return json_show(CommonModel::$error_param, '该企业不存在');

        $card = CardModel::field('id,title')
            ->where(['is_del' => CommonModel::$del_normal, 'id' => $data['card_id']])
            ->findOrEmpty();
        if ($card->isEmpty()) return json_show(CommonModel::$error_param, '该卡类型不存在');


        $res = GroupModel::create(array_merge($data, [
            'combination' => $company->title . '_' . $card->title,
            'status' => CommonModel::$status_normal,
            'is_del' => CommonModel::$del_normal,
            'addtime' => date('Y-m-d H:i:s'),
            'updatetime' => date('Y-m-d H:i:s'),
        ]))->save();

        return $res ? json_show(CommonModel::$success, '添加分组成功') : json_show(CommonModel::$success, '添加分组失败');

    }

    //获取详情
    public static function read(int $id = 0): Json
    {
        $res = GroupModel::field(true)
            ->where(['id' => $id, 'is_del' => CommonModel::$del_normal])
            ->findOrEmpty()
            ->toArray();

        if (empty($res)) throw new ValidateException('该分组为空');

        return json_show(CommonModel::$success, '获取详情成功', $res);
    }

    //编辑
    public static function edit(array $data = []): Json
    {

        $rs = GroupModel::field('id,company_id,card_id')
            ->where([
                'id' => $data['id'],
                'is_del' => CommonModel::$del_normal,
            ])
            ->findOrEmpty();
        if ($rs->isEmpty()) return json_show(CommonModel::$error_param, '该分组不存在');

        if (($rs->company_id != $data['company_id']) || ($rs->card_id != $data['card_id'])) {

            $temp = GroupModel::field('id')
                ->where(['is_del' => CommonModel::$del_normal, 'company_id' => $data['company_id'], 'card_id' => $data['card_id']])
                ->findOrEmpty()
                ->isEmpty();
            if (!$temp) return json_show(CommonModel::$error_param, '该分组已存在');

            $company = CompanyModel::field('id,title')
                ->where(['is_del' => CommonModel::$del_normal, 'id' => $data['company_id']])
                ->findOrEmpty();
            if ($company->isEmpty()) return json_show(CommonModel::$error_param, '该企业不存在');

            $card = CardModel::field('id,title')
                ->where(['is_del' => CommonModel::$del_normal, 'id' => $data['card_id']])
                ->findOrEmpty();
            if ($card->isEmpty()) return json_show(CommonModel::$error_param, '该卡类型不存在');

            $data['combination'] = $company->title . '_' . $card->title;

        }

        $res = GroupModel::where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
            ->save(array_merge($data, ['updatetime' => date('Y-m-d H:i:s')]));

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

    }

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

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

    }

    //删除
    public static function delete(array $ids = []): Json
    {
        $rs = GroupModel::whereIn('id', $ids)
            ->where('is_del', CommonModel::$del_normal)
            ->save(['is_del' => CommonModel::$del_deleted, 'updatetime' => date('Y-m-d H:i:s')]);

        return $rs ? json_show(CommonModel::$success, '删除成功') : json_show(CommonModel::$success, '删除失败');
    }


}