import requests
from django.core.paginator import Paginator
from django.db import transaction

from DCbackend.utils.common import success, fail, pageData
from backend.Form.WechatComplaintForm import WechatComplaintForm
from backend.models import WechatComplaint
#微信模块相关方法
class WechatComplaintService:

    @staticmethod
    @transaction.atomic
    def insertComplaint(request):
        try:
            name = request.POST.get("name")
            if not name:
                return fail("姓名为空")

            phone = request.POST.get("phone")
            if not phone:
                return fail("手机号为空")

            form = WechatComplaintForm(request.POST)
            if form.is_valid():
                complaint = form.save()
                # 发送 HTTP 请求
                email_url = "http://120.46.190.49:9998/apis/SMS/email"
                params = {
                    "email": "qlithyw@shqlsy.com",
                    # "email": "786912717@qq.com",
                    "title": "新投诉通知",
                    "content": f"""
<html>
<body style="font-family: Arial, sans-serif; line-height: 1.6; color: #333;">
    <h2 style="color: #1a5f7a;">新投诉详情</h2>
    <table style="border-collapse: collapse; width: 100%;">
        <tr>
            <td style="padding: 10px; border: 1px solid #ddd;"><strong>姓名：</strong></td>
            <td style="padding: 10px; border: 1px solid #ddd;">{name}</td>
        </tr>
        <tr>
            <td style="padding: 10px; border: 1px solid #ddd;"><strong>电话：</strong></td>
            <td style="padding: 10px; border: 1px solid #ddd;">{phone}</td>
        </tr>
        <tr>
            <td style="padding: 10px; border: 1px solid #ddd;"><strong>公司名称：</strong></td>
            <td style="padding: 10px; border: 1px solid #ddd;">{complaint.corporate_name}</td>
        </tr>
    </table>
    <h3 style="color: #1a5f7a; margin-top: 20px;">投诉内容：</h3>
    <p style="background-color: #f9f9f9; padding: 15px; border-left: 5px solid #1a5f7a;">
        {complaint.content}
    </p>
    <p style="color: #d9534f; font-weight: bold; margin-top: 20px;">请及时处理！</p>
</body>
</html>
"""
                }
                try:
                    response = requests.get(email_url, params=params)
                    response.raise_for_status()
                except requests.RequestException as e:
                    print(f"发送邮件通知失败: {str(e)}")
                return success("感谢您的宝贵建议")
            else:
                return fail("表单验证失败")
        except Exception as e:
            return fail(f'保存失败: {str(e)}')


    @staticmethod
    @transaction.atomic
    def deleteComplaint(request):
        id = request.POST.get("id")
        if not id:
            return fail("id为空")
        WechatComplaint.objects.filter(id=id).update(status = 4)
        return success("删除成功")

    @staticmethod
    def getComplaintList(request):
        page = request.POST.get("page")
        pageSize = request.POST.get("pageSize")
        if page is None:
            page = 1
        if pageSize is None:
            pageSize = 10

        where = {}

        paginator = Paginator(WechatComplaint.objects.filter(**where).exclude(status=4).order_by("-create_time"), pageSize)  # 每页显示10条数据
        page_obj = paginator.get_page(page)
        dataList = []
        for item in page_obj:
            info = WechatComplaintService.getDetail(item)
            dataList.append(info)
        return success(pageData(page, pageSize, paginator.num_pages, paginator.count, dataList))

    @staticmethod
    def getDetail(item: WechatComplaint):
        return {
            "id": item.id,
            'name': item.name,
            'phone': item.phone,
            'corporateName': item.corporate_name,
            'content': item.content,
            'status': item.status,
            'create_time': item.create_time
        }
    @staticmethod
    def getComplaintInfo(request):
        id = request.POST.get("id")
        if not id:
            return fail("id为空")

        complaint = WechatComplaint.objects.filter(id=id).first()
        if complaint:
            info = WechatComplaintService.getDetail(complaint)
            return success(info)
        else:
            return fail("未找到相关投诉")

    @staticmethod
    @transaction.atomic
    def updateComplaint(request):
        id = request.POST.get("id")
        if not id:
            return fail("id为空")
        complaint = WechatComplaint.objects.filter(id=id).first()
        if complaint:
            complaint.name = request.POST.get("name")
            complaint.phone = request.POST.get("phone")
            complaint.status = request.POST.get("status")
            complaint.corporate_name = request.POST.get("corporate_name")
            complaint.content = request.POST.get("content")
            complaint.save()
            return success("修改成功")
        else:
            return fail("修改失败")











