<?php

namespace app\common\service;

use app\common\model\PreOrder;
use GuzzleHttp\Client;
use think\Db;
use think\Exception;
use think\Log;

class UserService
{
    private $model =  null;

    /**
     * 初始化方法
     */
    public function __construct()
    {
        $this->model = Db::name('user');
    }

    /**
     * 用户换绑
     * @return void
     */
    public function userBindCompany($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            $companyId = isset($params['company_id']) ? $params['company_id'] : 0;
            $where['id'] = $userId;
            $user = Db::name('user')->where($where['id'])->find();
            if (!empty($user)) {
                if ($user['company_id'] != $companyId) {
                    $userData['company_id'] = $companyId;
                    $userData['updatetime'] = time();
                    $userRes = Db::name('user')->where($where['id'])->update($userData);
                    if (!$userRes) {
                        throw new Exception('操作失败');
                    }
                }
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * 用户绑定门店和钱包
     * @return void
     */
    public function userWallet($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            $companyId = isset($params['company_id']) ? $params['company_id'] : 0;
            $comefrom = isset($params['comefrom']) ? $params['comefrom'] : '';
            $bindRes = $this->userBindCompany($params);//绑定门店
            if (!$bindRes['status']) {
                throw new Exception($bindRes['msg']);
            }
            $where['user_id'] = $userId;
            $where['company_id'] = $companyId;
            $userWallet = Db::name('user_wallet')->where($where['id'])->find();
            $time = time();
            if (empty($userWallet)) {
                $userWalletData = [
                    'user_id' => $userId,
                    'company_id' => $companyId,
                    'money' => 0.00,
                    'createtime' => $time,
                    'comefrom' => $comefrom,
                ];
                $userWalletRes = Db::name('user_wallet')->insertGetId($userWalletData);
                if (!$userWalletRes) {
                    throw new Exception('生成钱包失败');
                }
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * 预约消息
     * @return void
     */
    public function msgPreOrder($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $preOrderId = isset($params['pre_order_id']) ? $params['pre_order_id'] : 0;

            $p = 'pre_order';
            $u = 'user';
            $c = 'company';
            $s = 'servicetype';
            $field = $p.'.*,'.$u.'.mini_openid,'.$c.'.name as `company_name`,'.$s.'.title as `service_title`';
            $where[$p.'.id'] = $preOrderId;
            $preOrder = Db::name($p)->alias($p)->field($field)
                ->join($u,$u.'.id = '.$p.'.user_id','LEFT')
                ->join($c,$c.'.id = '.$p.'.company_id','LEFT')
                ->join($s,$s.'.id = '.$p.'.servicetype_id','LEFT')
                ->where($where)->find();
            if (empty($preOrder)) {
                throw new Exception('未找到预约信息');
            }
            $statusArr = model('PreOrder')->getPreOrderStatusList();
            $statusText = isset($statusArr[$preOrder['pre_order_status']]) ? $statusArr[$preOrder['pre_order_status']] : '';
            $wechatTemplate = config('param.wechat_template');
            $preOrderMsg = isset($wechatTemplate['pre_order']) ? $wechatTemplate['pre_order'] : [];
            $wechatSetting = config('param.wechat_setting');
            if ($wechatSetting == 'release') {//正式
                /*预约时间：{{time2.DATA}}
                网点名称：  {{thing3.DATA}}
                类型：     {{thing1.DATA}}*/
                $data = [//数据内容
                    "time2"  => ["value" => date('Y年m月d日 H:i',$preOrder['pre_time'])],
                    "thing3" => ["value" => $preOrder['company_name'] .'的预约'.$statusText],
                    "thing1" => ["value" => $preOrder['service_title']],
                ];
            } else {
            /*预约日期 {{time1.DATA}}
              场地{{thing8.DATA}}
              预约类型{{thing7.DATA}}
              顾客称号{{thing3.DATA}}*/
                $data = [//数据内容
                    "time1"  => ["value" => date('Y年m月d日 H:i',$preOrder['pre_time'])],
                    "thing8" => ["value" => $preOrder['company_name'] .'的预约'.$statusText],
                    "thing7" => ["value" => $preOrder['service_title']],
                    "thing3" => ["value" => $preOrder['name']],
                ];
            }
            $paramsData = $preOrderMsg;
            $paramsData['mini_openid'] = $preOrder['mini_openid'];
            $paramsData['data'] = $data;
            $msgRes = $this->wechatMessageSend($paramsData);
            if (!$msgRes['status']) {
                throw new Exception($msgRes['msg']);
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
            $errorData = [
                'pre_order_id' => $preOrderId,
                'params' => isset($paramsData) ? $paramsData : [],
                'error' => $result['msg'],
            ];
            Log::error(json_encode($errorData));
        }
        return $result;
    }

    /**
     * 订单消息
     * @return void
     */
    public function msgOrder($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $orderId = isset($params['order_id']) ? $params['order_id'] : 0;

            $o = 'order';
            $u = 'user';
            $where[$o.'.id'] = $orderId;
            $field = $o.'.*,'.$u.'.mini_openid';
            $order = Db::name('order')->alias($o)->field($field)
                ->join($u,$u.'.id = '.$o.'.user_id','LEFT')
                ->where($where)->find();
            if (empty($order)) {
                throw new Exception('未找到订单信息');
            }
            $statusArr = model('Order')->getStatusList();
            $statusText = isset($statusArr[$order['status']]) ? $statusArr[$order['status']] : '';
            $wechatTemplate = config('param.wechat_template');
            $orderMsg = isset($wechatTemplate['order']) ? $wechatTemplate['order'] : [];
            $wechatSetting = config('param.wechat_setting');
            if ($wechatSetting == 'release') {//正式
                /*工单号： {{character_string5.DATA}}
                  状态：   {{phrase4.DATA}}
                  下单时间：{{time8.DATA}}*/
                $data = [//数据内容
                    "character_string5"  => ["value" => $order['orderno']],
                    "phrase4" => ["value" => $statusText],
                    "time8" => ["value" => date('Y年m月d日 H:i:s',$order['createtime'])],
                ];
            } else {
            /*工单号{{character_string1.DATA}}
              处理进度 {{phrase4.DATA}}
              提交时间 {{time2.DATA}}*/
                $data = [//数据内容
                    "character_string1"  => ["value" => $order['orderno']],
                    "phrase4" => ["value" => $statusText],
                    "time2" => ["value" => date('Y年m月d日 H:i:s',$order['createtime'])],
                ];
            }
            $orderMsg['page'] = $orderMsg['page'].'?id='.$order['id'];
            $paramsData = $orderMsg;
            $paramsData['mini_openid'] = $order['mini_openid'];
            $paramsData['data'] = $data;
            $msgRes = $this->wechatMessageSend($paramsData);
            if (!$msgRes['status']) {
                throw new Exception($msgRes['msg']);
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
            $errorData = [
                'order_id' => $orderId,
                'params' => isset($paramsData) ? $paramsData : [],
                'error' => $result['msg'],
            ];
            Log::error(json_encode($errorData));
        }
        return $result;
    }

    /**
     * 微信消息发送
     * @return void
     */
    public function wechatMessageSend($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $client = new Client();
            $tk = getAccessToken();
            $uri = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$tk;

            $jsonData = [
                "touser"            => isset($params['mini_openid']) ? $params['mini_openid'] : '',//openid
                "template_id"       => isset($params['template_id']) ? $params['template_id'] : '',//模版ID
                "page"              => isset($params['page']) ? $params['page'] : '',              //跳转地址
                "miniprogram_state" => isset($params['miniprogram_state']) ? $params['miniprogram_state'] : '',//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
                "lang"              => isset($params['lang']) ? $params['lang'] : 'zh_CN',         //支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN
                "data"              => isset($params['data']) ? $params['data'] : [],              //数据
            ];
            $res = $client->request('POST', $uri, ['json' => $jsonData]);
            $returnResJson = $res->getBody()->getContents();
            $returnRes = json_decode($returnResJson, true);
            if ($returnRes['errcode'] != 0) {
                throw new Exception($returnRes['errmsg']);
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
}