<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\shops;


use app\common\model\shops\ShopGoods;
use app\common\logic\BaseLogic;
use app\common\model\shops\ShopGoodSpecsInventory;
use think\facade\Db;


/**
 * ShopGoods逻辑
 * Class ShopGoodsLogic
 * @package app\adminapi\logic\shops
 */
class ShopGoodsLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 11:07
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            if(isset($params['custom_attribute_items']) && !empty($params['custom_attribute_items'])){
                foreach($params['custom_attribute_items'] as &$item){
                    if(intval($item['img_type']) === 0){
                        foreach($item['spec_items'] as $k => $v){
                            unset($item['spec_items'][$k]['spec_img']);
                        }
                    }
                }
            }
            $params['goods_category_id'] = end($params['goods_category_ids']);
            $model = ShopGoods::create([
                'delivery_type' => $params['delivery_type'],
                'shop_goods_type' => $params['shop_goods_type'],
                'goods_category_ids' => $params['goods_category_ids'],
                'goods_category_id' => $params['goods_category_id'],
                'goods_name' => $params['goods_name'],
                'company_name' => $params['company_name'],
                'good_unit' => $params['good_unit'],
                'goods_image' => $params['goods_image'],
                'goods_banners' => !empty( $params['goods_banners']) ? $params['goods_banners'] : null,
                'description' => $params['description'],
                'goods_status' => $params['goods_status'],
                'is_recommend' => $params['is_recommend'],
                'recommend_weight' => $params['recommend_weight'],
                'specs_type' => $params['specs_type'] ?? 1,
                'custom_attribute_items' => $params['specs_type'] ==3 ? $params['custom_attribute_items'] : null,
            ]);
            if(!empty($params['goodSpecsInventory'])){
                $data = [];
                foreach ($params['goodSpecsInventory'] as $item){
                    $val = [];
                    $val['specs'] = $item['specs'];
                    $val['inventory'] = $item['inventory'];
                    $val['remaining_inventory'] = $item['remaining_inventory'];
                    $val['service_total'] = $item['service_total'];
                    $val['service_fee'] = $item['service_fee'];
                    $val['shop_goods_id'] = $model->id;
                    $data[] = $val;
                }
                $model->goodSpecsInventory()->saveAll($data);
            }
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 11:07
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            if(isset($params['custom_attribute_items']) && !empty($params['custom_attribute_items'])){
                foreach($params['custom_attribute_items'] as &$item){
                    if(intval($item['img_type']) === 0){
                        foreach($item['spec_items'] as $k => $v){
                            unset($item['spec_items'][$k]['spec_img']);
                        }
                    }
                }
            }
            ShopGoods::where('id', $params['id'])->update([
                'delivery_type' => $params['delivery_type'],
                'shop_goods_type' => $params['shop_goods_type'],
                'goods_category_ids' => $params['goods_category_ids'],
                'goods_category_id' => $params['goods_category_id'],
                'goods_name' => $params['goods_name'],
                'company_name' => $params['company_name'],
                'goods_image' => $params['goods_image'],
                'goods_banners' => !empty($params['goods_banners']) ? json_encode($params['goods_banners'],true) : null,
                'description' => $params['description'],
                'goods_status' => $params['goods_status'],
                'is_recommend' => $params['is_recommend'],
                'recommend_weight' => $params['recommend_weight'],
                'specs_type' => $params['specs_type'] ?? 1,
                'custom_attribute_items' => $params['specs_type']==3 ? json_encode($params['custom_attribute_items'],true) : null,
            ]);
            $ids = ShopGoodSpecsInventory::where('shop_goods_id',$params['id'])->column('id');
            $saveIds = [];
            if(!empty($ids)){
                $saveIds = array_reverse(array_slice($ids,0,count($params['goodSpecsInventory'])));
                $deleteIds = array_slice($ids,count($params['goodSpecsInventory']));
               ShopGoodSpecsInventory::destroy($deleteIds);
            }
            $model = ShopGoods::find($params['id']);
            $data = [];
            foreach($params['goodSpecsInventory'] as $item){
                $val = [];
                if(!empty($saveIds)){
                    $id = array_pop($saveIds);
                    $val['id'] = $id;
                }
                $val['specs'] = $item['specs'];
                $val['inventory'] = $item['inventory'];
                $val['remaining_inventory'] = $item['remaining_inventory'];
                $val['service_total'] = $item['service_total'];
                $val['service_fee'] = $item['service_fee'];
                $val['shop_goods_id'] = $model->id;
                $data[] = $val;
            }
            $model->goodSpecsInventory()->saveAll($data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/08/04 11:07
     */
    public static function delete(array $params): bool
    {
        ShopGoodSpecsInventory::where('shop_goods_id',$params['id'])->delete();
        return ShopGoods::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/08/04 11:07
     */
    public static function detail($params): array
    {
        return ShopGoods::findOrEmpty($params['id'])->toArray();
    }
}