import time
import json
from utils.base import APIView
from gm_upload import upload, upload_file
from openpyxl import load_workbook


class VirtualVote(APIView):

    def post(self, request):
        
        xls_file = request.FILES.get('file')
        if not xls_file:
            return {'message': u'上传失败，请重新上传', 'code': 500}

        wb = load_workbook(xls_file)
        data = wb.get_sheet_by_name(wb.get_sheet_names()[0])

        columns = [item for item in data.columns]
        column_data = columns[0]

        column_data = [item.value for item in column_data]
        if '用户id' not in column_data:
            
            return {'message': u'文件数据格式错误，请确保内容中有”用户id“标题', 'code': 500}
        user_ids = []
        for item in column_data:
            try:
                user_id = int(item)
                user_ids.append(user_id)
            except:
                continue
        if not user_ids:
            return {'message': u'上传失败，文件第一列不存在user_id数据', 'code': 500}

        self.rpc['venus/sun/tools/virtual_vote'](user_ids=user_ids).unwrap()

        return {'message': u'上传成功', 'code': 200}


class BatchUpdateTopicTag(APIView):

    def post(self, request):
        
        xls_file = request.FILES.get('file')
        if not xls_file:
            return {'message': u'上传失败，请重新上传', 'code': 500}

        wb = load_workbook(xls_file)
        data = wb.get_sheet_by_name(wb.get_sheet_names()[0])

        rows_data = [item.value for row in data.rows for item in row if item.value]

        topic_infos = []
        topic_tag_info = {}
        for index, item in enumerate(rows_data):
            if index == len(rows_data) - 1:
                topic_infos.append(topic_tag_info)
            if item.startswith('http:'):
                if topic_tag_info.get('url'):
                    topic_infos.append(topic_tag_info)
                
                topic_tag_info = {}
                topic_tag_info['url'] = item.split('-')[0].replace('http://alpha.iyanzhi.com/', '')
                continue
            if item.split(':')[-1] and topic_tag_info.get('url'):
                if not topic_tag_info.get('tags'):
                    topic_tag_info['tags'] = [item.split(':')[-1]]
                else:
                    topic_tag_info['tags'].append(item.split(':')[-1])
        
        self.rpc['venus/sun/tools/batch_update_topic_tags'](topic_infos=topic_infos).unwrap()

        return {'message': u'上传成功', 'code': 200}


class BatchCreateTopicWithAiFashionTag(APIView):

    def post(self, request):
        
        json_file = request.FILES.get('file')
        tag_infos = request.POST.get('tag_infos', '[]')
        if not json_file and not tag_infos:
            return {'message': u'上传失败，请重新上传', 'code': 500}

        if json_file:
            json_data = json.load(json_file)
            self.rpc['venus/sun/tools/batch_create_topic_with_ai_fashion_tag'](infos=json_data).unwrap()
        if tag_infos:
            json_data = json.loads(tag_infos)
            self.rpc['venus/sun/tools/batch_create_topic_with_ai_fashion_tag'](infos=json_data).unwrap()

        return {'message': u'上传成功', 'code': 200}


class AddVirtFans(APIView):

    def post(self, request):

        xls_file = request.FILES.get('file')
        if not xls_file:
            return {'message': u'上传失败，请重新上传', 'code': 500}

        wb = load_workbook(xls_file)
        data = wb.get_sheet_by_name(wb.get_sheet_names()[0])

        columns = [item for item in data.columns]

        user_id_column = [item.value for item in columns[0]]
        fans_num_column = [item.value for item in columns[1]]
        user_id_fans_num_data = list(zip(user_id_column[1:], fans_num_column[1:]))

        #做一次数据清洗。 避免文件中的空行
        user_id_fans_num_data = [
            (user_id, fans_num) for user_id, fans_num in user_id_fans_num_data
            if isinstance(user_id, int) and isinstance(fans_num, int)
        ]

        try:
             self.rpc['venus/sun/tools/add_virt_fans'](data=user_id_fans_num_data).unwrap()
        except:
            return {'message': u'处理失败', 'code': 500}
        return {'message': u'处理成功', 'code': 200}
