<?php

namespace app\adminapi\controller\v1\merchant;

use app\adminapi\controller\AuthController;
use app\models\merchant\MerchantMiniprogram;
use app\models\merchant\Merchant as MerchantModel;
use app\Request;
use crmeb\basic\BaseModel;
use crmeb\services\UtilService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Response;

class Merchant extends AuthController
{
    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 注册商户
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function registerMerchant(Request $request)
    {
        $data = UtilService::postMore([
            ['name', '', '', '', [
                'empty_check',
                function ($val) {
                    return MerchantModel::be(['name' => $val]);
                }
            ], ['请输入小程序名称', '已存在同名小程序']]
        ], $request, false);
        try {
            $data['add_time'] = time();
            $res = MerchantModel::create($data);
            if ($res)
                return app('json')->success('添加小程序成功', ['id' => $res->id]);
            else
                return app('json')->fail('添加小程序失败');
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage());
        } catch (DbException $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    /**
     * 编辑商户
     * @param $mer_id
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function editMerchant($mer_id, Request $request)
    {
        $data = UtilService::postMore([
            ['name', ''],
            ['lx_name', ''],
            ['phone', '']
        ], $request, false);
        if (!($mer_id && MerchantModel::be($mer_id))) {
            return app('json')->fail('小程序不存在');
        }
        try {
            $res = MerchantModel::edit($data, $mer_id);
            if ($res)
                return app('json')->success('编辑小程序成功');
            else
                return app('json')->fail('编辑小程序失败');
        } catch (Exception $e) {
            return app('json')->fail($e->getMessage());
        } catch (DbException $e) {
            return app('json')->fail($e->getMessage());
        }
    }

    /**
     * 编辑商户支付信息
     * @param $mer_id
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function editMerchantPay($mer_id, Request $request)
    {
        $data = UtilService::postMore([
            ['mch_id', ''],
            ['mch_key', ''],
            ['mch_cert_p12', ''],
        ], $request, false);
        if (!($mer_id && MerchantMiniprogram::vaildWhere()->where(['mer_id' => $mer_id])->count() > 0)) {
            return app('json')->fail('商户小程序尚未关联');
        }
        $update = [];
        foreach ($data as $k => $v) {
            if (!empty_check($v)) {
                $update[$k] = $v;
            }
        }
        BaseModel::beginTrans();
        try {
            $update['update'] = time();
            $res = MerchantMiniprogram::where('mer_id', $mer_id)->update($update);
            if ($res) {
                BaseModel::commitTrans();
                return app('json')->success('编辑商户支付信息成功');
            } else {
                BaseModel::rollbackTrans();
                return app('json')->fail('编辑商户支付信息失败');
            }
        } catch (Exception $e) {
            BaseModel::rollbackTrans();
            return app('json')->fail($e->getMessage());
        } catch (DbException $e) {
            BaseModel::rollbackTrans();
            return app('json')->fail($e->getMessage());
        }
    }

    /**
     * 获取商户列表
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function getMerchantList(Request $request)
    {
        $where = UtilService::getMore([
            ['page', 1],
            ['limit', 10],
            ['name', '']
        ], $request, false);
        $list = MerchantModel::getList($where);
        return app('json')->success('ok', $list);
    }

    /**
     * 获取商户详情
     * @param $mer_id
     * @param Request $request
     * @return mixed
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function getMerchantDetail($mer_id, Request $request)
    {
        if (!$mer_id) {
            return app('json')->fail('小程序不存在');
        }
        $merchant = MerchantModel::get($mer_id);
        if (!$merchant) {
            return app('json')->fail('小程序不存在');
        }
        $merchant = $merchant->toArray();
        $merchant['miniprogram_info'] = ($data = MerchantMiniprogram::vaildWhere()->where('mer_id', $mer_id)->find()) && $data ? $data->toArray() : [];
        return app('json')->success('ok', $merchant);
    }


    /**
     * 删除指定资源
     *
     * @param $mer_id
     * @return Response
     */
    public function delete($mer_id)
    {
        if (!MerchantMiniprogram::delMiniprogram($mer_id))
            return $this->fail(MerchantMiniprogram::getErrorInfo('删除失败,请稍候再试!'));
        else
            return $this->success('删除成功!');
    }

}