<?php
/*
 * @Descripttion:
 * @version:
 * @Author: kangkang
 * @Date: 2020-10-13 19:52:37
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-12-07 17:16:18
 */

namespace app\order\controller;

use app\order\model\TbRefund as RefundMOdel;
use app\order\model\User as UserModel;
use app\order\model\UserScore as ScoreModel;
use enum\order\TbRefund as RefundEnum;
use fastphp\base\Controller;

class TbRefund extends Controller
{
    public function refundList()
    {
        $refund = new RefundMOdel;
        $userModel = new UserModel;
        $get_list = $refund->getListPage([], '*', 'Modified desc');
        $user_phone = [];
        $lists = [];
        $list = [];
        foreach ($get_list as $v) {
            $v['status'] = RefundEnum::$refundStatus[$v['status']];
            if (!in_array($v['Phone'], $user_phone)) {
                $user_phone[] = $v['Phone'];
            }
            $lists[] = $v;
        }
        $user_test = $userModel->getListPage("LoginCode in('" . implode("','", $user_phone) . "') OR Phone in('" . implode("','", $user_phone) . "')", 'RestAmount,LoginCode,Phone');

        foreach ($lists as $key => $val) {
            foreach ($user_test as $k => $v) {
                if ($val['Phone'] == $v['LoginCode'] || $val['Phone'] == $v['Phone']) {
                    $val['account'] = $v['RestAmount'];
                    $list[] = $val;
                }
            }
        }
        $count = $refund->getCount();
        $data = [
            'Code' => 10000,
            'count' => $count['count'],
            'data' => $list,
        ];
        echo json_encode($data);
    }

    public function pageList()
    {
        if (!$_GET) {
            die;
        }
        $page = ($_GET['page'] - 1) * 50;
        $refund = new RefundMOdel;
        $userModel = new UserModel;
        $get_list = $refund->getListPage([], '*', 'Modified desc', "$page,50");
        $user_phone = [];
        $lists = [];
        $list = [];
        foreach ($get_list as $v) {
            $v['status'] = RefundEnum::$refundStatus[$v['status']];
            if (!in_array($v['Phone'], $user_phone)) {
                $user_phone[] = $v['Phone'];
            }
            $lists[] = $v;
        }
        $user_test = $userModel->getListPage("LoginCode in('" . implode("','", $user_phone) . "') OR Phone in('" . implode("','", $user_phone) . "')", 'RestAmount,LoginCode,Phone');

        foreach ($lists as $key => $val) {
            foreach ($user_test as $k => $v) {
                if ($val['Phone'] == $v['LoginCode'] || $val['Phone'] == $v['Phone']) {
                    $val['account'] = $v['RestAmount'];
                    $list[] = $val;
                }
            }
        }
        $data = [
            'Code' => 10000,
            'data' => $list,
        ];
        echo json_encode($data);
    }

    //获取记录
    public function search()
    {
        $data = json_decode(file_get_contents("php://input"), true)['data'];
        $refund = new RefundMOdel;
        $userModel = new UserModel;

        $where = [];
        $where_str = '';
        if (!empty($data)) {
            if (!empty($data['Phone'])) {
                $where['Phone'] = ['like', '%' . $data['Phone'] . '%'];
            }
            if (!empty($data['SellerNick'])) {
                $where['SellerNick'] = ['like', '%' . $data['SellerNick'] . '%'];
            }
            if (!empty($data['handle_user'])) {
                $where['handle_user'] = ['like', '%' . $data['handle_user'] . '%'];
            }
            if (!empty($data['Modified']['st'])) {
                $date1 = date('Y-m-d', strtotime($data['Modified']['st']));
                $date2 = date('Y-m-d', strtotime($data['Modified']['et']));
                $where_str = " Modified>='" . $date1 . "' and Modified<='" . $date2 . "' ";
            }
            if ($data['status'] != null) {
                $where['status'] = $data['status'];
            }
        }
        $list = $refund->search($where, '*', 'id desc', '10000', $where_str);
        foreach ($list as &$v) {
            $v['status'] = RefundEnum::$refundStatus[$v['status']];
            $v['account'] = $userModel->getOne(['LoginCode' => $v['Phone']])['RestAmount'];
        }
        $data = [
            'Code' => 10000,
            'count' => isset($count['count']) ? $count['count'] : 0,
            'data' => $list,
        ];
        echo json_encode($data);
    }

