import React, { useState, useRef, useEffect } from "react";
import { Form, Input, Button, Space, Table, Menu, Image } from "antd";
import {
  Routes,
  Route,
  Navigate,
  useNavigate,
  useLocation,
} from "react-router-dom";
import baseRequest from "../../utils/baseRequest";

const StreamerTextMachineReviewContent = (props) => {
  const { TextArea } = Input;
  const current = props.current;
  //表头
  const columns = [
    {
      title: "基本信息",
      dataIndex: "account",
      key: "account",
      render: (data) => (
        <div>
          <Image
            src={data?.avatar?.images[0]?.urls[0]}
            width={50}
            height={50}
            className="rounded-full"
          />
          <p>
            ID：<span className="text-red-400">{data.user_id}</span>
          </p>
          <p>
            昵称：<span className="text-red-400">{data.name}</span>
          </p>
        </div>
      ),
    },
    {
      title: "修改项目",
      dataIndex: "item",
      key: "item",
      render: (data) => (
        <div>
          {data === "name" && <p>昵称</p>}
          {data === "bio" && <p>个性签名</p>}
          {data === "auto_response_message" && <p>私信自动回复</p>}
          {data === "profile" && <p>空间介绍</p>}
        </div>
      ),
    },
    {
      title: "新内容",
      dataIndex: "newMedia",
      key: "newMedia",
    },
    {
      title: "旧内容",
      dataIndex: "oldMedia",
      key: "oldMedia",
    },
    {
      title: "审核结果",
      dataIndex: "info",
      key: "info",
      render: (data) => {
        if (data.status === 2 || data.status === 5)
          return <p className="text-green-400">无违规</p>;
        return (
          <div className="flex flex-wrap gap-1">
            {data.spam_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>垃圾审核：</p>
                <ul>
                  {data.spam_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.politics_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>敏感审核：</p>
                <ul>
                  {data.politics_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.abuse_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>辱骂审核：</p>
                <ul>
                  {data.abuse_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.terrorism_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>暴恐审核：</p>
                <ul>
                  {data.terrorism_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.porn_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>鉴黄审核：</p>
                <ul>
                  {data.porn_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.flood_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>灌水审核：</p>
                <ul>
                  {data.flood_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
            {data.contraband_label_details && (
              <div className="border-2 border-black bg-gray-200">
                <p>违禁审核：</p>
                <ul>
                  {data.contraband_label_details?.map((item, index) => (
                    <li key={index}>{item}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        );
      },
    },
    {
      title: "提交时间",
      dataIndex: "submitTime",
      key: "submitTime",
    },
    {
      title: "备注",
      dataIndex: "remarks",
      key: "remarks",
      render: (_, record) => (
        <Form.Item name={record.id} initialValue={record.remarks}>
          <TextArea disabled rows={4} />
        </Form.Item>
      ),
    },
    {
      title: "操作",
      dataIndex: "opeartion",
      key: "opeartion",
      render: (_, record) => (
        <div>
          <Space>
            <Space.Compact direction="vertical">
              {current !== "passbyoperator" && (
                <>
                  <Button type="primary" onClick={() => onClickSubmit(record)}>
                    通过
                  </Button>
                  <Button onClick={() => onClickRefuse(record)}>拒绝</Button>
                </>
              )}
            </Space.Compact>
          </Space>
        </div>
      ),
    },
  ];
  //给表单绑定ref
  const formRef = useRef(null);
  //点击通过按钮
  const onClickSubmit = (record) => {
    formRef.current.record = record;
    formRef.current.btn = "submit";
    formRef.current.submit();
  };
  //点击拒绝按钮
  const onClickRefuse = (record) => {
    formRef.current.record = record;
    formRef.current.btn = "refuse";
    formRef.current.submit();
  };
  //提交表单
  const handleSubmit = async () => {
    let opType = 0;
    if (formRef.current.btn === "refuse") {
      opType = 1;
    }
    //提交数据
    try {
      const base = baseRequest();
      const response = await fetch("/op/text_audit_task/review", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          ids: [formRef.current.record.others.id],
          op_type: opType,
          ...base,
        }),
      });
      const approveData = await response.json();
      if (approveData.ret === -1) {
        alert(approveData.msg);
        return;
      }
    } catch (error) {
      console.error(error);
    }
    //取消数据展示
    setShowData(
      showData.filter((item) => item.id !== formRef.current.record.others.id)
    );
  };
  //获取数据
  const [data, setData] = useState([]);
  const [offset, setOffset] = useState(0);
  const [more, setMore] = useState(1);
  const getData = async () => {
    if (!more) return;
    let querryStatus;
    switch (current) {
      case "rollbackbymachine":
        querryStatus = 4;
        break;
      case "passbymachine":
        querryStatus = 2;
        break;
      case "passbyoperator":
        querryStatus = 5;
        break;
      default:
        break;
    }
    try {
      const base = baseRequest();
      const response = await fetch("/op/text_audit_task/list", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          associative_database: "streamer",
          associative_table_name: "streamer",
          status: querryStatus,
          offset: offset,
          limit: 200,
          ...base,
        }),
      });
      const temData = await response.json();
      console.log(temData);
      if (temData.ret === -1) {
        alert(temData.msg);
        return;
      }
      //匹配表格格式
      const structedData = temData.data.list.map((item, index) => {
        return {
          key: index,
          id: item.id,
          account: item.account,
          item: item.associative_table_column,
          newMedia: item.audited_text,
          oldMedia: item.old_text,
          info: item.text_audit,
          submitTime: new Date(item.ct * 1000).toLocaleString(),
          remarks: item.remarks,
          others: {
            id: item.id,
            audited_text: item.audited_text,
            associative_database: item.associative_database,
            associative_table_name: item.associative_table_name,
            associative_table_id: item.associative_table_id,
            associative_table_column: item.associative_table_column,
          },
        };
      });
      setData([...data, ...structedData]);
      setOffset(temData.data.offset);
      setMore(temData.data.more);
    } catch (error) {
      console.error(error);
    }
  };
  useEffect(() => {
    getData();
  }, [current]);

  //展示的数据
  const [showData, setShowData] = useState([]);
  useEffect(() => {
    setShowData(data);
  }, [data]);
  //表单提交失败
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };
  return (
    <div style={{ marginLeft: 20, marginRight: 20 }}>
      <p>
        {current === "rollbackbymachine" && `机审核违规${showData.length}条`}
        {current === "passbymachine" && `机审核通过${showData.length}条`}
        {current === "passbyoperator" && `运营通过${showData.length}条`}
      </p>
      <Form
        ref={formRef}
        name="remarks"
        onFinish={handleSubmit}
        onFinishFailed={onFinishFailed}
      >
        <Table
          columns={columns}
          dataSource={showData}
          pagination={{ pageSize: 20 }}
          scroll={{ y: window.innerHeight - 300 }}
        />
      </Form>
    </div>
  );
};

export default function StreamerTextMachineReview() {
  const navigate = useNavigate();
  //当前tab
  const location = useLocation();
  const pathname = location.pathname.split("/")[2] || "rollbackbymachine";
  const [current, setCurrent] = useState(pathname);
  //tab名称
  const items = [
    {
      label: "机审回退",
      key: "rollbackbymachine",
    },
    {
      label: "机审通过",
      key: "passbymachine",
    },
    {
      label: "运营通过",
      key: "passbyoperator",
    },
  ];
  const onClick = (e) => {
    setCurrent(e.key);
    navigate(e.key);
    window.location.reload();
  };

  return (
    <div>
      <Menu
        onClick={onClick}
        selectedKeys={[current]}
        mode="horizontal"
        items={items}
      />
      <Routes>
        <Route
          path="/"
          element={
            <Navigate to="/streamerTextMachineReview/rollbackbymachine" />
          }
        />
        <Route
          path="/rollbackbymachine"
          element={
            <StreamerTextMachineReviewContent current="rollbackbymachine" />
          }
        />
        <Route
          path="/passbymachine"
          element={<StreamerTextMachineReviewContent current="passbymachine" />}
        />
        <Route
          path="/passbyoperator"
          element={
            <StreamerTextMachineReviewContent current="passbyoperator" />
          }
        />
      </Routes>
    </div>
  );
}
