<?php

namespace app\admin\logic;

use app\model\CommonModel;
use app\model\GoodModel;
use think\exception\ValidateException;
use think\response\Json;

class GoodLogic extends BaseLogic
{
    //获取商品列表
    public static function list(array $data = []): Json
    {

        $db = GoodModel::alias('a')
            ->leftJoin('unit b', 'b.id=a.unit_id AND b.is_del=' . CommonModel::$del_normal)
            ->where('a.is_del', CommonModel::$del_normal);

        if ($data['good_code'] !== '') $db->whereLike('a.good_code', '%' . $data['good_code'] . '%');
        if ($data['good_name']) $db->whereLike('a.good_name', '%' . $data['good_name'] . '%');
        if ($data['status'] != '') $db->where('a.status', $data['status']);
        if ($data['type'] != '') $db->where('a.type', $data['type']);

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

        $list = $db
            ->field('a.id,a.good_cover_img,a.good_code,a.good_name,a.moq,a.step,b.unit,a.good_remark,a.type,a.price,a.status,a.creater,a.addtime')
            ->page($data['page'], $data['size'])
            ->order('a.addtime desc')
            ->select()
            ->toArray();

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

    //添加商品
    public static function add(array $data = []): Json
    {

        $rs = GoodModel::field('id')
            ->where(['is_del' => CommonModel::$del_normal, 'good_name' => $data['good_name']])
            ->findOrEmpty()
            ->isEmpty();

        if (!$rs) throw new ValidateException('该商品名称已存在');

        $good_code = make_no("SP");

        $res = GoodModel::create([
            'good_cover_img' => $data['good_cover_img'],
            'good_code' => $good_code,
            'good_name' => $data['good_name'],
            'moq' => $data['moq'],
            'step' => $data['step'],
            'type' => $data['type'],
            'price' => $data['price'],
            'good_banner_img' => implode(',', $data['good_banner_img']),
            'good_img' => implode(',', $data['good_img']),
            'good_param' => json_encode($data['good_param'], JSON_UNESCAPED_UNICODE),
            'good_remark' => $data['good_remark'],
            'unit_id' => $data['unit_id'],
            'is_del' => CommonModel::$del_normal,
            'status' => CommonModel::$status_normal,
            'createrid' => self::$uid,
            'creater' => self::$uname,
            'addtime' => date("Y-m-d H:i:s"),
            'updaterid' => self::$uid,
            'updater' => self::$uname,
            'updatetime' => date("Y-m-d H:i:s"),
        ])->save();

        return $res ? json_show(CommonModel::$success, '新建商品成功') : json_show(CommonModel::$error_param, '新建商品失败');
    }

    //读取商品详情
    public static function read(int $id = 0): Json
    {
        $rs = GoodModel::field(true)
            ->where(['id' => $id, 'is_del' => CommonModel::$del_normal])
            ->withAttr('good_banner_img', function ($val) {
                return explode(',', $val);
            })->withAttr('good_img', function ($val) {
                return explode(',', $val);
            })->withAttr('good_param', function ($val) {
                return json_decode($val);
            })
            ->findOrEmpty()
            ->toArray();
        return json_show(CommonModel::$success, '获取商品详情成功', $rs);
    }

    //编辑商品
    public static function edit(array $data = []): Json
    {
        $rs = GoodModel::field('id,good_name')
            ->where(['id' => $data['id'], 'is_del' => CommonModel::$del_normal])
            ->findOrEmpty();

        if ($rs->isEmpty()) throw new ValidateException('该商品不存在');

        //修改了商品名称,检查商品名称是否重复
        if ($rs->good_name != $data['good_name']) {
            $temp = GoodModel::field('id')
                ->where(['is_del' => CommonModel::$del_normal, 'good_name' => $data['good_name']])
                ->findOrEmpty()
                ->isEmpty();
            if (!$temp) throw new ValidateException('该商品名称重复');
        }

        $res = GoodModel::where(['id' => $data['id']])->save([
            'good_cover_img' => $data['good_cover_img'],
            'good_name' => $data['good_name'],
            'moq' => $data['moq'],
            'step' => $data['step'],
            'price' => $data['price'],
            'good_banner_img' => implode(',', $data['good_banner_img']),
            'good_img' => implode(',', $data['good_img']),
            'good_param' => json_encode($data['good_param'], JSON_UNESCAPED_UNICODE),
            'good_remark' => $data['good_remark'],
            'unit_id' => $data['unit_id'],
            'updaterid' => self::$uid,
            'updater' => self::$uname,
            '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

    {
        $where = [
            ['id', '=', $data['id']],
            ['is_del', '=', CommonModel::$del_normal],
            ['status', '<>', $data['status']],
        ];
        $rs = GoodModel::field('id,status')
            ->where($where)
            ->findOrEmpty()
            ->isEmpty();

        if ($rs) throw new ValidateException('该商品不存在或重复操作');

        $res = GoodModel::where($where)->save($data);

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

    }

    //删除商品
    public static function delete(int $id = 0): Json
    {
        $rs = GoodModel::where(['id' => $id, 'is_del' => CommonModel::$del_normal])
            ->save(['is_del' => CommonModel::$del_deleted]);

        return $rs ? json_show(CommonModel::$success, '商品删除成功') : json_show(CommonModel::$error_param, '商品不存在或重复删除');
    }

}