<?php

namespace app\admin\controller\company;

use app\admin\controller\AuthController;

use crmeb\services\{JsonService, JsonService as Json, UtilService as Util, FormBuilder as Form, UtilService};
use crmeb\traits\CurdControllerTrait;
use think\facade\Route as Url;
use app\admin\model\system\{StoreBill, StoreExtract, SystemAttachment, ShippingTemplates, SystemStore};


/**
 * 产品管理
 * Class StoreProduct
 * @package app\admin\controller\store
 */
class Finance extends AuthController
{

    use CurdControllerTrait;

    protected $store;

    protected $main_where = [];

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $store_id = $this->adminInfo['store_id'];
        $this->store = SystemStore::where('id', $store_id)->find();
        if ($this->store && $this->store['is_triple']) {
            $this->main_where['store_id'] = $store_id;
        }
    }

    /**
     * 显示资金记录
     */
    public function index()
    {
        $list = StoreBill::where($this->main_where)
            ->field(['title', 'type'])
            ->group('type')
            ->distinct(true)
            ->select()
            ->toArray();
        if ($this->adminInfo['store_id'] > 0) {
            $balance = SystemStore::where('id', $this->adminInfo['store_id'])->value('money');
        }
        $this->assign('selectList', $list);
        $this->assign('balance', $balance ?? 0);
        return $this->fetch();
    }

    /**
     * 显示资金记录ajax列表
     */
    public function billlist()
    {
        $where = Util::getMore([
            ['start_time', ''],
            ['end_time', ''],
            ['nickname', ''],
            ['limit', 20],
            ['page', 1],
            ['type', ''],
        ]);
        $where = array_merge($where, $this->main_where);
        Json::successlayui(StoreBill::getBillList($where));
    }

    /**
     * 添加/修改分组页面
     * @param int $id
     * @return string
     */
    public function extract($type = 'alipay')
    {
        $store_info = SystemStore::where('id', $this->adminInfo['store_id'])->find();
        if (!$store_info) $this->failed('门店不存在');
        $f = array();
        $f[] = Form::number('money', '提现金额', '')->step(0.01)->max($store_info['money'])->min(0)->required();
        $f[] = Form::hidden('extract_type', $type);
        switch ($type) {
            case 'alipay':
                $f[] = Form::input('name', '姓名')->required();
                $f[] = Form::input('alipay_code', '支付宝账号')->required();
                break;
            case 'bank':
                $f[] = Form::input('name', '姓名')->required();
                $f[] = Form::input('bankname', '开户行')->required();
                $f[] = Form::input('cardnum', '银行卡号')->required();
                break;
            case 'weixin':
                $f[] = Form::input('name', '姓名')->required();
                $f[] = Form::input('weixin', '微信号')->required();
                break;
            default:
                $this->failed('不允许的提现方式');
                break;
        }
        $form = Form::make_post_form('申请提现', $f, Url::buildUrl('saveExtract'));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * 添加/修改
     * @param int $id
     */
    public function saveExtract()
    {
        $store_info = SystemStore::where('id', $this->adminInfo['store_id'])->find();
        if (!$store_info) Json::fail('门店不存在');
        $uid = \app\models\user\User::where('user_store_id', $store_info['id'])->column('uid');
        if (!count($uid)) Json::fail('推荐用户不足100人');
        $count = \app\models\user\User::where('spread_uid', 'in', $uid)->count();
        if ($count < 100) Json::fail('推荐用户不足100人');
        $data = UtilService::postMore([
            ['alipay_code', ''],
            ['extract_type', ''],
            ['money', 0],
            ['name', ''],
            ['bankname', ''],
            ['cardnum', ''],
            ['weixin', ''],
        ]);
        if ($data['money'] > $store_info['money']) Json::fail('可提余额不足');
        if (!$data['cardnum'] == '')
            if (!preg_match('/^([1-9]{1})(\d{14}|\d{18})$/', $data['cardnum']))
                Json::fail('银行卡号输入有误');
        if (StoreExtract::userExtract($store_info, $data))
            Json::success('申请提现成功!');
        else
            Json::fail(StoreExtract::getErrorInfo('提现失败'));
    }

}
