<?php

namespace app\api\service\order;

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

/**
 * @package app\api\service\order
 * @class Refund
 * @author xzncit 2024/3/20
 */
class Refund {

    public static function getList($params=[]){
        $array = [
            "total" => 0,
            "list"  => [],
            "size"  => 10
        ];

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

        $condition   = [];
        $condition[] = ["order_refunds.user_id","=",UsersService::get("id",0)];
        $page        = $params["page"]??1;
        $count       = OrderRefundsModel::withSearch(...$fields)->withJoin("orders")->where($condition)->count();
        $array["list"] = OrderRefundsModel::withSearch(...$fields)->withJoin("orders")->where($condition)->order('order_refunds.id','desc')->page($page,$array["size"])->select()->map(function($item){
            $value  = $item["orders"];
            $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),
                    "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),
                "spec"              => $spec,
                "sell_price"        => $res["sell_price"],
                "total_price"       => $res["total_price"],
                "goods_total_nums"  => $res["goods_total_nums"]
            ];
        });

        $array["refund"] = OrderRefundsModel::field("audit_status,refuse_desc")->where("order_id",$array["id"])->findOrEmpty()->toArray();
        if(!empty($array["refund"])){
            $array["refund"]["text"] = OrderRefundsEnum::auditStatus($array["refund"]["audit_status"]);
        }else{
            $array["refund"]["audit_status"] = 0;
        }

        return $array;
    }

    /**
     * 提交退款
     * @param $params
     * @return true
     * @throws BaseException
     */
    public static function save($params=[]){
        $id = intval($params["id"]??0);
        $message = trim($params["message"]??"");

        if(empty($message)){
            throw new BaseException("请填写退款说明",0);
        }

        $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"] == 3){
            throw new BaseException("您的订单已申请退款，请勿重复申请",0);
        }

        if($order["active"] == 4){
            throw new BaseException("您的订单退款已完成，请勿重复申请",0);
        }

        if($order["active"] == 5 && $order["refund_status"] == 1){
            OrderService::refund($id,2,["apply_desc"=>$message]);
        }

        return true;
    }

}