<?php

namespace Modules\Mall\Http\Controllers\Admin;

use Encore\Admin\Form;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\MessageBag;
use Modules\Mall\Models\Goods;
use Modules\Mall\Models\GoodsSku;

class SkuMultipleController extends Controller
{
    public function index(Content $content, Goods $goods): Content
    {
        return $content
            ->header($goods->name)
            ->description('价格条目')
            ->body($this->form($goods));
    }

    protected function form($goods)
    {
        $form   = new Form(new GoodsSku());
        $groups = $this->attrGroup($goods->specs);
        if (! empty($groups)) {
            foreach ($groups as $key => $group) {
                if ($goods->skus()->count() > 0) {
                    $sku = $goods->skus()->where('unit', $group['id'])->first();
                }
                $form->text('规格'.($key + 1))->disable()->value($group['value']);
                $form->hidden("goods[$key][unit]")->value($group['id']);
                $form->hidden("goods[$key][sku_cost]")->value(0);
//                $form->currency("goods[$key][sku_cost]", '商品成本价')
//                    ->default(0)
//                    ->value($sku->sku_cost ?? 0)
//                    ->required();
                $form->currency("goods[$key][price]", '销售价格')
                    ->default(0)
                    ->value($sku->price ?? 0)
                    ->required();
                $form->image("goods[$key][cover]", '封面图片')
                    ->move('images/'.date('Y/m/d'))
                    ->value($sku->cover ?? '')
                    ->uniqueName()
                    ->removable()
                    ->retainable();
//                $form->currency("goods[$key][score]", '共力值')
//                    ->default(0)
//                    ->value($sku->score ?? 0)
//                    ->required();
                $form->hidden("goods[$key][assets]")->value($sku->assets ?? 0);
                $form->number("goods[$key][stock]", '商品库存')
                    ->default(0)
                    ->value($sku->stock ?? 0)
                    ->min(1)
                    ->required();
                $form->text("goods[$key][weight]", '商品重量')
                    ->default(0)
                    ->setWidth(2)
                    ->value($sku->weight ?? 0)
                    ->required();
                $form->setAction(admin_url('mall/goods/'.$goods->id.'/multiple'));
                $form->divider();
            }
        }
        return $form;
    }

    public function store(Request $request, Goods $goods)
    {
        $data = [];
        foreach ($request->goods as $key => $value) {
//            if ($value['sku_cost'] <= 0) {
//                $error = new MessageBag([
//                    'title'   => '错误提示',
//                    'message' => '规格'.($key + 1).'商品成本价格式不正确',
//                ]);
//                return back()->with(compact('error'));
//            }
            if ($value['price'] <= 0) {
                $error = new MessageBag([
                    'title'   => '错误提示',
                    'message' => '规格'.($key + 1).'销售价格格式不正确',
                ]);
                return back()->with(compact('error'));
            }
            if ($value['stock'] <= 0) {
                $error = new MessageBag([
                    'title'   => '错误提示',
                    'message' => '规格'.($key + 1).'库存必须大于0个',
                ]);
                return back()->with(compact('error'));
            }
            $verify = GoodsSku::verifyPrice($value['sku_cost'], $value['price']);
            if ($verify > 0) {
                $error = new MessageBag([
                    'title'   => '错误提示',
                    'message' => '规格'.($key + 1).'销售价格过低，建议销售价最低为'.$verify,
                ]);
                return back()->with(compact('error'));
            }
            $cover = $value['cover'] ?? '';
            if ($cover) {
                $file           = $cover;
                $value['cover'] = $file->store('images/'.date('Y/m/d'));
            }
            $data[$value['unit']] = $value;
        }
        if ($goods->skus()->count() > 0) {
            foreach ($data as $key => $val) {
                $sku = $goods->skus()->where('unit', $key)->first();
                if ($sku) {
                    $sku->update($val);
                    unset($data[$key]);
                }
            }
            if (count($data) > 0) {
                $goods->skus()->createMany($data);
            }
            return redirect(admin_url('mall/goods'));
        } else {
            $result = $goods->skus()->createMany($data);
            if ($result) {
                return redirect(admin_url('mall/goods'));
            } else {
                $error = new MessageBag([
                    'title'   => '错误提示',
                    'message' => '操作失败',
                ]);
                return back()->with(compact('error'));
            }
        }
    }

    private function attrGroup($specs): array
    {
        if (empty($specs)) {
            return [];
        }
        $data = [];
        foreach ($specs as $key => $spec) {
            foreach ($spec->values as $k => $value) {
                $data[$key][$k] = [
                    'id'    => $value->id,
                    'name'  => $spec->name,
                    'value' => $value->value,
                ];
            }
        }
        $returnData = [];
        if (count($data) > 1) {
            for ($i = 0; $i < count($data) - 1; $i++) {
                if ($i == 0) {
                    foreach ($data[$i] as $value) {
                        $returnData[] = [
                            'id'    => $value['id'],
                            'value' => $value['name'].':'.$value['value'],
                        ];
                    }
                }
                $tempArray = [];
                foreach ($returnData as $value) {
                    foreach ($data[$i + 1] as $val) {
                        $tempArray[] = [
                            'id'    => $value['id'].'|'.$val['id'],
                            'value' => $value['value'].'|'.$val['name'].':'.$val['value'],
                        ];
                    }
                }
                $returnData = $tempArray;
            }
        } else {
            foreach ($data[0] as $value) {
                $returnData[] = [
                    'id'    => $value['id'],
                    'value' => $value['name'].':'.$value['value'],
                ];
            }
            $tempArray = [];
            foreach ($returnData as $value) {
                $tempArray[] = [
                    'id'    => $value['id'],
                    'value' => $value['value'],
                ];
            }
            $returnData = $tempArray;
        }
        return $returnData;
    }

}