#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tablib
from django.conf import settings
from gm_upload import upload_file, IMG_TYPE
from helios import create_default_invoker
from gm_types.gaia import TAG_TYPE
from gm_types.wiki import TREATMENT_TYPE

from api.models import Tag
from hera.management.commands.utils import get_mail
from wiki.models import Item
import xml.dom.minidom as Dom
import re


def items_all():
    objs = Item.objects.filter(is_online=1)
    doc = Dom.Document()
    root_node = doc.createElement("urlset")
    root_node.setAttribute("content_method", "full")
    loc = "https://m.igengmei.com/base_wiki/item/{}/"
    doc.appendChild(root_node)
    for obj in objs:
        url_node = doc.createElement("url")
        root_node.appendChild(url_node)
        keys = ['loc', 'changefreq']
        items = {'loc': loc.format(obj.id), "changefreq": "weekly"}
        create_node(keys, items, doc, url_node)
        data_node = doc.createElement("data")
        url_node.appendChild(data_node)
        display_node = doc.createElement('display')
        data_node.appendChild(display_node)
        mUrl = "https://m.igengmei.com/base_wiki/item/{}/"
        url = "https://www.igengmei.com/wiki/{}/"
        prices = re.findall("\d+", obj.price)
        if prices:
            low_price = prices[0]
            high_price = prices[-1]
        else:
            low_price = high_price = 0
        keys = ['id', 'url', 'mUrl', 'name', 'alias', 'description',
                'lowPrice', 'highPrice', 'advantage', 'disadvantage', 'suitCrowds', 'tabooCrowds', 'safety', 'operationMethod', 'duration']

        items = {"id": obj.id, 'url': url.format(obj.id), 'mUrl': mUrl.format(obj.id), 'name': obj.name,
                 "alias": obj.other_name, "description": obj.description, "lowPrice": low_price, "highPrice": high_price,
                 "advantage": obj.advantage, "disadvantage": obj.disadvantage, "suitCrowds": obj.fit_people, "tabooCrowds": obj.avoid_people,
                 "operationMethod": TREATMENT_TYPE.getDesc(obj.treatment_method), "duration": obj.maintain_time
                 }
        create_node(keys, items, doc, display_node)

        #通过项目名称搜索对应的tag
        tag = Tag.objects.filter(name__contains=obj.name, is_online=1, tag_type__in=[TAG_TYPE.BODY_PART, TAG_TYPE.BODY_PART_SUB_ITEM, TAG_TYPE.ITEM_WIKI]).order_by("tag_type").last()
        categoryFirstName = '其他'
        categorySecondName = categoryThirdName = ''
        diary_info = [{}]
        if tag:
            if tag.tag_type == '1':
                categoryFirstName = tag.name
            elif tag.tag_type == '2':
                first_tags = tag.online_parent_tags()
                if first_tags:
                    categoryFirstName = first_tags[0].name
            elif tag.tag_type == '3':
                second_tags = tag.online_parent_tags()
                second_tag = second_tags[0] if second_tags else ''
                first_tags = second_tag.online_parent_tags() if second_tag else ''
                first_tag = first_tags[0] if first_tags else ''
                categoryFirstName = first_tag.name if first_tag else '其他'
                categorySecondName = second_tag.name if second_tag else ''
                categoryThirdName = tag.name

            # 获取相关日记本信息
            rpc_client = create_default_invoker(debug=settings.DEBUG)
            diary_info = rpc_client['diary/wiki/relation_diary_info'](tag_id=tag.id).unwrap()
        keys = ["id", "url", "mUrl", "title", "description", "firstTime", "updateTime", "imageBefore", "imageAfter", "viewCount"]
        for diary in diary_info:
            diaryList_node = doc.createElement("diaryList")
            display_node.appendChild(diaryList_node)
            create_node(keys, diary, doc, diaryList_node)
        keys = ["categoryFirstName", "categorySecondName", "categoryThirdName"]
        items = {"categoryFirstName": categoryFirstName, "categorySecondName": categorySecondName, "categoryThirdName": categoryThirdName}
        create_node(keys, items, doc, display_node)

        # 公司信息
        provider_node = doc.createElement("provider")
        keys = ["brand", "logo", "showurl"]
        items = {"brand": u"更美", "logo": "https://heras.igengmei.com/2020/02/26/4dc1224831", "showurl": "www.igengmei.com"}
        create_node(keys, items, doc, provider_node)
        display_node.appendChild(provider_node)

    with open('./wiki_item.xml', 'wb') as f:
        f.write(doc.toprettyxml(indent="\t", newl="\n", encoding="utf-8"))
    url = upload_file('./wiki_item.xml', IMG_TYPE.CONSULTWIKI)
    dt_result = tablib.Dataset()
    dt_result.headers = ['url']
    dt_result.append((url, ))
    get_mail(u'百科同步数据.xlsx', u'百科数据链接', [u'sunyinghe@gmei.com', u'songzhenqi@igengmei.com'], dt_result.xlsx).send()


def create_node(keys,  items, doc, parent_note):
    for key in keys:
        child_note = doc.createElement(key)
        if items.get(key):
            val = doc.createTextNode(str(items.get(key)))
            child_note.appendChild(val)
        parent_note.appendChild(child_note)