<?php

namespace app\api\service\order;

use app\common\enum\Order as OrderEnum;
use app\common\library\utils\Image;
use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\Spec as SpecModel;
use app\api\model\order\Order as OrderModel;
use app\common\model\order\OrderGoods as OrderGoodsModel;
use app\common\model\order\OrderAddress as OrderAddressModel;
use app\common\exception\BaseException;
use app\common\service\Users as UsersService;
use app\common\service\order\Order as OrderService;
use app\common\service\Express as ExpressService;

/**
 * @package app\api\service\order
 * @class Order
 * @author xzncit 2024/3/18
 */
class Order {

    /**
     * 列表
     * @param array $params
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

        $fields = ["type",[
            "type" => trim($params["type"]??'all')
        ]];

        $condition = [];
        $condition[] = ["user_id","=",UsersService::get("id",0)];
        $page  = $params["page"]??1;
        $count = OrderModel::withSearch(...$fields)->where($condition)->count();
        $array["list"] = OrderModel::withSearch(...$fields)->where($condition)->order('id','desc')->page($page,$array["size"])->select()->map(function($value){
            $active = OrderEnum::active($value);
            $result = [
                "id"            => $value["id"],
                "active"        => $active,
                "text"          => OrderEnum::activeText($active),
                "order_amount"  => $value["order_amount"],
                "create_time"   => date("Y-m-d H:i:s",$value["create_time"])
            ];

            $result["goods"] = OrderGoodsModel::where("order_id",$value["id"])->select()->map(function($res){
                $array = json_decode($res["goods_array"],true);
                $spec  = SpecModel::getSpecInfo($array["value"]??"");
                $photo = GoodsModel::where("id",$res["goods_id"])->value("photo","");
                return [
                    "type"              => (in_array($res["order_type"],[1,2]) ? 1 : 2),
                    "goods_name"        => $res["goods_name"],
                    "thumb_image"       => Image::thumb($photo,["prefix"=>"medium"]),
                    "spec"              => $spec,
                    "sell_price"        => $res["sell_price"],
                    "total_price"       => $res["total_price"],
                    "goods_total_nums"  => $res["goods_total_nums"]
                ];
            });

            return $result;
        });

        $array["total"] = ceil($count / $array["size"]);
        if($array["total"] == $page -1){
            throw new BaseException("没有数据了哦！",-1,$array);
        }

        return $array;
    }

    /**
     * 详情
     * @param $id
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $order = OrderModel::where(["user_id"=>UsersService::get("id"),"id"=>$id])->findOrEmpty()->toArray();
        if(empty($order)){
            throw new BaseException("订单不存在",0);
        }

        $array = [];
        $array["id"]            = $order["id"];
        $array["order_no"]      = $order["order_no"];
        $array["express_name"]  = $order["express_name"];
        $array["express_no"]    = $order["express_no"];
        $array["real_freight"]  = $order["real_freight"];
        $array["real_amount"]   = $order["real_amount"];
        $array["order_amount"]  = $order["order_amount"];
        $array["active"]        = OrderEnum::active($order);
        $array["text"]          = OrderEnum::activeText($array["active"]);
        $array["create_time"]   = date("Y-m-d H:i:s",$order["create_time"]);
        $array["send_time"]     = $order["send_time"] > 0 ? date("Y-m-d H:i:s",$order["send_time"]) : '';
        $array["message"]       = $order["message"];

        $array["goods"] = OrderGoodsModel::where("order_id",$array["id"])->select()->map(function ($res){
            $array = json_decode($res["goods_array"],true);
            $spec  = SpecModel::getSpecInfo($array["value"]??"");
            $photo = GoodsModel::where("id",$res["goods_id"])->value("photo","");
            return [
                "type"              => (in_array($res["order_type"],[1,2]) ? 1 : 2),
                "goods_name"        => $res["goods_name"],
                "photo"             => Image::thumb($photo,["prefix"=>"medium"]),
                "spec"              => $spec,
                "sell_price"        => $res["sell_price"],
                "total_price"       => $res["total_price"],
                "goods_total_nums"  => $res["goods_total_nums"]
            ];
        });

        $address = OrderAddressModel::where("order_id",$order["id"])->find();
        $array["address"]["name"]    = $address["accept_name"];
        $array["address"]["mobile"]  = $address["mobile"];
        $array["address"]["address"] = implode(",",[$address["province"],$address["city"],$address["area"]]) . ' ' . $address["address"];
        return $array;
    }

    public static function delivery($id){
        OrderService::delivery($id);
        return true;
    }

    /**
     * 取消订单
     * @param $id
     * @return true
     * @throws BaseException
     */
    public static function cancel($id){
        $order = OrderModel::where(["id"=>$id,"user_id"=>UsersService::get("id",0)])->findOrEmpty()->toArray();
        if(empty($order)){
            throw new BaseException("您要操作的订单不存在",0);
        }

        $order["active"] = OrderEnum::active($order);
        if($order["active"] == 2 && $order["refund_status"] == 1){
            OrderService::refund($id);
        }

        return true;
    }

    /**
     * 物流信息
     * @param $id
     * @return array
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function express($id){
        $order = OrderModel::where(["id"=>$id,"user_id"=>UsersService::get("id",0)])->findOrEmpty()->toArray();
        if(empty($order)){
            throw new BaseException("您要操作的订单不存在",0);
        }

        $order["active"] = OrderEnum::active($order);
        if(!in_array($order["active"],[5,6,7])){
            throw new BaseException("该订单不允许执行此操作",0);
        }

        return ExpressService::query($id);
    }

}