<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\model\Manager as mManager;
use app\common\model\Platform as mPlatform;
use app\common\validate\Platform as vPlatform;

class Platform extends Base
{

    /**
     * @系统推荐渠道列表
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\9 0009 11:55
     */
    public function lists($param)
    {
        // 查询已接入平台
        $mPlatform = new mPlatform();
        $enameArr = $mPlatform -> column('ename');
        $url = config('api.xigu.domain') . config('api.xigu.platform');
        $result = json_decode(curl($url), true);
        foreach ($result['data'] as &$v) {
            if (in_array($v['ename'], $enameArr)) {
                $v['disable'] = 1;
            } else {
                $v['disable'] = 0;
            }
        }
        return $result;
    }

    /**
     * @我的渠道列表
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\8 0008 11:41
     */
    public function mine($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $where = [];
        if (!empty($param['name'])) {
            $where [] = ['p.name', 'like', '%' . $param['name'] . '%'];
        }
        if (!empty($param['create_type'])) {
            $where [] = ['create_type', '=', $param['create_type']];
        }
        $where [] = ['p.status', 'in', '0,1'];
        $field = 'p.id,p.name,p.status,p.linkman,p.tel,p.create_time,p.creator,create_type,p.appid';
        $mPlatform = new mPlatform();
        $result['count'] = $mPlatform -> alias('p') -> where($where) -> count('id');
        if ($result['count'] < 1) {
            return $result;
        }
        $result['page'] = $page;
        $data = $mPlatform -> alias('p')
                -> field($field)
                -> where($where) -> order('p.update_time desc') -> page($page, $limit) -> select();
        foreach ($data as &$v) {
            $v['create_type_str'] = $v['create_type'] == 1 ? '自主添加' : '系统导入';
        }
        $result['data'] = $data;
        return $result;
    }


    /**
     * @添加渠道
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\8 0008 11:05
     */
    public function create($param)
    {
        $result = ['code' => 200, 'msg' => '渠道添加成功', 'data' => []];
        $vPlatform = new vPlatform();
        if (!$vPlatform -> scene('create') -> check($param)) {
            $result['code'] = 0;
            $result['msg'] = $vPlatform -> getError();
            return $result;
        }
        try {
            $mPlatform = new mPlatform();
            $mPlatform -> name = $param['name'];
            $mPlatform -> appid = $param['appid'];
            $mPlatform -> ename = $param['ename'];
            $mPlatform -> api = json_encode($param['api'], JSON_UNESCAPED_UNICODE);
            $mPlatform -> token = $param['token'];
            $mPlatform -> linkman = $param['linkman'];
            $mPlatform -> tel = $param['tel'];
            $mPlatform -> creator_id = $this -> getManagerId();
            $mPlatform -> creator = $this -> getManagerName();
            $mPlatform -> save();
        } catch (\Exception $e) {
            $result['code'] = '1200002';
            $result['msg'] = $this -> errorCode(1200002);
        }
        return $result;
    }


    /**
     * @渠道详情
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\8 0008 11:43
     */
    public function detail($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $vPlatform = new vPlatform();
        if (!$vPlatform -> scene('detail') -> check($param)) {
            $result['code'] = 0;
            $result['msg'] = $vPlatform -> getError();
            return $result;
        }
        $result['data'] = $this -> info($param);
        return $result;
    }

    /**
     * @更新渠道
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\8 0008 12:02
     */
    public function modify($param)
    {
        $result = ['code' => 200, 'msg' => '渠道修改成功', 'data' => []];
        if (!empty($param['api'])) {
            foreach ($param['api'] as $key => $value) {
                $param['api_' . $key] = $value;
            }
        }
        $vPlatform = new vPlatform();
        if (!$vPlatform -> scene('modify') -> check($param)) {
            $result['code'] = 0;
            $result['msg'] = $vPlatform -> getError();
            return $result;
        }
        $mPlatform = $this -> info(['id' => $param['id']]);
        if (empty($mPlatform)) {
            $result['code'] = '1200004';
            $result['msg'] = $this -> errorCode(1200004);
            return $result;
        }
        try {
            $mPlatform -> name = $param['name'];
            $mPlatform -> appid = $param['appid'];
            $mPlatform -> ename = $param['ename'];
            $mPlatform -> api = json_encode($param['api'], JSON_UNESCAPED_UNICODE);
            $mPlatform -> token = $param['token'];
            $mPlatform -> linkman = $param['linkman'];
            $mPlatform -> tel = $param['tel'];
            $mPlatform -> creator_id = $this -> getManagerId();
            $mPlatform -> creator = $this -> getManagerName();
            $mPlatform -> save();
        } catch (\Exception $e) {
            $result['code'] = '1200003';
            $result['msg'] = $this -> errorCode(1200003);
        }
        return $result;
    }


