# -*- coding:utf-8 -*-
"""
DATE：2024/3/5 16:27

"""
import pendulum
from uuid import uuid4
from unify_api.constants import OSS_NEWS
from pot_libs.logger import log
from unify_api.modules.common.procedures.file_operate_pds import upload_file
from pot_libs.mysql_util.mysql_util import MysqlUtil
from pot_libs.settings import SETTING


async def upload_file_helper(file):
    is_upload, file_url = False, ""
    file_name = file.name
    file_name_lst = file_name.rsplit(".", 1)
    if len(file_name_lst) <= 1:
        return False, file_url

    if file.body:
        now_dt = pendulum.now()
        yr, month = now_dt.year, now_dt.month
        file_url = f"{OSS_NEWS}/{yr}/{month}/{uuid4()}.{file_name_lst[1]}"

        log.info(f"准备上传文件 {file_name} {file_url}")
        is_upload = await upload_file(file, file_url,
                                      bucket=SETTING.qingstor_public_bucket)

    return is_upload, file_url


async def upload_news_qs(request):
    """附件上传"""
    url_article, url_cover = "", ""
    news_file = request.files.getlist("file1")[0]
    file2_lst = request.files.getlist("file2")
    cover_file = file2_lst[0] if file2_lst else None
    if not news_file:
        return False, url_article, url_cover

    if cover_file and news_file.name == cover_file.name:
        return False, url_article, url_cover

    news_upload, url_article = await upload_file_helper(news_file)
    if not news_upload or not url_article:
        log.info(f"上传文章失败, url {url_article}")
        return False, url_article, url_cover

    if not cover_file:
        log.info(f"没有上传文章封面｜删除文章封面成功")
        return True, url_article, url_cover

    cover_upload, url_cover = await upload_file_helper(cover_file)
    if all([news_upload, url_article, cover_upload, url_cover]):
        log.info(f"上传文章和封面成功 {url_article} {url_cover}")
        return True, url_article, url_cover

    log.info(f"上传文章或封面失败 {url_article} {url_cover}")
    return False, url_article, url_cover


async def save_news_info(news_info, news_url, cover_url):
    sql = "INSERT INTO official_web.news_info (title, news_type, news_url, " \
          "cover_url, keywords, contents, pub_time) " \
          "VALUES (%s, %s, %s, %s, %s, %s, %s);"
    async with MysqlUtil(db="official_web") as conn:
        await conn.execute(sql, (news_info["title"], news_info["news_type"],
                                 news_url, cover_url, news_info["keywords"],
                                 news_info["contents"],
                                 str(news_info["pub_time"]),))


async def update_news_info(news_info, news_url, cover_url):
    sql = "UPDATE official_web.news_info " \
          "SET title=%s, news_type=%s, news_url=%s, cover_url=%s, " \
          "keywords=%s, contents=%s, pub_time=%s WHERE id=%s;"
    async with MysqlUtil(db="official_web") as conn:
        await conn.execute(sql, (news_info["title"], news_info["news_type"],
                                 news_url, cover_url, news_info["keywords"],
                                 news_info["contents"],
                                 str(news_info["pub_time"]),
                                 news_info["news_id"]))


async def update_news_seo(news_id, keywords, contents):
    async with MysqlUtil(db="official_web") as conn:
        sql = "UPDATE official_web.news_info " \
              "SET keywords=%s, contents=%s WHERE id=%s;"
        return await conn.execute(sql, (news_id, keywords, contents,))


async def delete_news(news_id):
    async with MysqlUtil(db="official_web") as conn:
        sql = "DELETE FROM official_web.news_info WHERE id=%s;"
        await conn.execute(sql, (news_id,))
        sql = "SELECT 1 FROM official_web.news_info WHERE id=%s LIMIT 1;"
        rlt = await conn.execute(sql, (news_id,))
        return False if rlt else True


async def top_news(news_id, top):
    async with MysqlUtil(db="official_web") as conn:
        sql = "UPDATE official_web.news_info SET top=%s WHERE id=%s;"
        await conn.execute(sql, (top, news_id,))
        sql = "SELECT 1 FROM official_web.news_info WHERE id=%s AND top=%s;"
        return await conn.execute(sql, (news_id, top,))


async def load_news_pages(params):
    page_num, page_size = params["page_num"], params["page_size"]
    news_type, se_title = params["news_type"], params["se_title"]
    s_dts, e_dts = params["s_dts"], params["e_dts"]
    offsets = 0 if page_num == 0 else (page_num - 1) * page_size
    conds = []
    if news_type:
        conds.append(f"news_type={news_type}")
    if s_dts:
        s_dt = pendulum.parse(s_dts, tz="Asia/Shanghai")
        conds.append(f"pub_time>='{str(s_dt)}'")
    if e_dts:
        e_dt = pendulum.parse(e_dts, tz="Asia/Shanghai")
        conds.append(f"pub_time<'{str(e_dt)}'")
    if se_title:
        conds.append(f"title LIKE '%%{se_title}%%'")

    conds_str = " WHERE " + " AND ".join(conds) if conds else ""
    async with MysqlUtil(db="official_web") as conn:
        sql = f"SELECT count(*) FROM official_web.news_info {conds_str};"
        total = await conn.fetch_value(sql)

        sql = f"SELECT id, title, author, news_type, pub_time, top " \
              f"FROM official_web.news_info {conds_str} " \
              f"ORDER BY pub_time DESC, id LIMIT {page_size} OFFSET {offsets};"
        articles = await conn.fetchall(sql)
        return total, articles


async def load_news_info(news_id):
    sql = "SELECT * FROM official_web.news_info WHERE id=%s;"
    async with MysqlUtil(db="official_web") as conn:
        return await conn.fetchone(sql, (news_id,))
