<?php

namespace App\Exports;

use App\Models\Shop;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class ShopExport implements FromCollection,WithHeadings
{

    protected $shops;
    public function __construct($shops)
    {
        $this->shops = $shops;
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $shops = $this->shops;
        $rows = [];
        foreach ($shops as $shop)
        {
            $sku_name ='';
            $freight = '';
            $price = '';
            $nature_str = '';
            if (is_array($shop['sku']) && count($shop['sku'])) {
                foreach ($shop['sku'] as $sku) {
                    $sku_name .= $sku['name'] . "/" . $sku["stock"] . ' | ';
                    if (isset($sku['ship_num'])) {
                        $ready_agent_price = $sku['ready_agent_price']??"无";
                        $freight .= "前{$sku['ship_num']}件 {$sku['ship_price']}元，每增加一件{$sku['ship_each_price']}元，最高{$sku['ship_max_price']}元 | ";
                        $price .= "{$sku["price"]}/{$ready_agent_price}/{$sku['agent_price']}/{$sku['staff_price']}";
                    }
                }
                if (is_array($shop['nature']) && count($shop['nature'])) {
                    foreach ($shop['nature'] as $nature) {
                        if ($nature == Shop::DMANATURE) {
                            $nature_str .= "DMA商品、";
                        } elseif ($nature == Shop::NURTURENATURE) {
                            $nature_str .= "营养品、";
                        } elseif ($nature == Shop::AGENTNATURE) {
                            $nature_str .= "批发商商品、";
                        }
                    }
                }
                $rows[] = ['id' => $shop['id'], 'name' => $shop['icon'], 'title' => $shop['title'], 'nature' => $nature_str, 'goods_price' => $shop['price'], 'sku_name' => $sku_name, "price" => $price, 'freight' => $freight, "created_at" => $shop['created_at']->toDateTimeString()];
            }
        }
        return collect($rows);

    }

    public function headings(): array
    {
        return [
            ['商品ID',"商品图片",'商品名称', '商品标签', '商品价格', '规格名称/库存','客户价/准批发商价/批发商价/员工价','邮费', "创建时间"]
        ];
    }


}
