<?php
// +----------------------------------------------------------------------
// | A3Mall
// +----------------------------------------------------------------------
// | Copyright (c) 2020 http://www.a3-mall.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xzncit <158373108@qq.com>
// +----------------------------------------------------------------------

namespace app\adminapi\service\order;

use app\adminapi\model\order\OrderRefunds as OrderRefundsModel;
use app\adminapi\model\order\Order as OrderModel;
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\order\OrderGoods as OrderGoodsModel;
use app\common\service\order\Order as OrderService;

/**
 * @package app\adminapi\service\order
 * @class Refund
 * @author xzncit 2024-02-27
 */
class Refund {

    /**
     * 列表
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getList($params=[]){
        $array           = [];
        $fields          = ["type,status,order_no,time",[
            "type"       => $params["type"]??'0',
            "status"     => $params["status"]??'0',
            "order_no"   => $params["order_no"]??"",
            "time"       => $params["time"]??""
        ]];

        $array["total"]  = OrderRefundsModel::withSearch(...$fields)->withJoin("orders")->count();
        $array["list"]   = OrderRefundsModel::withSearch(...$fields)->withJoin("orders")->order("id","desc")->page($params["current"]??1,$params["size"]??10)->select()->map(function ($res){
            $res["username"] = getUserName($res["user_id"]);
            $res["goods"]    = OrderGoodsModel::where("id","in",$res["order_goods_list"])->select()->map(function ($value){
                $value["photo"] = Image::thumb(GoodsModel::where("id",$value["goods_id"])->value("photo",""));
                $value["spec"]  = !empty($value["goods_array"]) ? json_decode($value["goods_array"],true) : ["name"=>"","value"=>""];
                return $value;
            });

            $order                          = $res["orders"];
            $res["real_freight"]            = $order["real_freight"];
            $res["real_amount"]             = $order["real_amount"];
            $res["order_amount"]            = $order["order_amount"];
            $res["refund_amount"]           = $res["order_amount"];
            $res["order_message"]           = $order["message"];
            $res["order_remarks"]           = $order["remarks"];
            $res["order_create_time"]       = $order["create_time"];
            $res["order_type"]              = OrderEnum::type($order["type"]);
            $res["refund_audit_status"]     = OrderRefundsEnum::auditStatus($res["audit_status"]);
            $res["refund_is_user_send"]     = OrderRefundsEnum::isUserSend($res["is_user_send"]);
            $res["refund_type"]             = OrderRefundsEnum::type($res["type"]);
            $res["refund_is_receipt"]       = OrderRefundsEnum::isReceipt($res["is_receipt"]);
            $res["refund_status"]           = OrderRefundsEnum::status($res["status"]);
            return $res;
        });

        return $array;
    }

    /**
     * @param $id
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function detail($id){
        $row = OrderModel::with(["payment","delivery","freight"])->where("id",$id)->find();
        if(empty($row)){
            throw new \Exception("您要查找的订单不存在",0);
        }

        $refund = OrderRefundsModel::where("order_id",$id)->findOrEmpty()->toArray();

        $row["username"] = getUserName($row["user_id"]);
        $row["goods"] = OrderGoodsModel::where("order_id",$row["id"])->select()->map(function ($value){
            $value["photo"] = Image::thumb(GoodsModel::where("id",$value["goods_id"])->value("photo",""));
            $value["spec"]  = !empty($value["goods_array"]) ? json_decode($value["goods_array"],true) : ["name"=>"","value"=>""];
            return $value;
        });

        $row["apply_desc"]          = $refund["apply_desc"];
        $row["refund_order_amount"] = $refund["order_amount"];
        $row["active"]              = OrderEnum::active($row);
        $row["text"]                = OrderEnum::activeText($row["active"]);
        $row["order_type"]          = OrderEnum::type($row["type"]);
        $row["transaction_status"]  = OrderEnum::status($row["status"]);
        return $row;
    }

    public static function save($params=[]){
        $id            = intval($params["order_id"]??0);
        $status        = intval($params["status"]??0);
        $order_amount  = trim($params["order_amount"]??0);
        $refuse_desc   = trim($params["refuse_desc"]??"");
        $row = OrderModel::with(["payment","delivery","freight"])->where("id",$id)->find();
        if(empty($row)){
            throw new \Exception("您要查找的订单不存在",0);
        }

        if(!in_array($status,[2,3])){
            throw new BaseException("请选择退款类型",0);
        }

        if($status == 3){
            if(empty($refuse_desc)){
                throw new BaseException("请填写拒绝原因",0);
            }

            OrderRefundsModel::where("order_id",$row["id"])->save([
                "audit_status"  => $status,
                "refuse_desc"   => $refuse_desc,
                "update_time"   => time()
            ]);

            return true;
        }

        if(empty($order_amount)){
            throw new BaseException("请填写退款金额",0);
        }else if(!is_numeric($order_amount)){
            throw new BaseException("您填写的金额不合法",0);
        }

        if($order_amount > $row["order_amount"]){
            throw new BaseException("退款金额不能大于订单金额",0);
        }

        OrderRefundsModel::where("order_id",$row["id"])->save([
            "audit_status"  => $status,
            "order_amount"  => $order_amount,
            "update_time"   => time()
        ]);

        OrderService::refund($row["id"]);
        return true;
    }

}