<?php
namespace app\admin\controller\weixin;

use app\common\controller\Backend;
use addons\weixin\library\WechatService;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 微信菜单  控制器
 * Class Menus
 * @package app\admin\controller\wechat
 */
class Menus extends Backend
{

    protected $wechatcfg = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->wechatcfg = Db::name('weixin_cache')->where('key', 'wechat_menus')->value('result');
        if (empty($this->wechatcfg)) {
            Db::name('weixin_cache')->insert([
                'result' => json_encode([], JSON_UNESCAPED_UNICODE), 'add_time' => time(), 'key' => 'wechat_menus'
            ]);
        }
    }

    public function index()
    {
        if (empty($this->wechatcfg) || $this->wechatcfg == '[]') {
            try {
                $ret = WechatService::menuService()->list();
                $this->wechatcfg = json_encode($ret['menu']['button'], JSON_UNESCAPED_UNICODE);

                Db::name('weixin_cache')->where(['key' => 'wechat_menus'])->update([
                    'result' => $this->wechatcfg, 'add_time' => time()
                ]);
            } catch (\Exception $e) {
                //$this->error($e->getMessage());
            }
        }
        $this->assign('menu', (array)json_decode($this->wechatcfg, true));
        return $this->fetch();
    }

    /**
     * 修改
     */
    public function edit($ids = null)
    {
        $menu = $this->request->post("menu");
        $menu = (array)json_decode($menu, true);
        foreach ($menu as $index => &$item) {
            if (isset($item['sub_button'])) {
                foreach ($item['sub_button'] as &$subitem) {
                    if ($subitem['type'] == 'view') {
                        $allowFields = ['type', 'name', 'url'];
                        $subitem = ['type' => $subitem['type'], 'name' => $subitem['name'], 'url' => $subitem['url']];
                    } else {
                        if ($subitem['type'] == 'miniprogram') {
                            $allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
                            $subitem = [
                                'type' => $subitem['type'], 'name' => $subitem['name'], 'url' => $subitem['url'],
                                'appid' => $subitem['appid'], 'pagepath' => $subitem['pagepath']
                            ];
                        } else {
                            $allowFields = ['type', 'name', 'key'];
                            $subitem = [
                                'type' => $subitem['type'], 'name' => $subitem['name'], 'key' => $subitem['key']
                            ];
                        }
                    }
                    $subitem = array_intersect_key($subitem, array_flip($allowFields));
                }
            } else {
                if ($item['type'] == 'view') {
                    $allowFields = ['type', 'name', 'url'];
                } else {
                    if ($item['type'] == 'miniprogram') {
                        $allowFields = ['type', 'name', 'url', 'appid', 'pagepath'];
                    } else {
                        $allowFields = ['type', 'name', 'key'];
                    }
                }
                $item = array_intersect_key($item, array_flip($allowFields));
            }
        }

        try {
            Db::name('weixin_cache')->where('key', 'wechat_menus')->update([
                'result' => json_encode($menu, JSON_UNESCAPED_UNICODE), 'add_time' => time()
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('修改成功!');
    }

    /**
     * 同步
     */
    public function sync()
    {
        $hasError = false;
        $menu = (array)json_decode($this->wechatcfg, true);
        foreach ($menu as $k => $v) {
            if (isset($v['sub_button'])) {
                if (empty($v['sub_button'])) {
                    unset($menu[$k]['sub_button']);
                    continue;
                }
                foreach ($v['sub_button'] as $m => $n) {
                    if ($n['type'] == 'click' && isset($n['key']) && !$n['key']) {
                        $hasError = true;
                        break 2;
                    }
                }
            } else {
                if ($v['type'] == 'click' && isset($v['key']) && !$v['key']) {
                    $hasError = true;
                    break;
                }
            }
        }
        if (!$hasError) {
            try {
                WechatService::menuService()->delete();
                WechatService::menuService()->create($menu);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        } else {
            $this->error(__('Invalid parameters'));
        }
        $this->success('同步成功!');
    }
}