import json
import logging
import smtplib
import time
import traceback
import datetime
import random
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
import re
import requests
from pypinyin import lazy_pinyin
import gevent

logger = logging.getLogger(__name__)


def send_email_tome():
    try:
        from_addrs = 'lixiaofang@igengmei.com'
        password = 'EzJzSRyEG4Jibuy9'
        toaddrs = "lixiaofang@igengmei.com"

        content = '爬取新氧热搜前100的词召回的商品，内容详见表格'
        text_apart = MIMEText(content, 'plain', "utf-8")

        zip_file_week = 'result1.csv'
        zip_apart_week = MIMEApplication(open(zip_file_week, 'rb').read())
        zip_apart_week.add_header('Content-Disposition', 'attachment', filename=zip_file_week)

        m = MIMEMultipart()
        m.attach(text_apart)
        m.attach(zip_apart_week)

        m['From'] = formataddr(("李小芳", from_addrs))
        m["To"] = formataddr(("李小芳", toaddrs))
        m['Subject'] = '新氧商品信息'

        try:
            server = smtplib.SMTP_SSL('smtp.exmail.qq.com', 465)
            server.login(from_addrs, password)
            server.sendmail(from_addrs, [toaddrs], m.as_string())
            print('success')
            server.quit()

        except smtplib.SMTPException as e:
            print('error', e)

    except Exception as e:
        print(str(e))
        logger.error("catch exception,main:%s" % traceback.format_exc())


def get_keynote_sentence(content):
    try:
        ss = content.encode('utf-16', 'surrogatepass').decode('utf-16')
        dr = re.compile(r"<[^>]+>", re.S)
        str_re = dr.sub("", ss)
        para = re.sub('([；。！？\?])([^”’])', r"\1\n\2", str_re)  # 单字符断句符
        para = re.sub('(\.{6})([^”’])', r"\1\n\2", para)  # 英文省略号
        para = re.sub('(\…{2})([^”’])', r"\1\n\2", para)  # 中文省略号
        para = re.sub('([；。！？\?][”’])([^，。！？\?])', r'\1\n\2', para)
        para = para.rstrip()  # 段尾如果有多余的\n就去掉它
        return para
    except:
        logging.error("catch exception,logins:%s" % traceback.format_exc())
        return []


