<?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\BusinessmanService;
use Modules\Jiesuan\Services\CompanyUserMoneyService;
use Modules\Jiesuan\Services\ConstService;
use Modules\User\Http\Controllers\UserTrait;

class FinanceCheckController extends CatchController
{
    use UserTrait;
    use ValidatesRequests;

    /**
     * 列表
     * @param Request $request
     */
    public function list(Request $request) {
        $this->validate($request, [
            'status' => 'required|in:1,2,3,4,5'
        ]);
        $tixianStartAt = $request->input('tixian_start_at');
        $tixianEndAt = $request->input('tixian_end_at');
        $companyUid = $request->input('company_uid');
        $owner_name = $request->input('owner_name');
        $isExport = $request->input('is_export', false);

        $sql = DB::table('tixian_records')
            ->leftJoin('bank_cards','tixian_records.bank_card_id','bank_cards.id')
            ->where('tixian_records.status', $request->input('status'))
            ->when($tixianStartAt, function ($query, $tixianStartAt){
                return $query->where('tixian_records.created_at', '>=', $tixianStartAt);
            })->when($tixianEndAt, function ($query, $tixianEndAt){
                return $query->where('tixian_records.created_at', '<=', $tixianEndAt . ' 23:59:59');
            })->when($owner_name, function ($query, $owner_name) {
                return $query->where('bank_cards.owner_name', 'like', '%'. $owner_name . '%');
            })->when($companyUid, function ($query, $companyUid) {
                return $query->where('tixian_records.company_uid', $companyUid);
            })
            ->select('tixian_records.id', 'tixian_records.company_uid', 'bank_cards.owner_name',
                'tixian_records.status', 'bank_cards.business_id', 'tixian_records.tixian_money', 'tixian_records.created_at','tixian_records.ticket_link',
            'bank_cards.card_no', 'bank_cards.name_of_payee', 'tixian_records.remark', 'tixian_records.updated_at')
        ->orderBy('id', 'desc');
        if($isExport) {
            $result = $sql->get();
        } else {
            $result = $sql->paginate($request->input('limit', 15));
        }
        $businessmans = BusinessmanService::list()->keyBy('id');
        foreach ($result as $item) {
            $item->business_str = $businessmans->get($item->business_id)->username ?? '';
            $item->status_str = ConstService::TIXIAN_CHECK_STATUS[$item->status] ?? '';
        }
        return $result;
    }

    /**
     * 审核
     * @param Request $request
     */
    public function check(Request $request) {
        $this->validate($request, [
            'status' => 'required|in:2,3',
            'id' => 'required',
            'remark' => 'nullable|string|max:140'
        ]);
        $record = DB::table('tixian_records')
            ->where([
                'id' => $request->input('id'),
                'status' => 1
            ])->first();
        if(!$record) {
            CommonBusinessException::throwError(Errors::TIXIAN_RECORD_NOT_EXISTS);
        }
        $before = CompanyUserMoneyService::userMoneyInfo($record->company_uid);
        DB::table('tixian_records')
            ->where([
                'id' => $request->input('id'),
                'status' => 1
            ])->update([
                'status' => $request->input('status'),
                'updated_at' => date('Y-m-d H:i:s'),
                'remark' => $request->input('remark', ''),
            ]);
        $after = CompanyUserMoneyService::userMoneyInfo($record->company_uid);
        if(2 == $request->input('status')) {
            CompanyUserMoneyService::log($record->company_uid, ConstService::MONEY_CHANGE_TYPE_CHECK_FAIL, $before, $after);
        }


        return 'ok';
    }

    /**
     * 打款
     * @param Request $request
     */
    public function remit(Request $request) {
        $this->validate($request, [
            'status' => 'required|in:4,5',
            'id' => 'required',
            'pay_channel' => 'required',
            'pay_no' => 'required_if:status,4',
            'remark' => 'nullable|string|max:256'
        ]);

        $record = DB::table('tixian_records')
            ->where([
                'id' => $request->input('id'),
                'status' => 3
            ])->first();
        if(!$record) {
            CommonBusinessException::throwError(Errors::TIXIAN_RECORD_NOT_EXISTS);
        }
        $before = CompanyUserMoneyService::userMoneyInfo($record->company_uid);
        DB::table('tixian_records')
            ->where([
                'id' => $request->input('id'),
                'status' => 3
            ])->update([
                'updated_at' => date('Y-m-d H:i:s'),
                'status' => $request->input('status'),
                'pay_channel' => $request->input('pay_channel'),
                'pay_no' => $request->input('pay_no', ''),
                'remark' => $request->input('remark', '')
            ]);

        $after = CompanyUserMoneyService::userMoneyInfo($record->company_uid);
        if(4 == $request->input('status')) {
            DB::table('company_user_money')
                ->where(['company_uid' => $record->company_uid])
                ->increment('total_dakuan', $record->tixian_money);
            CompanyUserMoneyService::log($record->company_uid,
                ConstService::MONEY_CHANGE_TYPE_CHECK_AND_DAKUAN_SUCCESS, $before, $after);
        } else {
            CompanyUserMoneyService::log($record->company_uid,
                ConstService::MONEY_CHANGE_TYPE_CHECK_SUCCESS_DAKUAN_FAIL, $before, $after);
        }

        return 'ok';
    }

    /**
     * 商户的账户余额信息
     * @param Request $request
     * @return object|null
     * @throws \Illuminate\Validation\ValidationException
     */
    public function getShanghuAccountInfo(Request $request) {
        $this->validate($request, [
            'company_uid' => 'required'
        ]);

        $accountInfo = CompanyUserMoneyService::userMoneyInfo($request->input('company_uid'));
        $accountInfo->total_jiesuan = bcsub($accountInfo->total_income,  $accountInfo->total_tuikuan, 2);

        return $accountInfo;
    }
}
