<?php

use Api\PhpUtils\Log\FileLog;
use App\Base\Cli;
use App\Models\marketing\mysql\ColonelDistributorPayInfo;
use App\Exception\custom\InterfaceException;
use Api\PhpUtils\Http\HttpUtil;

/**
 * php public/cli.php colonelwallet index
 */
class ColonelwalletController extends Cli
{
    public function indexAction()
    {
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $payInfoList = $this->getPayInfo($yesterday);
        if (!empty($payInfoList)) {
            if ($this->toWallet($payInfoList)) {
                if ($this->deductingInventory($payInfoList)) {
                    $this->handlePayInfoStatus(array_column($payInfoList, 'colonel_distributor_pay_info_id'));
                }
            }
        }
    }

    /**
     * colonel_distributor_pay_info 数据
     * @param $date
     * @return array
     */
    public function getPayInfo($date)
    {
        $list = ColonelDistributorPayInfo::select("*", ["date" => $date,'status' => ColonelDistributorPayInfo::STATUS_NOT_USE], []);
        $data = [];
        if (!empty($list)) {
            foreach ($list as $item) {
                //去重
                $key = $item["colonel_user_id"].$item["date"].$item["type"].$item["finish_num"];
                $data[$key] = $item;
            }
            $data = array_values($data);
        }
        return $data;
    }

    /**
     * 写入钱包
     */
    public function toWallet($payInfoList)
    {
        $url = config('interface', 'wallet.account.transfer');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }
        $data = [];
        foreach ($payInfoList as $payInfo) {
            if ($payInfo["type"] == ColonelDistributorPayInfo::TYPE_NEW_USER) {
                $desc = "邀请新用户（".$payInfo["invite_user_nick"]."）完成下单奖励";
            }
            if ($payInfo["type"] == ColonelDistributorPayInfo::TYPE_FINISH_TARGET) {
                $desc = "完成".$payInfo["finish_num"]."单用户下单奖励";
            }
            $tmp = [];
            $tmp["user_id"] = $payInfo["colonel_user_id"];
            $tmp["service_name"] = 11; //服务名字，10生活圈优惠券，11营销活动
            $tmp["source_name"] = 1; //使用方名，1生活圈，2主端
            $tmp["third_order_id"] = $payInfo["colonel_distributor_pay_info_id"];
            $tmp["third_order_id_type"] = $payInfo["type"];
            $tmp["third_order_desc"] = $desc;
            $tmp["amount"] = $payInfo["reward"];
            $tmp["extra"] = $payInfo;
            $data[] = $tmp;
        }

        $res = HttpUtil::post($url, ["list" => $data]);
        if ($res['code'] == 0 && isset($res['response']["result"])) {
            $date = date("Y-m-d H:i:s");
            FileLog::info("colonel_distributor_to_wallet", $date." 写入钱包成功");
            return true;
        } else {
            $msg = json_encode(["list" => $data]);
            FileLog::error("colonel_distributor_to_wallet", $msg, null, 'bp-server@yidian-inc.com');
            return false;
        }
    }

    /**
     * 资金池授予用户奖励
     */
    public function deductingInventory($payInfoList)
    {
        $url = config('interface', 'coupon.capitalpool.grant_user_amount');
        if (empty($url)) {
            throw new InterfaceException(['cus' => 0]);
        }

        $data["capital_pool_id"] = 2;
        foreach ($payInfoList as $payInfo) {
            if ($payInfo["type"] == ColonelDistributorPayInfo::TYPE_NEW_USER) {
                $desc = "邀请新用户（".$payInfo["invite_user_nick"]."）完成下单奖励";
            }
            if ($payInfo["type"] == ColonelDistributorPayInfo::TYPE_FINISH_TARGET) {
                $desc = "完成".$payInfo["finish_num"]."单用户下单奖励";
            }
            $tmp = [];
            $tmp["op"] = 200; //200：团长奖励
            $tmp["user_id"] = $payInfo["colonel_user_id"];
            $tmp["amount"] = $payInfo["reward"];
            $tmp["third_order_id"] = $payInfo["colonel_distributor_pay_info_id"];
            $tmp["third_order_id_type"] = $payInfo["type"];
            $tmp["third_order_desc"] = $desc;
            $data["body"][] = $tmp;
        }
        $res = HttpUtil::post($url, $data, 100000, 3);
        if ($res['code'] == 0 && isset($res['response']["result"])) {
            $date = date("Y-m-d H:i:s");
            FileLog::info("colonel_distributor_deducting_inventory", $date." 资金池授予用户奖励成功");
            return true;
        } else {
            $msg = json_encode(["list" => $data]);
            FileLog::error("colonel_distributor_deducting_inventory", $msg, null, 'bp-server@yidian-inc.com');
            return false;
        }
    }

    /**
     * 修改状态
     */
    public function handlePayInfoStatus(array $payInfoIds)
    {
        return ColonelDistributorPayInfo::updateRecord(['status' => ColonelDistributorPayInfo::STATUS_USE], ['id' => $payInfoIds]);
    }
}
