# -*- coding:utf-8 -*-
"""网站文章"""
from kyger.utility import *



class KgcmsApi(object):
    """KGCMS框架接口"""

    kg = db = None

    def __init__(self):
        pass

    def __call__(self):
        from kyger.kgcms import template
        # 1.数据获取
        get_param = self.kg['get']  # get参数
        post_param = self.kg['post']  # post参数

        # 2.动作判断
        research_id = numeric(get_param.get('id', 0), 0)  # 获取编辑的文章id
        copy_id = numeric(get_param.get('copy', 0), 0)  # 获取编辑的文章id
        if research_id: action = 'edit'
        elif copy_id: action = 'copy'
        else: action = 'add'

        # 3.提交判断
        if post_param.get('action', '') == 'submit':
            pass

        elif post_param.get('action', '') in ('wx_freq', 'dev_freq', 'ip_freq'):
            # 参数
            act_id = numeric(post_param.get('id'), 0)
            freq = numeric(post_param.get('freq', 1), 1)
            time_type = numeric(post_param.get('time_type', 0), 0, 10)
            # 检测
            if not act_id: return json2dict({'errcode': 1, 'errmsg': '问卷id出错'}, trans=False)
            aim_data = self.db.list(table='questionnaire', where=act_id)
            if not aim_data: return json2dict({'errcode': 2, 'errmsg': '问卷不存在'}, trans=False)
            # 工作判断
            if post_param.get('action', '') == 'wx_freq':
                edit_data = {'wx_frequency': freq, 'wx_limit_time': time_type}
            elif post_param.get('action', '') == 'dev_freq':
                edit_data = {'device_frequency': freq, 'device_limit_time': time_type}
            else:
                edit_data = {'ip_frequency': freq, 'ip_limit_time': time_type}

            row = self.db.edit('questionnaire', edit_data, 'id=%s' % act_id)
            if isinstance(row, int): return json2dict({'errcode': 0, 'errmsg': '修改成功', 'data': edit_data}, trans=False)
            else: return json2dict({'errcode': 3, 'errmsg': '修改失败：%s' % row}, trans=False)


        elif post_param.get('action', '') in self.ajax_act:
            # 参数
            act_id = numeric(post_param.get('id'), 0)
            freq = numeric(post_param.get('freq', 1), 1)
            time_type = numeric(post_param.get('time_type', 0), 0, 10)
            # 检测
            if not act_id: return json2dict({'errcode': 1, 'errmsg': '问卷id出错'}, trans=False)
            aim_data = self.db.list(table='questionnaire', where=act_id)
            if not aim_data: return json2dict({'errcode': 2, 'errmsg': '问卷不存在'}, trans=False)
            # 修改数据
            if post_param.get('action', '') == 'wx_freq':
                edit_data = {'wx_frequency': freq, 'wx_limit_time': time_type}
            elif post_param.get('action', '') == 'dev_freq':
                edit_data = {'device_frequency': freq, 'device_limit_time': time_type}
            elif post_param.get('action', '') == 'ip_freq':
                edit_data = {'ip_frequency': freq, 'ip_limit_time': time_type}
            elif post_param.get('action', '') == 'password':
                edit_data = {'password': post_param.get('password', '')}
            # elif post_param.get('action', '') == 'limit_phone':
            #     pass
            # elif post_param.get('action', '') == 'limit_email':
            #     pass
            elif post_param.get('action', '') == 'limited_time':
                edit_data = {'limited_time': numeric(post_param.get('limited_time'), 0, 1)}
            elif post_param.get('action', '') == 'record_info':
                edit_data = {'record_info': numeric(post_param.get('record_info'), 0, 1)}
            elif post_param.get('action', '') == 'only_wx':
                edit_data = {'only_wx': numeric(post_param.get('only_wx'), 0, 1)}
            elif post_param.get('action', '') == 'only_fans':
                edit_data = {'only_fans': numeric(post_param.get('only_fans'), 0, 1)}
            elif post_param.get('action', '') == 'wx_share':
                edit_data = {'wx_share': numeric(post_param.get('wx_share'), 0, 1)}
            elif post_param.get('action', '') == 'wx_remind':
                edit_data = {'wx_remind': numeric(post_param.get('wx_remind'), 0, 1)}
            elif post_param.get('action', '') == 'category':
                self.db.list(
                    table='category',
                    where="module='research' && id=%s" % post_param.get('category')
                )
                # edit_data = {'wx_remind': numeric(post_param.get('wx_remind'), 0, 1)}

            row = self.db.edit('questionnaire', edit_data, 'id=%s' % act_id)
            if isinstance(row, int): return json2dict({'errcode': 0, 'errmsg': '修改成功', 'data': edit_data}, trans=False)
            else: return json2dict({'errcode': 3, 'errmsg': '修改失败：%s' % row}, trans=False)

        else:
            # 文章数据
            if action == "edit":
                from kyger.research import Research
                research_data = Research(self.db, self.kg).single(research_id, date='%Y-%m-%d %H:%M')
                if not research_data: return alert(msg="该问卷不存在", act=3)
            elif action == 'copy':
                copy_data = self.db.list(table='questionnaire', where=copy_id, shift=1)
                if not copy_data: return alert(msg="复制的目标问卷不存在", act=3)
                del copy_data['id']
                current = int(self.kg['run_start_time'][1])
                copy_data['update_time'], copy_data['update_time'] = (current, current)
                r_id = self.db.add('questionnaire', copy_data)
                from kyger.research import Research
                research_data = Research(self.db, self.kg).single(r_id, date='%Y-%m-%d %H:%M')
            else:
                cate = self.db.list(table='category', where='module="research" && level=1', order='id ASC', shift=1)
                if not cate: return alert(msg="问卷调查没有栏目", act=3)
                insert_data = {
                    'webid': self.kg['web']['id'],
                    "category": json2dict([cate['id']]),
                    "title": '问卷标题',
                    'authority': json2dict(['all']),
                    'description': '感谢您能抽出几分钟时间来参加本次答题，现在我们就马上开始吧！',
                    'normal_end': '您已完成本次问卷，感谢您的帮助与支持',
                    'early_closure': '不好意思，您不太适合本次调查，谢谢您的参与',
                    'multiple_pages': 0,
                    'wx_limit_time': 0,
                    'wx_frequency': 0,
                    'device_limit_time': 0,
                    'device_frequency': 0,
                    'ip_limit_time': 0,
                    'ip_frequency': 0,
                    'password': '',
                    'limited_phone': json2dict([]),
                    'limited_email': json2dict([]),
                    'limited_time': 0,
                    'start': 0,
                    'end': 0,
                    'only_wx': 0,
                    'record_info': 0,
                    'enforce': 0,
                    'only_fans': 0,
                    'icon':'/static/image/admin_default_image.png',
                    'wx_share': 1,
                    'wx_remind': 0,
                    'audit': 0,
                    'published':0,
                    'recycle': 0,
                    'update_time': int(self.kg['run_start_time'][1]),
                    'addtime': int(self.kg['run_start_time'][1])
                }
                r_id = self.db.add('questionnaire', insert_data)
                from kyger.research import Research
                research_data = Research(self.db, self.kg).single(r_id, date='%Y-%m-%d %H:%M')

            # 数据整形
            data = {
                "id": research_data.get("id", 0),
                "category": research_data.get("category", []),
                "title": research_data.get("title", ''),
                'authority': research_data.get('authority', []),
                'description': research_data.get('description', ''),
                'normal_end': research_data.get('normal_end', ''),
                'early_closure': research_data.get('early_closure', ''),
                'multiple_pages': research_data.get('multiple_pages', 0),
                'wx_limit_time': research_data.get('wx_limit_time', 0),
                'wx_frequency': research_data.get('wx_frequency', 1),
                'device_limit_time': research_data.get('wx_limit_time', 0),
                'device_frequency': research_data.get('device_frequency', 1),
                'ip_limit_time': research_data.get('wx_limit_time', 0),
                'ip_frequency': research_data.get('ip_frequency', 1),
                'password': research_data.get('password', ''),
                'limited_phone': research_data.get('limited_phone', []),
                'limited_email': research_data.get('limited_email', []),
                'limited_time': research_data.get('limited_time', 0),
                'start': research_data.get('start', int(self.kg['run_start_time'][1])),
                'end': research_data.get('end', int(self.kg['run_start_time'][1]) + 86400 * 30),
                'only_wx': research_data.get('only_wx', 0),
                'record_info': research_data.get('record_info', 0),
                'enforce': research_data.get('enforce', 0),
                'only_fans': research_data.get('only_fans', 0),
                'icon': research_data.get('icon', '/static/image/admin_default_image.png"'),
                'wx_share': research_data.get('wx_share', 1),
                'wx_remind': research_data.get('wx_remind', 0),
                'audit': research_data.get('audit', 0),
                'published': research_data.get('audit', 0),
                'recycle': research_data.get('recycle', 0),
                'update_time': research_data.get('recycle', 0),
                'addtime': research_data.get('addtime', 0),

            }
            # 获取栏目列表
            from kyger.category import Category
            category_list = Category(self.db, self.kg).rank(cid="research")
            from copy import deepcopy
            category_data_copy = deepcopy(category_list)
            for var in category_data_copy:
                if var['template']: category_list.pop(category_list.index(var))
            category_list.insert(0, {"id": 0, "title": "请选择栏目", "level": 1})
            # 获取用户等级
            rank = self.db.list(table='rank', where='webid=%s && enable=1' % self.kg['web']['id'])
            return template(assign={'data': data, 'category': category_list, 'action': action, 'rank': rank})


