#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import re
from zhon import (
    hanzi,
    pinyin,
)

from alpha_types.venus.enum import (
    SKIN_ALL_CLASSIFY,
    SKIN_CHECK_ITEMIZE_TYPE,
    SKIN_QUALITY_COLOR_DESC,
    SKIN_QUALITY_TEMPERATURE,
    SKIN_QUALITY_OIL_LEVEL,
    SKIN_PORE_SEVERITY,
    SKIN_ROUGHNESS_TYPE,
    SKIN_ACNE_TYPE,
    SKIN_BLACK_HEADS_TYPE,
    SKIN_DARK_CIRCLE_TYPE,
)

from utils.base import APIView, get_offset_count
from utils.logger import error_logger, info_logger


class SkinCheckPictorial(APIView):

    def get(self, request):
        try:
            data = self.rpc['venus/sun/skin_check/get_pictorial_info']().unwrap()

            for item in data:
                if item.get("skin_classify") == SKIN_ALL_CLASSIFY.SKIN_QUALITY:
                    item["skin_classifiy_desc"] = u"肤色"

        except Exception as e:
            error_logger.error(u'获取测肤榜单配置失败%s', e)
            raise

        return data

    def post(self, request):
        """
        榜单信息创建 or 更新
        :param request:
        :return:
        """
        _data = json.loads(request.POST.get("pictorial_info") or "[]")

        # 对变更数据做一层封装
        modify_data = []
        for info in _data:
            _skin_classify = info.get("skin_classify", "")
            if _skin_classify in SKIN_ALL_CLASSIFY:
                _data = {
                    "skin_classify": _skin_classify,
                    "url": info.get("url", ""),
                    "content": info.get("content", ""),
                }
                modify_data.append(_data)

        info_logger.info("skin_check pictorial modify data: {}".format(json.dumps(modify_data)))

        if modify_data:
            try:
                self.rpc['venus/sun/skin_check/pictorial_update_or_create'](
                    modify_data=modify_data
                ).unwrap()

            except Exception as e:
                error_logger.error(u'变更测肤榜单配置失败%s', e)
                raise

        return {
            "message": u"操作成功",
        }


