import "./index.scss";
import {
  Input,
  Tree,
  Select,
  DatePicker,
  Button,
  Table,
  Space,
  Tag,
  message,
  Modal,
  Form,
  Row,
  Col,
  TreeSelect,
  Radio,
} from "antd";

import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleFilled,
} from "@ant-design/icons";

import {
  getUserListApi,
  deleteUserApi,
  getDeptTreeApi,
  addUserApi,
  getRoleListApi,
  getUserInfoApi,
  editUserApi,
} from "../../../api/system/users";

import FormatData from "../../../utils/formatData";
import locale from "antd/es/date-picker/locale/zh_CN";
import React, { useEffect, useState, useMemo, useRef } from "react";
import { SearchOutlined, RedoOutlined, PlusOutlined } from "@ant-design/icons";

export default function User() {
  const [form] = Form.useForm();
  const postIdList: number[] = [];
  const [echoId, setEchoId] = useState<any>();
  const [myTreeData, setMyTreeData] = useState<[]>([]);
  const [listData, setListData] = useState([]);
  const [radioValue, setRadioValue] = useState(1);
  const [searchTreeValue, setSearchTreeValue] = useState("");
  const [roleList, setRoleList] = useState<any[]>([]);
  const [messageApi, contextHolder] = message.useMessage();
  const [modalTitle, setModalTitle] = useState<string>("");
  const [buttonType, setButtonType] = useState<string>("");
  const [isShowModal, setIsShowModal] = useState<boolean>(false);
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([
    100, 102, 101, 104,
  ]);
  const [treeValue, setTreeValue] = useState<string>();
  const fieldNames = {
    label: "deptName",
    title: "deptName",
    value: "deptId",
    key: "deptName",
  };
  const [queryParams, setQueryParams] = useState<QueryParamsType>({
    userName: undefined,
    phoneNumber: undefined,
    state: undefined,
    startTime: undefined,
    endTime: undefined,
    pageNum: undefined,
    pageSize: undefined,
  });
  const columns = [
    {
      title: "序号",
      dataIndex: "userId",
      key: "Id",
      render: (text: string) => <>{text ? text : "null"}</>,
    },
    {
      title: "用户名称",
      dataIndex: "userName",
      key: "userName",
      render: (text: string) => <>{text ? text : "null"}</>,
    },
    {
      title: "用户昵称",
      dataIndex: "nickName",
      key: "nikeName",
      render: (text: string) => <>{text ? text : "null"}</>,
    },
    {
      title: "部门",
      key: "deptId",
      dataIndex: "deptName",
      render: (text: string) => <>{text ? text : "--"}</>,
    },
    {
      title: "手机号码",
      key: "phoneNumber",
      dataIndex: "phoneNumber",
      render: (text: string) => <>{text ? text : "--"}</>,
    },
    {
      title: "状态",
      key: "state",
      dataIndex: "state",
      render: (text: string) => (
        <>
          {text === "0" ? (
            <Tag color="processing">停用</Tag>
          ) : (
            <Tag color="processing">正常</Tag>
          )}
        </>
      ),
    },
    {
      title: "创建时间",
      key: "createTime",
      dataIndex: "createTime",
      render: (text: string) => <>{text ? text : "null"}</>,
    },
    {
      title: "操作",
      key: "operate",
      dataIndex: "operate",
      render: (_: string, record: object) => (
        <div style={{ color: "#58aaff" }}>
          <Space>
            <EditOutlined />
            <a
              href="#"
              onClick={() => handleEdit(record)}
              style={{ color: " #58aaff" }}
            >
              编辑
            </a>
            <DeleteOutlined />
            <a
              href="#"
              onClick={() => handleDel(record)}
              style={{ color: " #58aaff" }}
            >
              删除
            </a>
          </Space>
        </div>
      ),
    },
  ];

  interface AddUserType {
    deptId: number | null;
    email: string;
    nickName: string;
    password: string;
    phoneNumber: string;
    postIds: number[];
    roleIds: number[];
    sex: string;
    state: string;
    userName: string;
  }

  interface QueryParamsType {
    userName?: string;
    phoneNumber?: string;
    state?: string;
    startTime?: string | null;
    endTime?: string | null;
    pageNum?: number;
    pageSize?: number;
  }

  let addUserParams: AddUserType = {
    deptId: null,
    email: "",
    nickName: "",
    password: "",
    phoneNumber: "",
    postIds: [],
    roleIds: [],
    sex: "",
    state: "",
    userName: "",
  };

  const getDeptTreeData = async () => {
    try {
      const { code, data } = await getDeptTreeApi();
      if (code === 1000) {
        setMyTreeData(data);
        handleLoopPostList(data);
        setExpandedKeys(postIdList);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const getUserList = async (newQueryParams: object) => {
    try {
      console.log(newQueryParams);

      const { code, data } = await getUserListApi(newQueryParams);
      if (code === 1000) {
        setListData(data.rows);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const getUserInfo = async () => {
    try {
      const { code, data } = await getUserInfoApi(echoId);
      if (code === 1000) {
        handleEcho(data);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const getRoleList = async () => {
    try {
      const { code, data } = await getRoleListApi();
      if (code === 1000) {
        setRoleList(data.rows);
      }
    } catch (err) {
      console.log(err);
    }
  };

  const handleAdd = () => {
    setModalTitle("新增用户");
    setButtonType("ADD");
    setIsShowModal(true);
  };

  const handleEdit = (echoData: any) => {
    setModalTitle("修改用户");
    setButtonType("EDIT");
    setIsShowModal(true);
    setEchoId(echoData.userId);
  };

  const handleConfirm = () => {
    form.validateFields().then((values) => {
      Object.keys(values).forEach(
        (key) => values[key] === undefined && delete values[key]
      );
      addUserParams = {
        ...addUserParams,
        ...values,
        userId: echoId,
      };
      if (buttonType === "ADD") {
        handleAddUser();
      } else if (buttonType === "EDIT") {
        handleEditUser();
      } else {
        messageApi.open({
          type: "error",
          content: "系统异常，请刷新后重试",
        });
      }
    });
  };

  const handleAddUser = async () => {
    const { code } = await addUserApi(addUserParams);
    try {
      if (code === 1000) {
        messageApi.open({
          type: "success",
          content: "创建成功",
        });
        setQueryParams({});
        handleClear();
      } else {
        messageApi.open({
          type: "error",
          content: "用户名已经存在",
        });
      }
    } catch (err) {
      console.log(err);
    }
  };

  const handleEditUser = async () => {
    const { code } = await editUserApi(addUserParams);
    try {
      if (code === 1000) {
        messageApi.open({
          type: "success",
          content: "修改成功",
        });
        setQueryParams({});
        handleClear();
      } else {
        messageApi.open({
          type: "error",
          content: "修改失败",
        });
      }
    } catch (err) {
      console.log(err);
    }
  };

  const handleReset = async () => {
    setQueryParams({
      startTime: null,
      endTime: null,
    });
    setQueryParams({});
    getUserList({});
  };

  const handleSearch = () => {
    console.log(queryParams);
    getUserList(queryParams);
  };

  const handleDel = async (record: any) => {
    Modal.confirm({
      title: `确定删除Id为-${record.userId}-, 用户名为-${record.userName}-的用户吗?`,
      icon: <ExclamationCircleFilled />,
      async onOk() {
        const { code } = await deleteUserApi(record.userId);
        try {
          if (code === 1000) {
            messageApi.open({
              type: "success",
              content: "删除成功",
            });
            setQueryParams({});
          } else {
            messageApi.open({
              type: "error",
              content: "删除失败",
            });
          }
        } catch (err) {
          console.log(err);
        }
      },
      onCancel() {
        messageApi.open({
          type: "warning",
          content: "取消成功",
        });
      },
    });
  };

  const handleTimePikerValue = (dates: any[]) => {
    setQueryParams({
      ...queryParams,
      startTime: FormatData(dates[0].$d),
      endTime: FormatData(dates[1].$d),
    });
  };

  const handleSearchValues = (e: any) => {
    const { name, value } = e.target;
    setQueryParams({ ...queryParams, [name]: value });
  };

  const handlePageChange = (page: number) => {
    setQueryParams({
      ...queryParams,
      pageNum: page,
    });
  };

  const handleEcho = (data: any) => {
    const { userName, nickName, sex, state, phoneNumber, deptId, email } =
      data.user;
    const { postIds, roleIds } = data;
    form.setFieldsValue({
      userName,
      nickName,
      state,
      phoneNumber,
      sex,
      deptId,
      email,
      postIds,
      roleIds,
    });
  };

  const handleCancel = () => {
    handleClear();
  };

  const handleClear = () => {
    form.resetFields();
    setIsShowModal(false);
  };

  const handleExpandKeys = (key: string, data: object[]) => {
    const filterRes = new RegExp(key, "i");
    data.forEach((item: any) => {
      if (filterRes.test(item?.title?.props?.children)) {
        postIdList.push(item.key);
      }
      item.children ? handleExpandKeys(key, item.children) : "";
    });
  };

  const handleLoopPostList = (loopData: object[]) => {
    loopData.forEach((item: any) => {
      if (item?.deptId) {
        const flag = postIdList.some((someItem) => {
          someItem === item.deptId;
        });
        if (!flag) {
          postIdList.push(item.deptId);
        }
      }
      item.children ? handleLoopPostList(item.children) : "";
    });
  };

  const onRadio = (e: any) => {
    setRadioValue(e.target.value);
  };

  const onTreeSelect = (newValue: string) => {
    setTreeValue(newValue);
  };

  const onTreeSearch = (e?: any) => {
    const { value } = e.target ? e.target : null;
    setSearchTreeValue(value);
    handleExpandKeys(value, treeData);
    console.log("postIdList:", postIdList);
    setExpandedKeys(postIdList);
    setAutoExpandParent(true);
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    console.log(newExpandedKeys);
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const treeData = useMemo(() => {
    const loop = (data: any[]): any[] =>
      data.map((item) => {
        const strTitle = item.deptName as string;
        const index = strTitle.indexOf(searchTreeValue);
        const beforeStr = strTitle.substring(0, index);
        const afterStr = strTitle.slice(index + searchTreeValue.length);
        const title =
          index > -1 ? (
            <span>
              {beforeStr}
              <span className="site-tree-search-value">{searchTreeValue}</span>
              {afterStr}
            </span>
          ) : (
            <span>{strTitle}</span>
          );
        if (item.children) {
          return { title, key: item.deptId, children: loop(item.children) };
        }
        return {
          title,
          key: item.deptId,
        };
      });
    return loop(myTreeData);
  }, [myTreeData]);

  useEffect(() => {
    getDeptTreeData();
    getRoleList();
    getUserInfo();
  }, [echoId]);

  useEffect(() => {
    getUserList({});
  }, [queryParams]);

  return (
    <div id="content">
      <div className="dept-content">
        <Input
          allowClear
          style={{ marginBottom: 8 }}
          prefix={<SearchOutlined />}
          placeholder="请输入部门名称"
          onChange={onTreeSearch}
        />
        <Tree
          onExpand={onExpand}
          defaultExpandAll={true}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          treeData={treeData}
        />
      </div>
      <>
        <div className="right-user">
          <div className="search-content">
            <>
              <div className="content-top">
                <div className="input-item">
                  <div>用户名称</div>
                  <Input
                    placeholder="请输入用户名称"
                    name="userName"
                    allowClear
                    value={queryParams.userName}
                    onChange={handleSearchValues}
                  />
                </div>
                <div className="input-item">
                  <div>手机号码</div>
                  <Input
                    placeholder="请输入手机号码"
                    name="phoneNumber"
                    allowClear
                    value={queryParams.phoneNumber}
                    onChange={handleSearchValues}
                  />
                </div>
                <div className="input-item">
                  <div>状态</div>
                  <Select
                    style={{ width: 120 }}
                    placeholder="用户状态"
                    allowClear
                    options={[
                      { value: "1", label: "正常" },
                      { value: "0", label: "停用" },
                    ]}
                    value={queryParams.state}
                    onChange={(value: any) =>
                      setQueryParams({
                        ...queryParams,
                        state: value,
                      })
                    }
                  />
                </div>
              </div>
              <div className="content-bottom">
                <div className="time-selector">
                  <div>创建时间</div>
                  <DatePicker.RangePicker
                    showTime
                    locale={locale}
                    className="time-picker"
                    placeholder={["开始时间", "结束时间"]}
                    onChange={(dates) => {
                      handleTimePikerValue(dates as any);
                    }}
                  />
                </div>
                <div className="search-button">
                  <Button type="primary" onClick={handleSearch}>
                    <SearchOutlined />
                    搜索
                  </Button>
                </div>
                <div className="reset-button" onClick={handleReset}>
                  <Button>
                    <RedoOutlined />
                    重置
                  </Button>
                </div>
              </div>
            </>
          </div>
          <div className="add-content">
            <>
              <Button type="primary" onClick={handleAdd}>
                <PlusOutlined />
                新增
              </Button>
            </>
          </div>
          <div className="table-content">
            <>
              {contextHolder}
              <Table
                columns={columns}
                dataSource={listData}
                className="article-table"
                pagination={{
                  onChange: handlePageChange,
                  locale: {
                    jump_to: "跳至",
                    page: "页",
                  },
                  showQuickJumper: true,
                  showTotal: (total, range) =>
                    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                }}
              />
            </>
          </div>
          <>
            {contextHolder}
            <Modal
              title={modalTitle}
              width={700}
              okText="确认"
              cancelText="取消"
              open={isShowModal}
              onOk={handleConfirm}
              onCancel={handleCancel}
            >
              <Form
                form={form}
                name="basic"
                initialValues={{ remember: true }}
                labelCol={{ span: 6 }}
                onFinish={handleConfirm}
                autoComplete="off"
                className="modal-form"
              >
                <Row>
                  <Col span={12}>
                    <Form.Item
                      label="用户名称"
                      name="userName"
                      rules={[{ required: true, message: "请输入用户名称" }]}
                    >
                      <Input defaultValue={""} placeholder="请输入用户名称" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="用户昵称"
                      name="nickName"
                      rules={[{ required: true, message: "请输入用户昵称" }]}
                    >
                      <Input defaultValue={""} placeholder="请输入用户昵称" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="用户性别"
                      name="sex"
                      rules={[{ required: false }]}
                    >
                      <Select
                        placeholder="请选择用户性别"
                        options={[
                          { value: "0", label: "男" },
                          { value: "1", label: "女" },
                          { value: "2", label: "未知" },
                        ]}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="用户密码"
                      name="password"
                      rules={[{ required: true, message: "请输入用户密码" }]}
                    >
                      <Input.Password
                        defaultValue={""}
                        placeholder="请输入密码"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="归属部门"
                      name="deptId"
                      rules={[{ required: false }]}
                    >
                      <TreeSelect
                        showSearch
                        style={{ width: "100%" }}
                        value={treeValue}
                        dropdownStyle={{ maxHeight: 400, overflow: "auto" }}
                        placeholder="请选择"
                        allowClear
                        fieldNames={fieldNames}
                        treeDefaultExpandAll
                        onChange={onTreeSelect}
                        treeData={myTreeData}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="手机号码"
                      name="phoneNumber"
                      rules={[{ required: false }]}
                    >
                      <Input placeholder="请输入手机号码" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="邮箱"
                      name="email"
                      rules={[{ required: false }]}
                    >
                      <Input defaultValue={""} placeholder="请输入邮箱" />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="状态"
                      name="state"
                      rules={[
                        {
                          required: false,
                          message: "Please input your password!",
                        },
                      ]}
                    >
                      <Radio.Group onChange={onRadio} value={radioValue}>
                        <Radio value="1">正常</Radio>
                        <Radio value="0">停用</Radio>
                      </Radio.Group>
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="岗位"
                      name="postIds"
                      rules={[
                        {
                          required: false,
                          message: "Please input your password!",
                        },
                      ]}
                    >
                      <Select
                        mode="multiple"
                        defaultValue={[]}
                        options={[
                          { value: "董事长", label: "董事长" },
                          { value: "项目经理", label: "项目经理" },
                          { value: "人力资源", label: "人力资源" },
                          { value: "普通员工", label: "普通员工" },
                        ]}
                        placeholder="请选择岗位"
                      />
                    </Form.Item>
                  </Col>
                  <Col span={12}>
                    <Form.Item
                      label="角色"
                      name="roleIds"
                      rules={[
                        {
                          required: false,
                          message: "Please input your password!",
                        },
                      ]}
                    >
                      <Select mode="multiple" placeholder="请选择角色">
                        {roleList.map((item) => (
                          <Select.Option key={item.roleId} value={item.roleId}>
                            {item.roleName}
                          </Select.Option>
                        ))}
                      </Select>
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="备注"
                      labelCol={{ span: 3 }}
                      rules={[
                        {
                          required: false,
                          message: "Please input your password!",
                        },
                      ]}
                    >
                      <Input.TextArea placeholder="请输入内容" />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Modal>
          </>
        </div>
      </>
    </div>
  );
}