def get_service_info(query="", city_name="", get_data_file=None):
    print("get_service_info")
    break_flat = False
    other_city_count = 0
    for page in range(0, 3000, 10):
        if break_flat == False and other_city_count < 10:
            s = random.random()
            # time.sleep(s)
            url = 'https://backend.igengmei.com/api/janus/search/v7/content?platform=iPhone&os_version=13.6.1&version=7.46.0&model=iphone%20X%20++&release=1&idfa=057F28DF-20B8-488F-A285-931367FCC110&idfv=74FE9CFB-DAD2-4379-B8F8-FC656F38BCA5&device_id=057F28DF-20B8-488F-A285-931367FCC110&uqid=47517624-F42B-469C-96EC-3BF936E44613&channel=App%20Store&app_name=gengmeiios&current_city_id={}&lat=39.98323941854652&lng=116.4880417854629&is_WiFi=1&hardware_model=iPhone12,1&ua=Mozilla/5.0%20(iPhone;%20CPU%20iPhone%20OS%2013_6_1%20like%20Mac%20OS%20X)%20AppleWebKit/605.1.15%20(KHTML,%20like%20Gecko)%20Mobile/15E148&sm_idfa=(null)&trace_id=2021/07/22/0956/53f8f1c10868&area_id=worldwide&count=10&is_first=1&is_gray=1&max_price=100000&min_price=0&offset={}&order_by=0&query={}&show_mode=1&size=10&tab_type=0'.format(
                city_name, page, query)
            response_res = requests.get(url, verify=False, timeout=30)
            time.sleep(1)
            if response_res.status_code == 200 and response_res.text:
                response = json.loads(response_res.text)
                responseData = response.get("data", {}).get("cards")
                for item in responseData:
                    if item.get("title") == "商品":
                        if len(item.get("feed", [])):
                            for service_data in item.get("feed", []):
                                city_id = service_data.get("hospital_info", {}).get("city_id")
                                if str(city_id) == str(city_name):
                                    service_info = dict()
                                    service_info['skuid'] = service_data.get("service_item_id")
                                    service_info['美购id'] = service_data.get("service_id")
                                    service_info['医生名称'] = service_data.get("doctor_info", {}).get("name")
                                    service_info['医院名称'] = service_data.get("doctor_hospital_name")
                                    service_info['sku原价'] = service_data.get("price_info", {}).get(
                                        "original_payment_desc")
                                    service_info['sku活动价'] = service_data.get("price_info", {}).get(
                                        "total_payment_desc")
                                    # service_info['机构等级'] = service_data.get("avg_score")
                                    service_info['美购名称'] = get_keynote_sentence(service_data.get("title"))
                                    service_info['销量'] = service_data.get("sell_num_desc", 0)
                                    service_info['可用尾款券'] = []
                                    service_info['可领取预约金优惠券'] = []
                                    icon_data = service_data.get("sales_info", [])
                                    # print(icon_data)
                                    for sales_item in icon_data:
                                        if int(sales_item.get("type")) == 1 or int(sales_item.get("type")) == 3:
                                            service_info['可用尾款券'].append(sales_item.get("desc"))
                                        elif int(sales_item.get("type")) == 2:
                                            service_info['可领取预约金优惠券'].append(sales_item.get("desc"))
                                        else:
                                            pass
                                    service_info['query词'] = query
                                    service_info['城市'] = city_name
                                    service_info['平台'] = "更美"
                                    service_info[
                                        '链接'] = "https://m.igengmei.com/promotion/{}?sku_id={}&distribute_type=1&distribute_id=30775628&is_share=1".format(
                                        service_info['美购id'], service_info['skuid'])

                                    get_data_file.write(json.dumps(service_info))
                                    get_data_file.write("\n")
                                    print("write success ", query, city_name)
                                else:
                                    other_city_count += 1

                        else:
                            print("break")
                            break_flat = True
                            break
            else:
                print(city_name, query, "爬取失败")
        else:
            print(page, city_name, query, "本地已爬完")