    /**
     * @激活渠道
     *
     * @author: zsl
     * @since: 2021/3/12 9:38
     */
    public function apply($param)
    {
        $result = ['code' => 200, 'msg' => '渠道激活成功,请联系平台获取appid和token', 'data' => []];
        // 获取系统渠道信息
        $url = config('api.xigu.domain') . config('api.xigu.platform_info');
        $rData = [];
        $rData['id'] = $param['id'];
        $platformInfo = json_decode(curl($url, $rData), true);
        if (empty($platformInfo)) {
            $result['code'] = 0;
            $result['msg'] = '获取渠道信息失败';
            return $result;
        }
        $vPlatform = new vPlatform();
        if (!$vPlatform -> scene('create') -> check($platformInfo)) {
            $result['code'] = 0;
            $result['msg'] = $vPlatform -> getError();
            return $result;
        }
        //检查接口标识是否被使用
        $mPlatform = new mPlatform();
        $info = $mPlatform -> where(['ename' => $platformInfo['ename']]) -> find();
        if (!empty($info)) {
            $result['code'] = '1200012';
            $result['msg'] = $this -> errorCode(1200012) . $info['ename'];
            return $result;
        }
        try {

            // 生成接口文件
            $templateFile = env('app_path') . 'common' . DIRECTORY_SEPARATOR . 'platform' . DIRECTORY_SEPARATOR . 'TEMPLATE.PHP';
            $targetFile = env('app_path') . 'common' . DIRECTORY_SEPARATOR . 'platform' . DIRECTORY_SEPARATOR . $platformInfo['ename'] . '.php';
            $fileContent = str_replace('TEMPLATE', $platformInfo['ename'], file_get_contents($templateFile));
            $res = file_put_contents($targetFile, $fileContent);
            if (!$res) {
                $result['code'] = '1200011';
                $result['msg'] = $this -> errorCode(1200011);
                return $result;
            }
            // 添加平台数据
            $mPlatform = new mPlatform();
            $mPlatform -> name = $platformInfo['name'];
            $mPlatform -> appid = '';
            $mPlatform -> ename = $platformInfo['ename'];
            $mPlatform -> api = json_encode($platformInfo['api'], JSON_UNESCAPED_UNICODE);
            $mPlatform -> token = '';
            $mPlatform -> linkman = $platformInfo['linkman'];
            $mPlatform -> tel = $platformInfo['tel'];
            $mPlatform -> creator_id = $this -> getManagerId();
            $mPlatform -> creator = $this -> getManagerName();
            $mPlatform -> create_type = 2;
            $res = $mPlatform -> save();
            if (false === $res) {
                $result['code'] = '1200002';
                $result['msg'] = $this -> errorCode(1200002);
                return $result;
            }
        } catch (\Exception $e) {
            $result['code'] = '1200002';
            $result['msg'] = $this -> errorCode(1200002);
        }
        return $result;
    }


    /**
     * @某渠道信息
     *
     * @author: 鹿文学[lwx]<fyj301415926@126.com>
     * @since: 2020\12\8 0008 14:18
     */
    private function info($param)
    {
        $detail = [];
        if (!empty($param['id'])) {
            $mPlatform = new mPlatform();
            $detail = $mPlatform -> where('id', '=', $param['id']) -> where('status', 'in', [0, 1]) -> find();
            $detail -> api = json_decode($detail -> api, true);
        }
        return $detail;
    }


    private function errorCode($code)
    {
        $errorCode = [
                1200001 => '',
                1200002 => '渠道添加失败',
                1200003 => '渠道修改失败',
                1200004 => '渠道不存在，或已被删除',
                1200006 => '渠道启用失败',
                1200007 => '渠道禁用失败',
                1200010 => '渠道删除失败',
                1200011 => '生成接口文件失败',
                1200012 => '平台标识已被使用',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }


}
