<?php
/**
 * ===========================================================================
 * Veitool 快捷开发框架系统
 * Author: Niaho 26843818@qq.com
 * Copyright (c)2019-2025 www.veitool.com All rights reserved.
 * Licensed: 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * ---------------------------------------------------------------------------
 */

namespace app\admin\controller\caiwu;

use app\admin\controller\AdminBase;
use app\event\PhpOffice;
use app\model\project\Mail;
use think\App;
use think\facade\Db;
use app\model\project\UserWithdrawal;
use app\model\project\UserMoneyLog;
use app\model\project\User;

/**
 * 后台主控制器
 */
class Withdrawal extends AdminBase
{

    protected $withdrawal;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->withdrawal = new UserWithdrawal();
    }

    // 列表
    public function index(string $do = '')
    {

        $limit = 10;
        if ($do == 'json') {

            $post = input();
            $post['limit'] = isset($post['limit']) ? $post['limit'] : $limit;
            $map = [];
            $hasmap = [];
            if (isset($post['kw']) && !empty($post['kw'])) {
                $map[] = ['sn', 'like', '%' . $post['kw'] . '%'];
            }
            if (isset($post['sh_status']) && $post['sh_status'] > -1) {
                $map[] = ['sh_status', '=', $post['sh_status']];
            }
            if (isset($post['dk_status']) && $post['dk_status'] > -1) {
                $map[] = ['dk_status', '=', $post['dk_status']];
            }
            if (isset($post['user']) && !empty($post['user'])) {
                $hasmap[] = ['username|mobile', 'like', '%' . $post['user'] . '%'];
            }

            $list = $this->withdrawal->where($map)->hasWhere('getuserdata', $hasmap)->with(['getuserdata'])->append(['sh_status_text', 'dk_status_text'])->order('createtime desc')->paginate($post['limit']);
            return $this->returnMsg($list);
        }
        $this->assign('limit', $limit);
        return $this->fetch('', '', false);
    }


    public function del()
    {
        $post = input();
//        $ids = is_array($post['id']) ? implode(',', $post['id']) : $post['id'];
        if ($this->withdrawal->destroy($post['id'])) {
            return $this->returnMsg("删除成功", 1);
        } else {
            return $this->returnMsg("删除失败");
        }
    }


    //审核
    public function shenhewithdrawal()
    {
        $post = input();
        try {
            Db::startTrans();

            $txinfo = $this->withdrawal->where('id', $post['id'])->lock(true)->find();
            if ($txinfo['sh_status'] != 0) {

                throw new \Exception('记录已审核');
            }
            $errordesc = '';
            $shstatus = 2;
            if ($post['shstatus'] == 1) {
                if (empty($post['errordesc'])) {
//                    return $this->returnMsg("请输入失败原因");
                    throw new \Exception('请输入失败原因');
                }
                $errordesc = $post['errordesc'];
                $shstatus = 1;

                //增加记录
                $usermoney = User::where(['id' => $txinfo['user_id']])->value('money');
                UserMoneyLog::addUserMoneyLog($txinfo['user_id'], $txinfo['tx_money'], $usermoney, 1, '审核驳回：' . $errordesc, $txinfo['id']);
                //退回余额到用户
                $res = User::where('id', $txinfo['user_id'])->setInc('money', $txinfo['tx_money']);
                if(!$res){
                    Db::rollback();
                    throw new \Exception('余额变动失败');
                }

            }
            $updatedata['sh_status'] = $shstatus;
            $updatedata['sh_status_desc'] = $errordesc;
//            $this->withdrawal->where('id', $post['id'])->update($updatedata);
            $txinfo->save($updatedata);
            Db::commit();
            return $this->returnMsg("操作成功", 1);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnMsg($e->getMessage());
        }


    }

    //打款
    public function dakuanwithdrawal()
    {
        $post = input();

        try {
            Db::startTrans();

            $txinfo = $this->withdrawal->lock(true)->find($post['id']);
            if ($txinfo['sh_status'] != 2) {

                throw new \Exception('请先审核再打款');
            }
            if ($txinfo['dk_status'] > 1) {

                throw new \Exception('记录已处理,请不要重复处理');
            }
            $errordesc = '';
            $shstatus = 3;
            if ($post['shstatus'] == 2) {
                if (empty($post['errordesc'])) {
                    throw new \Exception('请输入失败原因');
                }
                $errordesc = $post['errordesc'];
                $shstatus = 2;

                //增加记录
                $usermoney = User::where(['id' => $txinfo['user_id']])->value('money');
                UserMoneyLog::addUserMoneyLog($txinfo['user_id'], $txinfo['tx_money'], $usermoney, 1, '打款驳回：' . $errordesc, $txinfo['id']);
                //退回余额到用户
                $res = User::where('id', $txinfo['user_id'])->setInc('money', $txinfo['tx_money']);
                if(!$res){
                    Db::rollback();
                    throw new \Exception('余额变动失败');
                }
                Mail::createmail($txinfo['user_id'], "您申请提现【" . $txinfo['sn']. "】打款失败 - " . $errordesc);
            }else{
                Mail::createmail($txinfo['user_id'], "您申请提现:【" . $txinfo['sn'] . "】已通过打款请注意查收");
            }

            $updatedata['dk_status'] = $shstatus;
            $updatedata['dk_status_desc'] = $errordesc;
            $updatedata['dk_time'] = time();
            $txinfo->save($updatedata);
            Db::commit();
            return $this->returnMsg("操作成功", 1);
        } catch (\Exception $e) {
            Db::rollback();
            return $this->returnMsg($e->getMessage());
        }

    }

    //导出excel
    public function excelwithdrawal()
    {
        $post = input();
        $map = [];
        $hasmap = [];
        if (isset($post['kw']) && !empty($post['kw'])) {
            $map[] = ['sn', 'like', '%' . $post['kw'] . '%'];
        }
        if (isset($post['sh_status']) && $post['sh_status'] > -1) {
            $map[] = ['sh_status', '=', $post['sh_status']];
        }
        if (isset($post['dk_status']) && $post['dk_status'] > -1) {
            $map[] = ['dk_status', '=', $post['dk_status']];
        }
        if (isset($post['user']) && !empty($post['user'])) {
            $hasmap[] = ['username|mobile', 'like', '%' . $post['user'] . '%'];
        }
        if (isset($post['ids']) && $post['ids']) {
            $map[] = ['user_withdrawal.id', 'in', $post['ids']];
        }

        try {
            $list = $this->withdrawal->where($map)->hasWhere('getuserdata', $hasmap)->with(['getuserdata'])->append(['sh_status_text', 'dk_status_text'])->order('createtime desc')->select()->toArray();
            if (empty($list)) {
                throw new \Exception('没有数据');
            }
            $exceldata[] = ['提现单号', '用户名', '用户手机', '提现金额', '提现手续费', '实际到账金额', '提现账号', '审核状态', '打款状态', '提现时间', '打款时间'];
            foreach ($list as $k => $v) {

                $exceldata[] = [
                    $v['sn'],
                    $v['getuserdata']['username'],
                    $v['getuserdata']['mobile'],
                    $v['tx_money'],
                    $v['tx_commission'],
                    $v['tx_sj_money'],
                    $v['account'],
                    $v['sh_status_text'],
                    $v['dk_status_text'],
                    $v['createtime'],
                    $v['dk_time'] ? date('Y-m-d H:i:s', $v['dk_time']) : '',
                ];
            }
            $excelid = PhpOffice::exportexcel($exceldata, '提现导出');
            $data['url'] = '/admin/caiwu.withdrawal/downloadfile?excel=1&fileid=' . $excelid;
            return $this->returnMsg('success', 1, $data);
        } catch (\Exception $e) {
            return $this->returnMsg($e->getMessage());
        }

    }
}