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 ImageReviewContent = (props) => {
  const { TextArea } = Input;
  const current = props.current;
  //表头
  const columns = [
    {
      title: "新内容",
      dataIndex: "newMedia",
      key: "newMedia",
      render: (data) => (
        <div className="flex flex-wrap gap-1">
          {data?.map((item, index) => (
            <Image key={index} src={item.urls[0]} width={100} />
          ))}
        </div>
      ),
    },
    {
      title: "旧内容",
      dataIndex: "oldMedia",
      key: "oldMedia",
      render: (data) => (
        <div className="flex flex-wrap gap-1">
          {data?.map((item, index) => (
            <Image key={index} src={item.urls[0]} width={100} />
          ))}
        </div>
      ),
    },
    {
      title: "审核结果",
      dataIndex: "info",
      key: "info",
      render: (data) => (
        <div>
          {data?.map((item, index) => {
            if (item.status === 2 || item.status === 5)
              return (
                <p key={index} className="text-green-400">
                  图{index + 1}无违规
                </p>
              );
            return (
              <div key={index}>
                <p className="text-red-400">图{index + 1}违规情况：</p>
                <div className="flex flex-wrap gap-1">
                  <div className="border-2 border-black bg-gray-200">
                    <p>色情审核：</p>
                    <ul>
                      <li>建议：{item.porn_scene_suggestion}</li>
                      <li>结果：{item.porn_scene_label}</li>
                      <li>结果：{item.porn_scene_rate.toFixed(1)}</li>
                    </ul>
                  </div>
                  <div className="border-2 border-black bg-gray-200">
                    <p>暴恐审核：</p>
                    <ul>
                      <li>建议：{item.terrorism_scene_suggestion}</li>
                      <li>结果：{item.terrorism_scene_label}</li>
                      <li>结果：{item.terrorism_scene_rate.toFixed(1)}</li>
                    </ul>
                  </div>
                  <div className="border-2 border-black bg-gray-200">
                    <p>广告审核：</p>
                    <ul>
                      <li>建议：{item.ad_scene_suggestion}</li>
                      <li>结果：{item.ad_scene_label}</li>
                      <li>结果：{item.ad_scene_rate.toFixed(1)}</li>
                    </ul>
                  </div>
                  <div className="border-2 border-black bg-gray-200">
                    <p>不良审核：</p>
                    <ul>
                      <li>建议：{item.live_scene_suggestion}</li>
                      <li>结果：{item.live_scene_label}</li>
                      <li>结果：{item.live_scene_rate.toFixed(1)}</li>
                    </ul>
                  </div>
                  <div className="border-2 border-black bg-gray-200">
                    <p>logo审核：</p>
                    <ul>
                      <li>建议：{item.logo_scene_suggestion}</li>
                      <li>结果：{item.logo_scene_label}</li>
                      <li>结果：{item.logo_scene_rate.toFixed(1)}</li>
                    </ul>
                  </div>
                </div>
              </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 === "rollbackbymachine" && (
                <Button type="primary" onClick={() => onClickSubmit(record)}>
                  {current === "rollbackbymachine" && "通过"}
                </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 handleSubmit = async () => {
    //提交数据
    try {
      const base = baseRequest();
      const response = await fetch("/op/image_audit_task/pass_batch", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          tasks: [formRef.current.record.others],
          ...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/image_audit_task/list", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          status: querryStatus,
          offset: offset,
          limit: 20,
          ...base,
        }),
      });
      const temData = await response.json();
      console.log(
        JSON.stringify({
          status: querryStatus,
          offset: offset,
          limit: 20,
          ...base,
        })
      );
      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,
          newMedia: item?.audited_media?.images,
          oldMedia: item?.old_media?.images,
          info: item.image_audits,
          submitTime: new Date(item.ct * 1000).toLocaleString(),
          remarks: item.remarks,
          others: {
            id: item.id,
            audited_media: item.audited_media,
            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 ImageReview() {
  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="/imageReview/rollbackbymachine" />}
        />
        <Route
          path="/rollbackbymachine"
          element={<ImageReviewContent current="rollbackbymachine" />}
        />
        <Route
          path="/passbymachine"
          element={<ImageReviewContent current="passbymachine" />}
        />
        <Route
          path="/passbyoperator"
          element={<ImageReviewContent current="passbyoperator" />}
        />
      </Routes>
    </div>
  );
}
