<?php

namespace App\Http\Controllers\Mounting;

use App\Inc\CommonInc;
use App\Services\AccountLogService;
use App\Services\AccountService;
use App\Services\VehicleService;
use Illuminate\Http\Request;
use BlueCity\Core\Controllers\MountingCoreController as Controller;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\LoginUserService;
use BlueCity\Core\Traits\ResourceControllerMethod;
use Illuminate\Support\Facades\DB;


class AccountController extends Controller
{

    public $dataService = null;  // ResourceControllerMethod 必备参数
    public $dataFields = [''];  // 保存和修改时的 fields 参数
    protected $validateRules = [
        'rules' => [
            'mem_name' => 'required',
            'mem_phone' => 'required'
        ],
        'messages' => [

        ],
        'attributes' => [
            'mem_name' => '姓名',
            'mem_sex' => '性别',
            'mem_phone' => '联系电话',
            'mem_birthday' => '生日',
            'mem_car_num' => '车牌号',
            'mem_car_series' => '车系',
            'mem_car_model' => '车型',
            'mem_province' => '省',
            'mem_city' => '市',
            'mem_county' => '区县',
            'mem_address' => '地址',
            'mem_consume_money' => '消费总金额',
            'mem_order_all' => '订单总量',
            'mem_retreat_trade' => '退换次数',
            'mem_create_time' => '添加时间',
            'mem_update_time' => '更新时间',
            'mem_bership' => '1正式会员2临时会员'
        ]
    ];

    public function __construct()
    {
        $service = new AccountService();
        $this->bootWithService($service);
    }

    use ResourceControllerMethod;

    /**
     * @api {get} /api/mounting/account 用户账户列表
     * @apiGroup account
     * @apiName 用户管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 用户账户列表
     *
     * @apiParam {String} keywords      关键字
     * @apiParam {String} page          页码
     * @apiParam {String} page_size     页容量
     *
     * @apiSuccess {Number} error       状态码，0：请求成功
     * @apiSuccess {String} msg         提示信息
     * @apiSuccess {Object} data        返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常","data":[]}
     *
     */


