<?php

namespace Modules\Jiesuan\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Common\Errors\Errors;
use Modules\Common\Exceptions\CommonBusinessException;
use Modules\Jiesuan\Services\CompanyUserMoneyService;
use Modules\Jiesuan\Services\ConstService;
use Modules\User\Http\Controllers\UserTrait;

class JiesuanController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;

    /**
     * 结算记录
     * @param Request $request
     */
    public function list(Request $request) {
        $jiesuanDateStartAt = $request->input('jiesuan_date_start_at');
        $jiesuanDateEndAt = $request->input('jiesuan_date_end_at');
        $isExport = $request->input('is_export', 0);
        $sql = DB::table('jiesuan_records')
            ->where([
                'company_uid' => $this->getCompanyUid($request),
            ])->when($jiesuanDateStartAt, function ($query, $jiesuanDateStartAt) {
                return $query->where('jiesuan_date', '>=', $jiesuanDateStartAt);
            })
            ->when($jiesuanDateEndAt, function ($query, $jiesuanDateEndAt) {
                return $query->where('jiesuan_date', '<=', $jiesuanDateEndAt . ' 23:59:59');
            })
            ->orderBy('jiesuan_date', 'desc')
            ->select('id', 'jiesuan_date', 'charge_money', 'tuikuan_money', 'share_rate', 'jiesuan_money', 'company_uid');
        if($isExport) {
            $results = $sql->get();
        } else {
            $results = $sql->paginate($request->input('limit', 15));
        }

        foreach ($results as $item) {
            $item->share_rate .= '%';
        }

        return $results;
    }

    /**
     * 账户金额详情
     * @param Request $request
     */
    public function accountInfo(Request $request) {
        $company_uid = $this->getLoginUserId();
        return CompanyUserMoneyService::userMoneyInfo($company_uid);
    }

    /**
     * 申请提现
     * @param Request $request
     */
    public function tixian(Request $request) {
        $this->validate($request, [
            'bank_card_id' => 'required',
            'tixian_money' => 'required|numeric|min:500'
        ]);
        $company_uid = $this->getLoginUserId();
        $now = date('Y-m-d H:i:s');

        if(DB::table('tixian_records')->where(['company_uid' => $company_uid])
            ->where('created_at', '>=', date('Y-m-d'))
            ->where('created_at', '<=', $now)
            ->exists()) {
            CommonBusinessException::throwError(Errors::TIXIAN_ONLY_ONCE_EVERY_DAY);
        }
        $tixianMoney = $request->input('tixian_money');
        $userMoneyInfo = CompanyUserMoneyService::userMoneyInfo($company_uid);
        if($tixianMoney > $userMoneyInfo->yue_money) {
            CommonBusinessException::throwError(Errors::TIXIAN_YUE_BUZU);
        }
        $bank_card_id = $request->input('bank_card_id');
        // $bankCard = DB::table('bank_cards')->where(['id' => $bank_card_id, 'status' => 2])->first();
        $bankCard = DB::table('bank_cards')->where(['id' => $bank_card_id])->where('status','>',0)->first();
        if(!$bankCard) {
            CommonBusinessException::throwError(Errors::BANK_CARD_STATUS_ERROR);
        }
        DB::table('tixian_records')
            ->insert([
                'tixian_money' => $tixianMoney,
                'company_uid' => $company_uid,
                'company_name' => $bankCard->owner_name,
                'bank_card_id' => $bank_card_id,
                'card_no' => $bankCard->card_no,
                'name_of_payee' => $bankCard->name_of_payee,
                'status' => 1,
                'bank_name' => $bankCard->bank_name,
                'sub_bank_name' => $bankCard->sub_bank_name,
                'created_at' => $now,
                'updated_at' => $now,
            ]);
        $afterUserMoneyInfo = CompanyUserMoneyService::userMoneyInfo($company_uid);
        CompanyUserMoneyService::log($company_uid, ConstService::MONEY_CHANGE_TYPE_USER_TIXIAN, $userMoneyInfo, $afterUserMoneyInfo);
    }

    /**
     * 提现记录
     * @param Request $request
     */
    public function listTixian(Request $request) {
        $company_uid = $this->getCompanyUid($request);
        $this->validate($request, [
            'status' => 'nullable|integer|in:1,2,3,4,5'
        ]);
        $status = $request->input('status');
        $isExport = $request->input('is_export');
        $tixianStartAt = $request->input('tixian_start_at');
        $tixianEndAt = $request->input('tixian_end_at');
        $sql = DB::table('tixian_records')
            ->where([
                'company_uid' => $company_uid,
            ])->when($status, function ($query, $status){
                return $query->where('status', $status);
            })->when($tixianStartAt, function ($query, $tixianStartAt) {
                return $query->where('created_at', '>=', $tixianStartAt);
            })->when($tixianEndAt, function ($query, $tixianEndAt) {
                return $query->where('created_at', '<=', $tixianEndAt. ' 23:59:59');
            })
            ->orderBy('id', 'desc');
        if($isExport) {
            $result = $sql->get();
        } else {
            $result = $sql->paginate($request->input('limit', 15));
        }
        foreach ($result as $item) {
            $item->status_str = ConstService::TIXIAN_CHECK_STATUS[$item->status] ?? '';
        }
        return $result;
    }

    private function getCompanyUid(Request $request) {
        if($this->isCompanyManager()) {
            return $this->getLoginUserId();
        } else {
            return $request->input('company_uid');
        }
    }


    public function updateTicket(Request $request,$id){
        $ticket = $request->post('ticket');
        if(empty($ticket)){
            CommonBusinessException::throwError(Errors::PARAM_EMPTY);
        }
        DB::table('tixian_records')->where('id',$id)->update([
            'ticket_link'=>$ticket
        ]);
        return [];
    } 

}
