<?php


namespace app\badminapi\controller\merchant;


use app\badminapi\controller\AuthController;
use app\models\merchant\MerchantMiniprogram;
use app\models\merchant\Merchant as MerchantModel;
use app\models\merchant\Industry as IndustryModel;
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]);
                }
            ], ['请输入店铺名称', '已存在同名店铺']],
            ['logo', '', '', '', 'empty_check', '请上传店铺Logo'],
            ['business_license', '', '', '', 'empty_check', '请输入营业执照号'],
            ['lx_name', '', '', '', 'empty_check', '请输入联系人'],
            ['phone', '', '', '', 'empty_check', '请输入电话'],
            ['industry_id', '', '', '', 'empty_check', '请选择所属行业'],
            ['address', '', '', '', 'empty_check', '', '请填写完整店铺地址'],
            ['detail_address', '', '', '', 'empty_check', '请填写完整店铺地址'],
            ['facilities', [], '', '', 'empty_check', '请输入店内设施'],
            ['day_time', '', '', '', 'empty_check', '请选择营业时间'],
            ['local', '', '', '', 'empty_check', '请填写商户域名'],
        ], $request, false);
        BaseModel::beginTrans();
        try {
            $data['industry_id'] = implode(',', $data['industry_id']);
            $data['address'] = implode(',', $data['address']);
            $data['facilities'] = implode(',', $data['facilities']);
            $data['day_time'] = implode(' - ', $data['day_time']);
            $data['add_time'] = time();
            $data['version'] = 1;
            $data['valid_time'] = strtotime("+1 year");
            if ($data['local']) $data['local_md5'] = strtolower(md5($data['local']));
            $res = MerchantModel::create($data);
            if ($res) {
                BaseModel::commitTrans();
                return app('json')->success('注册商户成功', ['id' => $res->id]);
            } 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 $mer_id
     * @param Request $request
     * @return mixed
     * @throws \Exception
     */
    public function editMerchant($mer_id, Request $request)
    {
        $data = UtilService::postMore([
            ['name', ''],
            ['logo', ''],
            ['business_license', ''],
            ['lx_name', ''],
            ['phone', ''],
            ['industry_id', ''],
            ['address', ''],
            ['detail_address', ''],
            ['facilities', []],
            ['day_time', ''],
            ['local', ''],
        ], $request, false);
        if (!($mer_id && MerchantModel::be($mer_id))) {
            return app('json')->fail('商户不存在');
        }
        $update = [];
        $data['day_time'] = implode(' - ', $data['day_time']);
        foreach ($data as $k => $v) {
            if (!empty_check($v)) {
                if (is_array($v))
                    $update[$k] = implode(',', $v);
                else
                    $update[$k] = $v;
            }
        }
        BaseModel::beginTrans();
        try {
            $res = MerchantModel::edit($update, $mer_id);
            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 $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],
            ['key_word', ''],
            ['industry_id', ''],
            ['version', ''],
            ['data', ''],
        ], $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() : [];
        $merchant['industry_name'] = IndustryModel::where('id', 'IN', $merchant['industry_id'])->column('name');
        $merchant['industry_id'] = $merchant['industry_id'] ? explode(',', $merchant['industry_id']) : [];
        $merchant['address'] = $merchant['address'] ? explode(',', $merchant['address']) : [];
        $merchant['facilities'] = $merchant['facilities'] ? explode(',', $merchant['facilities']) : [];
        $merchant['day_time'] = $merchant['day_time'] ? explode(' - ', $merchant['day_time']) : [];
        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('删除成功!');
    }

}