def main():
    begin = time.time()
    nowday = datetime.datetime.now()
    today = str(nowday).split()[0]
    file_name = "test_gengmei_save_data_" + str(today) + ".txt"
    get_data_file = open(file_name, "a+", encoding="utf-8")

    keywords = ['瘦脸针', '双眼皮', '光子嫩肤', '吸脂', '水光针', '玻尿酸', '热玛吉',
                '脱毛', '瘦腿针', '鼻综合', '瘦肩针', '下颌角', '线雕', '超声刀',
                '美白针', '眼综合', '隆鼻', '菲洛嘉', '下巴', '热拉提', '点阵激光',
                '面部吸脂', '开内眼角', '嗨体', '牙齿矫正', '皮秒', '超皮秒', '植发',
                '黄金微针', '隆胸', '微针', '光子嫩肤', '祛斑', '小气泡', '嗨体熊猫针',
                '熊猫针', '果酸焕肤', '自体脂肪隆胸', '7D聚拉提', '瘦脸', '埋线双眼皮',
                '菲洛嘉水光针', '双眼皮修复', '欧洲之星', '脂肪填充', '溶脂针', '法令纹',
                '鼻基底', '全切双眼皮', '颧骨内推', '鼻子', '光子嫩肤m22', '下颌缘提升',
                'm22', '鼻翼缩小', '欧洲之星fotona4d', '自体脂肪全面部填充', '玻尿酸丰唇',
                '水光', '嗨体祛颈纹', '假体隆胸', '英诺小棕瓶', '黄金微雕', '眼袋', '乔雅登',
                '除皱', '颧骨', '艾莉薇', '抽脂', '瘦腿', '玻尿酸丰下巴', '纹眉', '伊肤泉微针',
                '美白', '厚唇改薄', '面部线雕', '祛疤', '伊婉V', '超皮秒祛斑', '除皱针', '开眼角',
                '海菲秀', '假体下巴', '刷酸', '泪沟', '拉皮', '全身吸脂', '缩鼻翼']

    city_list = ['合肥市', '芜湖市', '蚌埠市', '淮南市', '马鞍山市', '淮北市', '铜陵市', '安庆市', '滁州市', '阜阳市', '宿州市', '六安地区', '亳州市', '池州市',
                 '宣城市', '福州市', '厦门市', '莆田市', '三明市', '泉州市', '漳州市', '南平市', '龙岩市', '宁德市', '韶关市', '东莞市', '中山市', '珠海市',
                 '佛山市', '汕头市', '江门市', '湛江市', '茂名市', '肇庆市', '惠州市', '梅州市', '河源市', '阳江市', '清远市', '潮州市', '揭阳市', '南宁市',
                 '柳州市', '桂林市', '梧州市', '北海市', '钦州市', '贵港市', '玉林市', '百色市', '贵阳市', '遵义市', '六盘水市', '铜仁地区', '毕节地区', '兰州市',
                 '张掖市', '平凉市', '庆阳市', '开封市', '洛阳市', '平顶山市', '安阳市', '新乡市', '焦作市', '濮阳市', '许昌市', '漯河市', '三门峡市', '南阳市',
                 '商丘市', '信阳市', '周口市', '驻马店市', '黄石市', '荆州市', '宜昌市', '襄阳市', '天门市', '十堰市', '荆门市', '孝感市', '黄冈市', '咸宁市',
                 '随州市', '仙桃市', '潜江市', '株洲市', '衡阳市', '益阳市', '邵阳市', '湘潭市', '岳阳市', '常德市', '郴州市', '永州市', '怀化市', '娄底市',
                 '石家庄市', '唐山市', '秦皇岛市', '邯郸市', '邢台市', '保定市', '张家口市', '承德市', '衡水市', '廊坊市', '沧州市', '哈尔滨市', '齐齐哈尔市',
                 '鸡西市', '鹤岗市', '大庆市', '佳木斯市', '七台河市', '牡丹江市', '绥化市', '海口市', '三亚市', '东方市', '苏州市', '无锡市', '常州市', '南通市',
                 '盐城市', '徐州市', '连云港市', '扬州市', '淮安市', '镇江市', '泰州市', '宿迁市', '南昌市', '景德镇市', '萍乡市', '九江市', '新余市', '鹰潭市',
                 '赣州市', '吉安市', '宜春市', '抚州市', '上饶市', '长春市', '吉林市', '四平市', '通化市', '白山市', '松原市', '沈阳市', '大连市', '鞍山市',
                 '抚顺市', '丹东市', '锦州市', '营口市', '阜新市', '辽阳市', '铁岭市', '朝阳市', '葫芦岛市', '呼和浩特市', '包头市', '赤峰市', '通辽市', '鄂尔多斯市',
                 '呼伦贝尔市', '巴彦淖尔市', '银川市', '西宁市', '自贡市', '绵阳市', '德阳市', '乐山市', '南充市', '攀枝花市', '泸州市', '广元市', '遂宁市', '内江市',
                 '眉山市', '宜宾市', '广安市', '达州市', '雅安市', '巴中市', '资阳市', '济南市', '青岛市', '枣庄市', '烟台市', '淄博市', '临沂市', '东营市',
                 '潍坊市', '济宁市', '泰安市', '威海市', '日照市', '德州市', '聊城市', '滨州市', '菏泽市', '宝鸡市', '咸阳市', '汉中市', '渭南市', '延安市',
                 '安康市', '太原市', '晋中市', '运城市', '大同市', '阳泉市', '长治市', '晋城市', '临汾市', '乌鲁木齐市', '石河子市', '昆明市', '曲靖市', '玉溪市',
                 '保山市', '昭通市', '丽江市', '宁波市', '温州市', '嘉兴市', '金华市', '台州市', '湖州市', '绍兴市', '舟山市', '衢州市', '丽水市', '台北市',
                 '台中市', '台北县']

    for city_name in city_list:
        for word in keywords:
            get_service_info(query=word, city_name="".join(lazy_pinyin(city_name)), get_data_file=get_data_file)

    get_data_file.close()
    print(time.time() - begin)


if __name__ == '__main__':
    main()