class SkinCheckConfig(APIView):

    # 大类对应的各小类枚举类型
    enum_mapping = {
        SKIN_CHECK_ITEMIZE_TYPE.SKIN_COLOR: SKIN_QUALITY_COLOR_DESC,  # 肤色
        SKIN_CHECK_ITEMIZE_TYPE.TEMPERATURE: SKIN_QUALITY_TEMPERATURE,  # 色温
        SKIN_CHECK_ITEMIZE_TYPE.OIL_LEVEL: SKIN_QUALITY_OIL_LEVEL,  # 干油性
        SKIN_CHECK_ITEMIZE_TYPE.SEVERITY: SKIN_PORE_SEVERITY,  # 毛孔
        SKIN_CHECK_ITEMIZE_TYPE.ROUGHNESS: SKIN_ROUGHNESS_TYPE,  # 粗糙度
        SKIN_CHECK_ITEMIZE_TYPE.BLACK_HEAD: SKIN_BLACK_HEADS_TYPE,  # 黑头
        SKIN_CHECK_ITEMIZE_TYPE.DARK_CIRCLE: SKIN_DARK_CIRCLE_TYPE,  # 黑眼圈
        SKIN_CHECK_ITEMIZE_TYPE.ACNE: SKIN_ACNE_TYPE,  # 痘痘
    }

    def _text_convert(self, text):
        """
        文案修正
        :param text:
        :return:
        """
        return text.replace(" ", "")

    def _input_string_check(self, text, check_str):
        """
        输入内容标签符号校验，是否都是 check_str
        :param text:
        :param check_str:
        :return:  没有标签符号，默认返回True
        """
        if re.search("[{}]+".format(hanzi.punctuation), text):  # 如果存在中文标点符号
            return False

        punctuation_marks = re.findall("[{}]+".format(pinyin.punctuation), text)  # 英文标点符号

        if len(punctuation_marks) == len(text):  # 如果全部是英文标点符号
            return False

        elif punctuation_marks:  # 判断是否都是以 check_str 分隔
            return all(map(lambda p: p == check_str, punctuation_marks))

        return True

    def get(self, request):

        data = {
            "skin_color": {},  # 肤色
            "temperature": {},  # 色温
            "oil_level": {},  # 干油性
            "severity": {},  # 毛孔
            "roughness": {},  # 粗糙度
            "black_head": {},  # 黑头
            "dark_circle": {},  # 黑眼圈
            "acne": {},  # 痘痘
            "type_1": [
                SKIN_CHECK_ITEMIZE_TYPE.SKIN_COLOR,
                SKIN_CHECK_ITEMIZE_TYPE.TEMPERATURE,
                SKIN_CHECK_ITEMIZE_TYPE.OIL_LEVEL,
            ],
            "type_2": [
                SKIN_CHECK_ITEMIZE_TYPE.SEVERITY,
                SKIN_CHECK_ITEMIZE_TYPE.ROUGHNESS,
            ],
            "type_3": [
                SKIN_CHECK_ITEMIZE_TYPE.BLACK_HEAD,
                SKIN_CHECK_ITEMIZE_TYPE.DARK_CIRCLE,
                SKIN_CHECK_ITEMIZE_TYPE.ACNE,
            ],
        }

        try:
            venus_data = self.rpc['venus/sun/skin_check/all_config']().unwrap()
            data.update({
                "skin_color": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.SKIN_COLOR, {}),  # 肤色
                "temperature": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.TEMPERATURE, {}),  # 色温
                "oil_level": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.OIL_LEVEL, {}),  # 干油性
                "severity": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.SEVERITY, {}),  # 毛孔
                "roughness": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.ROUGHNESS, {}),  # 粗糙度
                "black_head": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.BLACK_HEAD, {}),  # 黑头
                "dark_circle": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.DARK_CIRCLE, {}),  # 黑眼圈
                "acne": venus_data.get(SKIN_CHECK_ITEMIZE_TYPE.ACNE, {}),  # 痘痘
            })
        except Exception as e:
            error_logger.error(u'获取测肤配置失败%s', e)
            raise

        return data

    def post(self, request):
        """
        配置 创建/修改
        :param request:
        :return:
        """
        _data = json.loads(request.POST.get("config_info") or "[]")

        # 对变更数据做一层封装
        modify_data = []
        _raise_message = ""

        for info in _data:
            _fitting = self._text_convert(info.get("fitting", ""))
            _dread = self._text_convert(info.get("dread", ""))
            _itemize_type = info.get("owner_enum", "")
            _enum_value = info.get("enum_value", "")
            maping_enum = self.enum_mapping.get(_itemize_type, None)

            if not self._input_string_check(_fitting, ","):
                _raise_message = u"{} {} 宜".format(
                    _itemize_type and SKIN_CHECK_ITEMIZE_TYPE.getDesc(_itemize_type) or u"",
                    _enum_value and maping_enum and maping_enum.getDesc(_enum_value) or u""
                )

            elif not self._input_string_check(_dread, ","):
                _raise_message = u"{} {} 忌".format(
                    _itemize_type and SKIN_CHECK_ITEMIZE_TYPE.getDesc(_itemize_type) or u"",
                    _enum_value and maping_enum and maping_enum.getDesc(_enum_value) or u""
                )

            if _raise_message:
                break

            _data = {
                "skin_check_itemize_type": _itemize_type,
                "enum_value": _enum_value,
                "fitting": _fitting,
                "dread": _dread,
                "fitting_suggest": info.get("fitting_suggest", ""),
                "dread_suggest": info.get("dread_suggest", ""),
            }
            modify_data.append(_data)

        if _raise_message:
            return {
                "message": u"{} 文案有误！请输入文字，多个文字之间以英文逗号分隔！".format(_raise_message),
            }

        info_logger.info("skin_check config modify data: {}".format(json.dumps(modify_data)))

        if modify_data:
            try:
                self.rpc['venus/sun/skin_check/config_update_or_create'](
                    modify_data=modify_data
                ).unwrap()

            except Exception as e:
                error_logger.error(u'变更测肤配置失败%s', e)
                raise

        return {
            "message": u"操作成功",
        }
