<?php

namespace app\queue\redis;

use app\extra\service\saas\OrderService;
use app\model\system\SystemExport;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Webman\RedisQueue\Consumer;

class ExportOrder implements Consumer
{

    public $queue = "export-order";

    public $connection = "default";


    /**
     * @param $data
     * @return bool
     */
    public function consume($data): bool
    {
        try {
            echo getDateFull()."===导出订单\n";
            $order = (new OrderService)->getListAll($data['param']);
            if (empty($order))
            {
                (new SystemExport)->where("id",$data['logId'])->save(['status' => 2]);
                return true;
            }
            $title = ["订单编号","所属门店","订单类型","商品ID","商品名称","规格","订单金额","收件人","收件电话","收件地址","券码"];
            $titCol = 'A';
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            foreach($title as $k=>$v){
                $sheet->setCellValue($titCol."1",$v);
                $titCol ++;
            }
            $row = 2;
            foreach ($order as $item){
                $dataCol = "A";
                $newData = [
                    "order_id"      => (string) $item['order_id'], // 余额
                    "store"         => $item['store']['store_name']??'-',
                    "type"          => $item['service_type']==1?'预约':'快递',
                    "out_id"        => $item['product_id']??'-',
                    "product_name"  => $item['product_name']??'-',
                    "sku"           => $item['sku']??'-',
                    "order_amount"  => "¥".$item['parent']['order_amount']??'-',
                    "username"      => $item['username']??'-',
                    "mobile"        => $item['mobile']??'-',
                    "address"       => $item['region'].$item['address'],
                    "certificate"   => $item['certificate_id']??'-'
                ];
                foreach ($newData as $value) {
                    $sheet->setCellValue($dataCol . $row, ' '.$value);
                    $dataCol++;
                }
                $row++;
            }
            $write = new Xlsx($spreadsheet);
            $pathName = public_path().DIRECTORY_SEPARATOR."logs".DIRECTORY_SEPARATOR.$data['param']['fileName'];
            (new SystemExport)->where("id",$data['logId'])->update([
                "down_url"  => "https://file.jsshuita.com.cn/logs/".$data['param']['fileName'],
                "status"    => 1
            ]);
            $write->save($pathName);
            return true;
        } catch (\Throwable $throwable) {
            echo getDateFull()."导出文件报错\n";
            echo $throwable->getMessage()."\n";
            echo $throwable->getFile()."\n";
            echo $throwable->getLine()."\n";
            return true;
        }
    }

}