    /**
     * @api {post} /api/mounting/account 用户账户添加
     * @apiGroup account
     * @apiName 用户管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 用户账户添加
     *
     * @apiParam {String} mem_name      用户名
     * @apiParam {String} mem_sex       性别
     * @apiParam {String} mem_birthday  生日
     * @apiParam {String} mem_province  省
     * @apiParam {String} mem_city      市
     * @apiParam {String} mem_county    区县
     * @apiParam {String} mem_address   详细地址
     * @apiParam {String} mem_bership
     * @apiParam {String} mem_phone     电话
     * @apiParam {String} mem_car_num   车牌号
     * @apiParam {String} mem_car_series 车系
     * @apiParam {String} mem_car_model 车型
     *
     * @apiSuccess {Number} error       状态码，0：请求成功
     * @apiSuccess {String} msg         提示信息
     * @apiSuccess {Object} data        返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常","data":[]}
     *
     */
    // 新增
    public function store(Request $request)
    {
        $user_info = LoginUserService::getUser();
        $adm_cid = $request['adm_cid'] = $user_info['adm_cid'];
        $shop_id = $request['shop_id'] = $user_info['shop_id'];
        $superior_shop_id = $request['superior_shop_id'] = $user_info['superior_shop_id'];
//        if (empty($request->get(''))) {
//
//        }
        //判断手机号 存在已否
        $exist = AccountService::getExists([
            'mem_cid' => $adm_cid,
            'mem_superior_shop_id' => $shop_id,
            'mem_phone' => $request->get('mem_phone')
        ], $shop_id);
        if ($exist) {
            return $this->error('当前手机号已存在', ErrorInc::INVALID_PARAM);
        }
        if ($request->get('mem_car_num')) {
            // 判断车牌号是否存在
            $exist = VehicleService::getExists([
                'meca_cid' => $adm_cid,
                'meca_superior_shop_id' => $superior_shop_id,
                'meca_car_num' => $request->get('mem_phone')
            ], $shop_id);
            if ($exist) {
                return $this->error('当前车牌号已存在', ErrorInc::INVALID_PARAM);
            }
        }
        DB::beginTransaction();
        // 2 新增一个会员信息
        $member = $this->dataService->create($request->all());
        if (!$member) {
            DB::rollBack();
            return $this->error('会员新增失败', ErrorInc::MYSQL_FAILED);
        }
        $mem_id = $member->mem_id;
        // 3.新增一个车辆信息
        if ($request['mem_car_num']) {
            $request['meca_mem_id'] = $mem_id;
            $meca_res = (new VehicleService())->create($request->all());
        } else {
            $meca_res = true;
        }

        if ($mem_id && $meca_res) {
            DB::commit();
//            Common::addLog($user_info, getRealIp($request), '会员列表','新增','新增会员：'.$request['mem_phone'].'成功');
            $return_data['mem_id'] = $mem_id;
            return $this->success('新增会员成功', $return_data);
        } else {
            DB::rollBack();

            return $this->error('新增会员失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @api {put} /api/mounting/account/{mem_id} 用户账户编辑
     * @apiGroup account
     * @apiName 用户管理
     * @apiVersion 1.0.0
     *
     * @apiDescription 用户账户编辑
     *
     * @apiParam {String} mem_id            用户ID
     * @apiParam {String} mem_name      用户名
     * @apiParam {String} mem_sex       性别
     * @apiParam {String} mem_birthday  生日
     * @apiParam {String} mem_province  省
     * @apiParam {String} mem_city      市
     * @apiParam {String} mem_county    区县
     * @apiParam {String} mem_address   详细地址
     * @apiParam {String} mem_bership
     * @apiParam {String} mem_phone     电话
     * @apiParam {String} mem_car_num   车牌号
     * @apiParam {String} mem_car_series 车系
     * @apiParam {String} mem_car_model 车型
     *
     * @apiSuccess {Number} error       状态码，0：请求成功
     * @apiSuccess {String} msg         提示信息
     * @apiSuccess {Object} data        返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"code":0,"message":"","data":[]}
     *
     * @apiErrorExample {json} Error-Response:
     * {"code":5001,"message":"接口异常","data":[]}
     *
     */
    // 编辑
    public function update(Request $request)
    {
        // 验证数据
        $mem_id = $request['mem_id'];

        // 获取当前操作账号信息
        $user_info = LoginUserService::getUser();
        $adm_cid = $user_info['adm_cid'];
        $shop_id = $user_info['shop_id'];
        $superior_shop_id = $user_info['superior_shop_id'];

        // 判断是否为加盟店账号,shop_superior_id 为0 是总店，不为0，是总店id或加盟店id
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;

        // 1. 判断手机号是否存在
        $exist = AccountService::getExists([
            'mem_id' => ['<>', $mem_id],
            'mem_superior_shop_id' => $superior_shop_id,
            'mem_phone' => $request['mem_phone']
        ], $shop_id);
        if ($exist) {
            return $this->error('当前手机号已存在', ErrorInc::INVALID_PARAM);
        }
        if ($request['mem_car_num']) {
            // 判断车牌号是否存在
            $where = [];
            $where[] = [];
            $exist = VehicleService::getExists([
                'meca_mem_id' => $mem_id,
                'meca_superior_shop_id' => $superior_shop_id,
                'meca_car_num' => $request['mem_phone']
            ], $shop_id);
            if ($exist) {
                return $this->error('当前车牌号已存在', ErrorInc::INVALID_PARAM);
            }
        }
        $mem_res = AccountService::update($request, $mem_id, 'mem_id');
        if ($mem_res) {
//            Common::addLog($user_info, getRealIp($request), '会员列表', '编辑', '编辑会员：' . $request['mem_phone'] . '成功');
            return $this->success('编辑会员成功');
        } else {
            return $this->error('编辑会员失败', ErrorInc::MYSQL_FAILED);
        }
    }

    public function logs(Request $request) {
        $memberID = intval($request['mem_id']);
        if ($memberID == 0) {
            return $this->error('会员参数错误', ErrorInc::INVALID_PARAM);
        }
        $account = AccountService::getByID($memberID);
        if (!$account) {
            return $this->error('该用户不存在', ErrorInc::INVALID_PARAM);
        }
        $logs = (new AccountLogService)->search(['member_id'=>$memberID], '*', 1, 0);

        return $this->success('获取成功', $logs);
    }

    public function pay(Request $request)
    {
        // 验证数据
        $memberID = intval($request['mem_id']);
        $orderID = intval($request['order_id']);
        $money = intval($request['money'] * 100);//转换成人民币:分
        if ($memberID == 0) {
            return $this->error('会员参数错误', ErrorInc::INVALID_PARAM);
        }
        if ($money == 0) {
            return $this->error('金额参数错误', ErrorInc::INVALID_PARAM);
        }

        $account = AccountService::getByID($memberID);
        if (!$account) {
            return $this->error('该用户不存在', ErrorInc::INVALID_PARAM);
        }

        //加个分布式锁，避免有事务冲突
        $lock = AccountService::lockAccount($account['mem_id']);
        if (!$lock) {
            return $this->error('该账户锁定中，请稍后尝试', ErrorInc::BUSINESS_FORBID);
        }
        DB::beginTransaction();
        $result = AccountService::changeBalance($account, $money, CommonInc::ACCOUNT_LOG_TYPE_ORDER);
        if ($result) {

            //这里应该add操作日志，免得找茬
            DB::commit();
            AccountService::unlockAccount($account['mem_id']); //解锁分布式锁
            return $this->success('操作成功');
        }
        DB::rollBack();
        AccountService::unlockAccount($account['mem_id']); //解锁分布式锁

        return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
    }

    public function recharge(Request $request)
    {
        // 验证数据
        $memberID = intval($request['mem_id']);
        $money = intval($request['money'] * 100);//转换成人民币:分
        if ($memberID == 0) {
            return $this->error('会员参数错误', ErrorInc::INVALID_PARAM);
        }
        if ($money == 0) {
            return $this->error('金额参数错误', ErrorInc::INVALID_PARAM);
        }

        $account = AccountService::getByID($memberID);
        if (!$account) {
            return $this->error('该用户不存在', ErrorInc::INVALID_PARAM);
        }

        //加个分布式锁，避免有事务冲突
        $lock = AccountService::lockAccount($account['mem_id']);
        if (!$lock) {
            return $this->error('该账户锁定中，请稍后尝试', ErrorInc::BUSINESS_FORBID);
        }
        DB::beginTransaction();
        $result = AccountService::changeBalance($account, $money, CommonInc::ACCOUNT_LOG_TYPE_RECHARGE);
        if ($result) {
            //这里应该add操作日志，免得找茬
            DB::commit();
            AccountService::unlockAccount($account['mem_id']); //解锁分布式锁
            return $this->success('操作成功');
        }
        DB::rollBack();
        AccountService::unlockAccount($account['mem_id']); //解锁分布式锁

        return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
    }



    public function cancelLog(Request $request)
    {
        $logID = intval($request->get('log_id'));
        if ($logID == 0) {
            return $this->error('日志id错误', ErrorInc::INVALID_PARAM);
        }
        $shopID = LoginUserService::getUserShopID();
        $log = AccountLogService::getByID($logID, $shopID);
        if (!$log) {
            return $this->error('日志未找到', ErrorInc::DATA_EMPTY);
        }
        //初始化需要的账户和记录数据
        $changeValue = $log['change_value'];
        $logType = $log['log_type'];
        $account = AccountService::getByID($log['member_id'], $shopID);
        $balance = $account['balance'];
        $lock = AccountService::lockAccount($account['mem_id']);//加个分布式锁，避免有事务冲突
        if (!$lock) {
            return $this->error('该账户锁定中，请稍后尝试', ErrorInc::BUSINESS_FORBID);
        }
        //判断记录的性质算出最后金额等
        if (CommonInc::ACCOUNT_BALANCE_ADD == $logType) { //如果是增加记录
            if ($account['balance'] - $log['change_value'] < 0) {
                return $this->error('取消此记录会导致账户余额为负数', ErrorInc::BUSINESS_FORBID);
            }
            $balance = $account['balance'] - $changeValue;
        } else if (CommonInc::ACCOUNT_BALANCE_REDUCE == $logType) { //如果是减少记录
            $balance = $account['balance'] + $changeValue;
        }
        $data['balance'] = $balance;

        //开始执行修改
        DB::beginTransaction();
        $result = $this->dataService->update($data, $logID);
        if ($result) {
            (new AccountLogService())->delete($logID);
            //这里应该add操作日志，免得找茬
            DB::commit();
            AccountService::unlockAccount($account['mem_id']); //解锁分布式锁
            return $this->success('记录取消成功');
        }
        DB::rollBack();
        AccountService::unlockAccount($account['mem_id']); //解锁分布式锁

        return $this->error('取消失败', ErrorInc::MYSQL_FAILED);
    }

    public function destroy(int $id)
    {
        $shopID = LoginUserService::getUserShopID();
        $entity = AccountService::getByID($id, $shopID);
        if (empty($entity)) {
            $this->error('无此账户', ErrorInc::INVALID_PARAM);
        }
        if ($entity['balance'] > 0) {
            $this->error('该账户内仍有余额无法删除', ErrorInc::BUSINESS_FORBID);
        }
        $result = $this->dataService->destroy($id);
        if ($result) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败', ErrorInc::MYSQL_FAILED);
        }
    }
}