    /**
     * @description: 获取点击的那一条数据
     * @param {type}
     * @return {type}
     */
    public function getOneInfo()
    {
        if (!$_GET) {
            die;
        }
        $id = $_GET['id'];
        $refund = new RefundMOdel;
        $where = ['Id' => $id];
        $info = $refund->getOne($where);
        \result($info);
    }

    /**
     * @description: 处理退款
     * @param {type}
     * @return {type}
     *
     */
    public function handle()
    {
        $data = json_decode(file_get_contents("php://input"), true)['row'];
        if($data){
            $id = $data['Id'];
            $user = $this->userinfo;
            $refund = new RefundMOdel;
            $update_data['handle_user'] = $user['LoginName'];

            $refund_info = $refund->getOne(['Id' => $id]);

            $userModel = new UserModel;
            $user_info = $userModel->getOne("LoginCode = '" . $refund_info['Phone'] . "' OR Phone='" . $refund_info['Phone']."'");
            //判断余额是否大于退款金额
            $returnOk = $user_info['RestAmount'] - $refund_info["RefundFee"];
            
            if ($returnOk < 0) {
                \result([], '余额不足', 20000);
            } else {
                $update_data['f_balance'] = $returnOk;
                if ($refund->updateOne(['Id' => $id], $update_data)) {
                    $user_update['RestAmount'] = $returnOk;
                    $fff = $userModel->updateOne("LoginCode = '" . $refund_info['Phone'] . "' OR Phone='" . $refund_info['Phone'] . "'", $user_update);

                    //记录资金明细
                    $score_data = [
                        'UserId' => $user_info['Id'],
                        'ScoreType' => 4,
                        'ScoreTypeName' => '淘宝退款扣除',
                        'ScoreValue' => $refund_info["RefundFee"],
                        'Remark' => $refund_info["Tid"],
                        'UserName' => $refund_info['Phone'],
                        'OperateUserName' => $user['LoginName'],
                        'RestAmount1' => $user_info['RestAmount'],
                        'RestAmount2' => $returnOk,
                        'CreateTime' => date('Y-m-d H:i:s', time()),
                        'UpdateTime' => date('Y-m-d H:i:s', time()),
                        'TenantId' => 0,
                        'DeleteTag' => 0,
                    ];
                    $score = new ScoreModel;
                    $score->add($score_data);
                }
            }

            $return = [
                'Code' => 30000,
                'msg' => '操作成功',
                'balance' => $returnOk,
            ];
            echo json_encode($return);
        }
    }

    /**
     * @description: 导出数据
     * @param {*}
     * @return {*}
     */
    public function export()
    {
        $data = $_GET['data'];
        $refund = new RefundMOdel;
        $userModel = new UserModel;

        $where = [];
        $where_str = '';
        if (!empty($data)) {
            if (!empty($data['Phone'])) {
                $where['Phone'] = ['like', '%' . $data['Phone'] . '%'];
            }
            if (!empty($data['SellerNick'])) {
                $where['SellerNick'] = ['like', '%' . $data['SellerNick'] . '%'];
            }
            if (!empty($data['handle_user'])) {
                $where['handle_user'] = ['like', '%' . $data['handle_user'] . '%'];
            }
            if (!empty($data['Modified']['st'])) {
                $date1 = date('Y-m-d', strtotime($data['Modified']['st']));
                $date2 = date('Y-m-d', strtotime($data['Modified']['et']));
                $where_str = " Modified>='" . $date1 . "' and Modified<='" . $date2 . "' ";
            }
            if (!empty($data['status']) && $data['status'] != null) {
                $where['status'] = $data['status'];
            }
        }
        $list = $refund->search($where, '*', 'id desc', '10000', $where_str);
        foreach ($list as &$v) {
            $v['status'] = RefundEnum::$refundStatus[$v['status']];
            $v['account'] = $userModel->getOne(['LoginCode' => $v['Phone']])['RestAmount'];
        }
        \exportToCsv('test.csv',['id','淘宝id','淘宝会员名','退款金额','子订单编号','交易编号','无关变量','无关变量','产品','申请时间','用户名','处理时间','备注','状态','扣除前余额','处理人','扣除后余额'],$list);
    }

}
