import { useState, useEffect } from "react";
import {
  Button,
  Input,
  Select,
  message,
  Table,
  Tag,
  Modal,
  Pagination,
  Form,
  Radio,
  ConfigProvider,
  Row,
  Col,
  TreeSelect,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import {
  SyncOutlined,
  SearchOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";
import zh_CN from "antd/es/locale/zh_CN";
import "dayjs/locale/zh-cn";
import "./index.scss";
import {
  getDataListAPI,
  getUserListAPI,
  getRolesListAPI,
  getDeptsListAPI,
  addDataAPI,
  deleteDataAPI,
  getDataAPI,
} from "../../../../api/system/publish";

interface searchValueType {
  dateTime: string[] | undefined;
  roleName: string | undefined;
  roleKey: string | undefined;
  state: string | undefined;
  startTime: string | undefined;
  endTime: string | undefined;
}

//表格单项数据类型
interface TableDataType {
  createTime: string;
  dataScope: string;
  deptIds: any[];
  menuIds: any[];
  roleId: number;
  roleKey: string;
  roleName: string;
  roleSort: string;
  state: string;
  updateTime: string;
  key?: number;
  total?: number;
}

//当前选择的角色信息
interface queryParamsType {
  cluster?: string;
  contentType?: string;
  noticeTitle?: string;
  noticeType?: string;
  publishId?: number;
  sendType?: string;
  pageNum?: number;
  pageSize?: number;
}
let thisrole: any = {};
export default function Inform() {
  const { confirm } = Modal;
  //提示组件
  const [messageApi, contextHolder] = message.useMessage();
  //搜索框内所有内容
  let [searchValue, setSearchValue] = useState<searchValueType>({
    dateTime: undefined,
    roleName: undefined,
    roleKey: undefined,
    startTime: undefined,
    state: undefined,
    endTime: undefined,
  });

  const [thisNotice, setThisNotice] = useState<any>({});
  //Modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("");
  //表单区域
  const [addForm] = Form.useForm();
  const [detailForm] = Form.useForm();
  //serach
  const [formSearch] = Form.useForm();
  //当前页面页数
  let [count, setCount] = useState(1);
  //表格内数据
  let [tableData, setTableData] = useState<TableDataType[]>([]);
  //发送对象数据
  const [senderIds, setSenderIds] = useState<any>(undefined);

  //表格数据总条数
  let [total, setTotal] = useState<number>(0);
  //表格格式
  const columns: ColumnsType<TableDataType> = [
    {
      title: "序号",
      dataIndex: "key",
      key: "key",
    },
    {
      title: "公告标题",
      dataIndex: "noticeTitle",
      key: "noticeTitle",
    },
    {
      title: "公告类型",
      dataIndex: "noticeType",
      key: "noticeType",
      render: (text) => {
        switch (text) {
          case "1":
            return <Tag color="processing">通知</Tag>;
          case "2":
            return <Tag color="processing">公告</Tag>;
        }
      },
    },
    {
      title: "内容类型",
      key: "contentType",
      dataIndex: "contentType",
      render: (text) => {
        switch (text) {
          case "text":
            return <Tag color="">文本</Tag>;
          case "html":
            return <Tag color="success">富文本</Tag>;
        }
      },
    },
    {
      title: "发送类型",
      key: "sendType",
      dataIndex: "sendType",
      render: (text) => {
        switch (text) {
          case "user":
            return <>用户</>;
          case "role":
            return <>角色</>;
          case "dept":
            return <>部门</>;
          case "all":
            return <>全发</>;
        }
      },
    },
    {
      title: "创建时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      key: "",
      dataIndex: "",
      render: (text) => (
        <>
          <Button type="link" onClick={() => handleDetail(text)}>
            {"详情"}
          </Button>
          <Button type="link" danger onClick={() => handleDelete(text)}>
            {"删除"}
          </Button>
        </>
      ),
    },
  ];
  //请求表格内容参数
  let [queryTableDataParams, setQueryTableDataParams] = useState<any>({
    cluster: undefined,
    contentType: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    publishId: undefined,
    sendType: undefined,
    pageSize: undefined,
    pageNum: undefined,
  });

  const onSendTypeChange = (value: string) => {
    console.log(value);
    if (value === "user") {
      getUserList();
    } else if (value === "role") {
      getRolesList();
    } else if (value === "dept") {
      getDeptsList();
    }
  };
  //   let thisrole: any = {roleId:'s'};
  const handleDetail = (text: any) => {
    getData(text.noticeId);
    setIsDetailModalOpen(true);
  };
  const handleDelete = (text: any) => {
    console.log(text);
    confirm({
      title: "系统提示",
      icon: <ExclamationCircleFilled />,
      content: `确定删除部门名称为${text.noticeTitle}的数据吗`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        (async () => {
          try {
            let { code } = await deleteDataAPI(text.noticeId);
            if (code === 1000) {
              messageApi.open({
                type: "success",
                content: "操作成功",
              });
              getDataList({});
            }
          } catch (error) {
            console.log(error);
          }
        })();
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  const handleSerach = () => {
    searchValue = formSearch.getFieldsValue();
    setSearchValue(searchValue);
    count = 1;
    setQueryTableDataParams({ ...searchValue });
  };
  const handleReset = () => {
    formSearch.resetFields();
    searchValue = formSearch.getFieldsValue();
    setSearchValue(searchValue);
    setQueryTableDataParams({ ...searchValue });
  };
  //Modal区域
  const handleModalOk = () => {
    addForm
      .validateFields()
      .then((values) => {
        // form.resetFields();
        console.log("add", values);
        if (modalTitle == "新增公告") {
          postAdd({ ...values, cluster: "notice", action: "SEND" });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });

    console.log("modal thisrole", thisrole);
  };
  const handleModalCanle = () => {
    setIsModalOpen(false);
  };
  const handleDetailCanle = () => {
    setIsDetailModalOpen(false);
  };
  //新增
  const handleNewAdd = () => {
    setModalTitle("新增公告");
    addForm.setFieldsValue({
      noticeTitle: undefined,
      noticeType: "1",
      sendType: undefined,
      senderIds: undefined,
      contentType: "html",
    });
    setIsModalOpen(true);
  };
  const filterOption = (
    input: string,
    option?: { label: string; value: string }
  ) => (option?.label ?? "").toLowerCase().includes(input.toLowerCase());
  //表格函数
  //从服务器获取数据

  //页码改变
  const pageChange = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    queryTableDataParams = { ...queryTableDataParams, pageNum: page, pageSize };
    // setQueryParams({...queryParams,pageNum:page,pageSize})
    console.log(queryTableDataParams);
    getDataList(queryTableDataParams);
    setCount(page);
  };
  //新增请求
  const postAdd = async (value: any) => {
    try {
      let { code } = await addDataAPI(value);
      if (code === 1000) {
        console.log("success");
        messageApi.open({
          type: "success",
          content: "操作成功",
        });
        addForm.setFieldsValue({
          noticeTitle: undefined,
          noticeType: "1",
          sendType: undefined,
          senderIds: undefined,
          contentType: "html",
        });
        getDataList({ ...queryTableDataParams, pageNum: count });
        setIsModalOpen(false);
      } else {
        messageApi.open({
          type: "error",
          content: "角色名称已存在",
        });
      }
    } catch (error) {}
  };
  const getData = async (noticeId: number) => {
    try {
      const { data, code } = await getDataAPI(noticeId);
      if (code === 1000) {
        setThisNotice({ ...data });
      }
    } catch (error) {
      console.log(error);
    }
  };
  const getTree = function (tree: any) {
    tree.title = tree.deptName;
    tree.value = tree.deptId;
    if (tree.children) {
      for (let child of tree.children) {
        getTree(child);
      }
    }
  };
  const getUserList = async () => {
    try {
      const { code, data } = await getUserListAPI();
      if (code === 1000) {
        let userIds: any = [];
        console.log(data.rows);
        data.rows.forEach((item: any) => {
          userIds.push({ value: item.userId, label: item.userName });
        });

        setSenderIds([...userIds]);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const getRolesList = async () => {
    try {
      const { code, data } = await getRolesListAPI();
      if (code === 1000) {
        let RolesIds: any = [];
        console.log(data.rows);

        data.rows.forEach((item: any) => {
          RolesIds.push({ value: item.roleId, label: item.roleName });
        });

        setSenderIds([...RolesIds]);
      }
    } catch (error) {
      console.log(error);
    }
  };
  const getDeptsList = async () => {
    try {
      const { code, data } = await getDeptsListAPI();
      if (code === 1000) {
        for (let child of data) {
          getTree(child);
        }
        console.log(data);
        setSenderIds([...data]);
        // setTotal(data.total);
      }
    } catch (err: any) {
      console.log("555", err);
    }
  };
  const getDataList = async (queryTableDataParams: queryParamsType) => {
    console.log("参数:", queryTableDataParams);
    try {
      const { code, data } = await getDataListAPI(queryTableDataParams);
      if (code === 1000) {
        const sortData = data.rows.sort(
          (a: TableDataType, b: TableDataType) =>
            parseInt(a.roleSort) - parseInt(b.roleSort)
        );
        sortData.forEach((element: TableDataType, i: number) => {
          element.key = i + 1;
        });
        setTableData(sortData);
        setTotal(data.total);
      }
    } catch (err: any) {
      console.log("555", err);
    }
  };
  useEffect(() => {
    // setQueryParams({...queryParams,...valueSch})
    queryTableDataParams = {
      ...queryTableDataParams,
      // ...searchValue,
      pageNum: count,
    };
    getDataList(queryTableDataParams);
    // console.log(queryParams);
  }, [queryTableDataParams]);
  return (
    <ConfigProvider locale={zh_CN}>
      <div className="Box">
        <Form
          layout="inline"
          initialValues={undefined}
          form={formSearch}
          onFinish={handleSerach}
          style={{ fontWeight: "700" }}
        >
          <Form.Item
            label="公告标题"
            name="noticeTitle"
            style={{ width: 350 + "px", marginTop: "10px" }}
          >
            <Input placeholder="请输入公告标题" allowClear />
          </Form.Item>
          <Form.Item
            label="公告类型"
            name="noticeType"
            style={{ width: 350 + "px", marginTop: "10px" }}
          >
            <Select
              style={{ textAlign: "left" }}
              allowClear
              showSearch
              placeholder="请选择公告类型"
              optionFilterProp="lable"
              filterOption={filterOption}
              options={[
                {
                  value: "1",
                  label: "通知",
                },
                {
                  value: "2",
                  label: "公告",
                },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="内容类型"
            name="contentType"
            style={{ width: 350 + "px", marginTop: "10px" }}
          >
            <Select
              style={{ textAlign: "left" }}
              allowClear
              showSearch
              placeholder="请选择内容类型"
              optionFilterProp="lable"
              filterOption={filterOption}
              options={[
                {
                  value: "text",
                  label: "文本",
                },
                {
                  value: "html",
                  label: "富文本",
                },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="发送类型"
            name="sendType"
            style={{ width: 350 + "px", marginTop: "10px" }}
          >
            <Select
              style={{ textAlign: "left" }}
              allowClear
              showSearch
              placeholder="请选择发送类型"
              optionFilterProp="lable"
              filterOption={filterOption}
              options={[
                {
                  value: "user",
                  label: "用户",
                },
                {
                  value: "role",
                  label: "角色",
                },
                {
                  value: "dept",
                  label: "部门",
                },
                {
                  value: "all",
                  label: "全发",
                },
              ]}
            />
          </Form.Item>
          <Form.Item style={{ marginTop: "10px" }}>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: 20 + "px" }}
              onClick={() => handleSerach()}
            >
              <SearchOutlined />
              搜索
            </Button>
          </Form.Item>
          <Form.Item style={{ marginTop: "10px" }}>
            <Button onClick={() => handleReset()}>
              <SyncOutlined />
              重置
            </Button>
          </Form.Item>
        </Form>
        {/* 新增 */}
        <div className="newadd">
          <Button type="primary" onClick={handleNewAdd}>
            +新增
          </Button>
        </div>
        {/* 弹出 */}
        <Modal
          open={isModalOpen}
          title={modalTitle}
          width={800}
          okText="确定"
          cancelText="取消"
          onCancel={handleModalCanle}
          onOk={handleModalOk}
        >
          <Form
            form={addForm}
            layout="horizontal"
            name="form_in_modal"
            initialValues={{ noticeType: "1", contentType: "1" }}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
          >
            <Row>
              <Col span={12}>
                <Form.Item
                  name="noticeTitle"
                  label="公告标题"
                  rules={[{ required: true, message: "请输入公告标题" }]}
                >
                  <Input placeholder="请输入公告标题" />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="noticeType"
                  label="公告类型"
                  rules={[{ required: true }]}
                >
                  <Radio.Group>
                    <Radio defaultChecked={true} value="1">
                      通知
                    </Radio>
                    <Radio value="2">公告</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={12}>
                <Form.Item
                  required
                  name="sendType"
                  label="发送类型"
                  rules={[{ required: true, message: "选择发送类型" }]}
                >
                  <Select
                    style={{ textAlign: "left" }}
                    allowClear
                    showSearch
                    placeholder="请选择发送类型"
                    optionFilterProp="lable"
                    filterOption={filterOption}
                    onChange={(value) => onSendTypeChange(value)}
                    options={[
                      {
                        value: "user",
                        label: "用户",
                      },
                      {
                        value: "role",
                        label: "角色",
                      },
                      {
                        value: "dept",
                        label: "部门",
                      },
                      {
                        value: "all",
                        label: "全发",
                      },
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  name="senderIds"
                  label="发送对象"
                  rules={[{ required: true, message: "选择发送对象" }]}
                >
                  {senderIds === undefined ? (
                    <Select
                      mode="multiple"
                      style={{ textAlign: "left" }}
                      allowClear
                      showSearch
                      placeholder="请选择发送对象"
                      optionFilterProp="lable"
                      filterOption={filterOption}
                    />
                  ) : senderIds[0].children === undefined ? (
                    <Select
                      mode="multiple"
                      style={{ textAlign: "left" }}
                      allowClear
                      showSearch
                      placeholder="请选择发送对象"
                      optionFilterProp="lable"
                      filterOption={filterOption}
                      options={senderIds}
                    />
                  ) : (
                    <TreeSelect
                      multiple
                      style={{ textAlign: "left" }}
                      dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                      placeholder="请选择发送对象"
                      allowClear
                      treeData={senderIds}
                      //
                    />
                  )}
                </Form.Item>
              </Col>
            </Row>

            <Form.Item
              name="contentType"
              label="内容类型"
              rules={[{ required: true, message: "选择发送类型" }]}
            >
              <Radio.Group>
                <Radio defaultChecked={true} value="html">
                  富文本
                </Radio>
                <Radio value="text">文本</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="menuIds"
              label="菜单权限"
              className="collection-create-form_last-form-item"
            ></Form.Item>
          </Form>
        </Modal>
        <Modal
          open={isDetailModalOpen}
          title={"公告详情"}
          width={1200}
          footer={null}
          onCancel={handleDetailCanle}
        >
          <Form
            form={detailForm}
            layout="horizontal"
            name="form_in_modal"
            initialValues={{}}
            labelAlign="right"
            wrapperCol={{ span: 16 }}
          >
            <Row>
              <Col span={8}>
                <Form.Item
                  name="noticeTitle"
                  label="公告标题"
                  // initialValue={'ssss'}
                >
                  <span> {thisNotice.noticeTitle}</span>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item
                  name="sendType"
                  label="发送类型"
                  // initialValue={'ssss'}
                >
                  <span>
                    {" "}
                    {thisNotice.sendType === "user"
                      ? "用户"
                      : thisNotice.sendType === "role"
                      ? "角色"
                      : thisNotice.sendType === "dept"
                      ? "部门"
                      : "全发"}
                  </span>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="sendIds" label="发送对象">
                  <span></span>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={8}>
                <Form.Item name="noticeType" label="公告类型">
                  <span>
                    {thisNotice.noticeType === "1" ? (
                      <Tag color="processing">通知</Tag>
                    ) : (
                      <Tag color="processing">公告</Tag>
                    )}
                  </span>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item name="contentType" label="内容类型">
                  <span>
                    {thisNotice.contentType === "html" ? (
                      <Tag color="success">富文本</Tag>
                    ) : (
                      <Tag>文本</Tag>
                    )}
                  </span>
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Form.Item name="noticeContent" label="公告内容">
                <span
                  dangerouslySetInnerHTML={{ __html: thisNotice.noticeContent }}
                ></span>
              </Form.Item>
            </Row>
          </Form>
        </Modal>
        {/* 表格 */}
        <div className="tablebox">
          {contextHolder}
          <Table columns={columns} dataSource={tableData} pagination={false} />
          <Pagination
            style={{
              float: "right",
              marginTop: "10px",
            }}
            total={total}
            current={count}
            showSizeChanger
            showQuickJumper
            onChange={(page, pageSize) => pageChange(page, pageSize)}
            showTotal={(total) => `共 ${total} 条`}
          />
        </div>
      </div>
    </ConfigProvider>
  );
}
