import { useState, useEffect } from "react";
import {
  Button,
  Input,
  Select,
  DatePicker,
  Space,
  message,
  Table,
  Tag,
  Modal,
  Pagination,
  Form,
  Checkbox,
  InputNumber,
  Radio,
  Tree,
  ConfigProvider,
} from "antd";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import type { DatePickerProps, RangePickerProps } from "antd/es/date-picker";
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 dataLocale from "antd/es/date-picker/locale/zh_CN";
import "dayjs/locale/zh-cn";
import "./index.scss";
import {
  getRolesDataAPI,
  delRoleAPI,
  getRoleAPI,
  addRoleAPI,
  setRoleDataAPI,
  getMenuLiseAPI,
} from "../../../api/system/role";
// import { useForm } from "antd/es/form/Form";
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;
}
//当前选择的角色信息
const fieldNames = {
  title: "menuName",
  key: "menuId",
  children: "children",
};

let thisrole: any = {};
let treeIds: number[] = [];
export default function Role() {
  const { confirm } = Modal;
  const { RangePicker } = DatePicker;
  //提示组件
  const [messageApi, contextHolder] = message.useMessage();
  //搜索框内所有内容
  let [searchValue, setSearchValue] = useState<searchValueType>({
    dateTime: undefined,
    roleName: undefined,
    roleKey: undefined,
    startTime: undefined,
    state: undefined,
    endTime: undefined,
  });
  //树列表数据
  const [menuTreeData, setMenuTreeData] = useState([]);
  //父子联动
  const [checkStrictly, setCheckStrictly] = useState(false);
  //树所有节点IDs
  //树是否自动展开
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  //Modal
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("");
  //表单区域
  const [form] = Form.useForm();
  //serach
  const [formSearch] = Form.useForm();
  //当前页面页数
  let [count, setCount] = useState(1);
  //表格内数据
  let [tableData, setTableData] = useState<TableDataType[]>([]);
  //表格数据总条数
  let [total, setTotal] = useState<number>(0);
  //表格格式
  const columns: ColumnsType<TableDataType> = [
    {
      title: "序号",
      dataIndex: "key",
      key: "key",
    },
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
    },
    {
      title: "角色权限",
      dataIndex: "roleKey",
      key: "roleKey",
    },
    {
      title: "数据范围",
      key: "dataScope",
      dataIndex: "dataScope",
      render: (text) => {
        switch (text) {
          case "1":
            return <>所有数据权限</>;
          case "2":
            return <>自定义数据权限</>;
          case "3":
            return <>本部门数据权限</>;
          default:
            return <>本部门及以下数据权限</>;
        }
      },
    },
    {
      title: "显示顺序",
      key: "roleSort",
      dataIndex: "roleSort",
    },
    {
      title: "状态",
      key: "state",
      dataIndex: "state",
      render: (text) => (
        <>
          {text === "0" ? (
            <Tag color="success">正常</Tag>
          ) : (
            <Tag color="error">停用</Tag>
          )}
        </>
      ),
    },
    {
      title: "创建时间",
      key: "createTime",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      key: "",
      dataIndex: "",
      render: (text) => (
        <>
          <Button type="link" onClick={() => handleEdit(text)}>
            {"修改"}
          </Button>
          {/* <Button type='link' danger onClick={() => handleClickDel(text)}>{'删除'}</Button> */}
          <Button type="link" danger onClick={() => handleDelete(text)}>
            {"删除"}
          </Button>
          <Button type="link">{"分配用户"}</Button>
        </>
      ),
    },
  ];
  //请求表格内容参数
  let [queryTableDataParams, setQueryTableDataParams] = useState<any>({
    roleKey: undefined,
    roleName: undefined,
    state: undefined,
    endTime: undefined,
    startTime: undefined,
    pageNum: undefined,
    pageSize: undefined,
  });
  const [allChecked, setAllChecked] = useState(false);
  const onTreeExpand = (expandedKeysValue: React.Key[]) => {
    // console.log("onExpand", expandedKeysValue);
    setExpandedKeys(expandedKeysValue);
  };
  const onCheckExpand = (e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`);
    console.log(treeIds);
    if (e.target.checked) setExpandedKeys(treeIds);
    else setExpandedKeys([]);
    console.log(expandedKeys);
  };
  const onCheckAll = (e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`);
    setAllChecked(!allChecked);
    if (!allChecked) setCheckedKeys(treeIds);
    else setCheckedKeys([]);
  };
  const onCheckFaSon = (e: CheckboxChangeEvent) => {
    console.log(`checked = ${e.target.checked}`);
    setCheckStrictly(!e.target.checked);
  };
  const onTreeCheck = (checkedKeysValue: any) => {
    // console.log("onCheck", checkedKeysValue.checked);
    console.log("onCheck", checkedKeysValue);
    console.log("treeIds", treeIds);

    if (checkedKeysValue.length != treeIds.length) {
      setAllChecked(false);
    } else {
      setAllChecked(true);
    }
    if (checkStrictly === false) {
      form.setFieldsValue({ menuIds: checkedKeysValue });
      setCheckedKeys(checkedKeysValue);
    } else {
      form.setFieldsValue({ menuIds: checkedKeysValue.checked });
      setCheckedKeys(checkedKeysValue.checked);
    }
  };
  const onTreeSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log("onSelect", info);
    // setExpandedKeys([...expandedKeys,...selectedKeysValue])
    setSelectedKeys(selectedKeysValue);
  };
  //当前角色的数据

  //   let thisrole: any = {roleId:'s'};
  const handleEdit = async (role: any) => {
    await getRoleData(role);
    setModalTitle("修改角色");
    // setCheckedKeys(role)
    setIsModalOpen(true);
  };
  const handleDelete = (role: any) => {
    console.log(role);
    confirm({
      title: "系统提示",
      icon: <ExclamationCircleFilled />,
      content: `确定删除角色名称为${role.roleName}的数据吗`,
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      onOk() {
        handleClickDel(role);
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  const handleSerach = () => {
    searchValue = formSearch.getFieldsValue();

    if (typeof searchValue.dateTime !== "undefined") {
      searchValue.startTime = (searchValue.dateTime as string[])[0];
      searchValue.endTime = (searchValue.dateTime as string[])[1];
    }
    setSearchValue(searchValue);
    count = 1;
    setQueryTableDataParams({ ...searchValue });
  };
  const handleReset = () => {
    formSearch.resetFields();
    searchValue = formSearch.getFieldsValue();
    setSearchValue(searchValue);
    setQueryTableDataParams({ ...searchValue });
    // setSearchValue({ ...searchValue });
    // setCount(1)
  };
  //Modal区域
  const handleModalOk = () => {
    form
      .validateFields()
      .then((values) => {
        // form.resetFields();
        console.log("add", values);
        if (modalTitle == "新增角色") {
          postAdd({ ...values, menuIds: checkedKeys });
        } else if (modalTitle == "修改角色") {
          console.log(thisrole);
          console.log(checkedKeys);
          console.log("now", { ...thisrole, ...values, menuIds: checkedKeys });
          // console.log({ ...thisrole, ...values,menuIds:setCheckedKeys });
          thisrole = { ...thisrole, ...values, menuIds: checkedKeys };
          editRoleData({ ...thisrole });
        }
      })
      .catch((info) => {
        console.log("Validate Failed:", info);
      });

    console.log("modal thisrole", thisrole);
  };
  const handleModalCanle = () => {
    setIsModalOpen(false);
  };
  //新增
  const handleNewAdd = () => {
    setModalTitle("新增角色");
    form.setFieldsValue({
      roleName: "",
      roleKey: "",
      state: "0",
      dataScope: "1",
      roleSort: "0",
    });

    setCheckedKeys([]);
    setIsModalOpen(true);
  };
  const onDateChange = (
    valueDate: DatePickerProps["value"] | RangePickerProps["value"],
    dateString: [string, string] | string
  ) => {
    // setSelectedDate(valueDate)
    console.log(valueDate);
    searchValue.startTime = dateString[0];
    searchValue.endTime = dateString[1];
    formSearch.setFieldsValue({ dateTime: [dateString[0], dateString[1]] });
    setSearchValue(searchValue);
    // setSearchValue({ ...searchValue })
  };
  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);
    getRolesData(queryTableDataParams);
    setCount(page);
  };
  //删除单项
  const handleClickDel = (role: TableDataType) => {
    console.log(role);
    let { roleId } = role;
    del(roleId);
  };
  //遍历菜单树获取所有节点ID
  const getTreeIds = function (tree: any) {
    // console.log('Ids:',tree);
    tree.forEach((item: any) => {
      // console.log(item);
      treeIds.push(item.menuId);
      if (item.children != null) getTreeIds(item.children);
    });
  };
  //获取单个角色详细信息
  const getRoleData = async (role: any) => {
    // const {roleId,roleKey,roleName,roleSort,dataScope,state,meunIds}=role
    // thisrole=role
    try {
      let { code, data } = await getRoleAPI(role);
      if (code === 1000) {
        console.log("role:", data);
        thisrole = data;
        console.log("thisrole", thisrole);
        form.setFieldsValue(thisrole);
        setCheckedKeys(data.menuIds);
      }
    } catch (error) {
      console.log(error);
    }
    // setOpen(true);
  };
  //获取菜单权限树
  const getMenuList = async () => {
    try {
      let menul = await getMenuLiseAPI();
      console.log("tree", menul.data);
      if (treeIds.length == 0) getTreeIds(menul.data);
      console.log(treeIds);
      setMenuTreeData(menul.data);
      // treeData = menul.data
      // setMenulist(menul.data)
    } catch (error) {
      console.log(error);
    }
  };
  //新增请求
  const postAdd = async (value: any) => {
    try {
      let { code } = await addRoleAPI(value);
      console.log(code);

      if (code === 1000) {
        console.log("success");
        messageApi.open({
          type: "success",
          content: "操作成功",
        });
        form.setFieldsValue({
          roleName: "",
          roleKey: "",
          state: "0",
          dataScope: "1",
        });
        getRolesData({ ...queryTableDataParams, pageNum: count });
        setIsModalOpen(false);
      } else {
        messageApi.open({
          type: "error",
          content: "角色名称已存在",
        });
      }
    } catch (error) {}
  };
  const getRolesData = async (queryTableDataParams: any) => {
    console.log("参数:", queryTableDataParams);
    try {
      const { code, data } = await getRolesDataAPI(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);
    }
  };
  //服务器删除角色
  const del = async (roleId: number) => {
    try {
      let { code } = await delRoleAPI({ roleId });
      if (code === 1000) {
        console.log("del", roleId);
        messageApi.open({
          type: "success",
          content: "操作成功",
        });
        getRolesData({ pageNum: count });
      }
    } catch (error) {
      console.log(error);
    }
  };
  //修改角色信息
  const editRoleData = async (role: any) => {
    console.log(role);
    try {
      let { code, data } = await setRoleDataAPI(thisrole);
      // let a = await setRoleDataAPI(role);
      if (code === 1000) {
        thisrole = { ...thisrole, ...data };
        getRolesData({ ...queryTableDataParams, pageNum: count });
        messageApi.open({
          type: "success",
          content: "操作成功",
        });
        setIsModalOpen(false);
        form.setFieldsValue({
          roleName: "",
          roleKey: "",
          state: "0",
          dataScope: "1",
        });
      } else {
        messageApi.open({
          type: "error",
          content: "角色名称已存在！",
        });
      }
    } catch (error) {
      messageApi.open({
        type: "error",
        content: "系统未知错误",
      });
      console.log(error);
    }
  };
  useEffect(() => {
    // setQueryParams({...queryParams,...valueSch})
    queryTableDataParams = {
      ...queryTableDataParams,
      // ...searchValue,
      pageNum: count,
    };
    getRolesData(queryTableDataParams);
    // console.log(queryParams);
  }, [queryTableDataParams]);
  useEffect(() => {
    getMenuList();
  }, []);
  return (
    <ConfigProvider locale={zh_CN}>
      <div className="roleBox">
        <Form
          layout="inline"
          initialValues={undefined}
          form={formSearch}
          onFinish={handleSerach}
          style={{ fontWeight: "700" }}
        >
          <Form.Item
            label="角色名称"
            name="roleName"
            style={{ width: 300 + "px", marginTop: "10px" }}
          >
            <Input placeholder="请输入角色名称" allowClear />
          </Form.Item>
          <Form.Item
            label="权限字符"
            name="roleKey"
            style={{ width: 300 + "px", marginTop: "10px" }}
          >
            <Input allowClear placeholder="请输入权限字符" />
          </Form.Item>
          <Form.Item
            label="状态:"
            name="state"
            wrapperCol={{ span: 22 }}
            style={{ marginTop: "10px" }}
          >
            <Select
              style={{ width: 300 + "px", textAlign: "left" }}
              allowClear
              showSearch
              placeholder="请选择角色状态"
              optionFilterProp="lable"
              // onChange={onStateChange}
              // onSearch={onSearch}
              filterOption={filterOption}
              // value={searchValue.state}
              options={[
                {
                  value: "0",
                  label: "正常",
                },
                {
                  value: "1",
                  label: "停用",
                },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="登陆时间"
            name="dateTime"
            style={{ marginTop: "10px" }}
          >
            <Space direction="vertical" style={{ width: 400 + "px" }}>
              <RangePicker
                locale={dataLocale}
                showTime
                format="YYYY-MM-DD HH:mm:ss"
                onChange={onDateChange}
              />
            </Space>
          </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}
          okText="确定"
          cancelText="取消"
          onCancel={handleModalCanle}
          onOk={handleModalOk}
        >
          <Form
            form={form}
            layout="horizontal"
            name="form_in_modal"
            initialValues={{ dataScope: "1", state: "0" }}
          >
            <Form.Item
              name="roleName"
              label="角色名称"
              rules={[{ required: true, message: "请输入角色名称" }]}
            >
              <Input placeholder="请输入角色名称" />
            </Form.Item>
            <Form.Item
              name="roleKey"
              label="角色权限"
              rules={[{ required: true, message: "请输入角色权限" }]}
            >
              <Input placeholder="请输入角色权限" />
            </Form.Item>

            <Form.Item
              required
              name="roleSort"
              label="显示顺序"
              rules={[{ required: true, message: "请输入角色显示顺序" }]}
            >
              <InputNumber min={0} max={10} controls={true} />
            </Form.Item>
            <Form.Item name="dataScope" label="数据范围">
              <Radio.Group>
                <Radio value="1" defaultChecked={true}>
                  所有数据权限
                </Radio>
                <Radio value="2">自定义数据权限</Radio>
                <Radio value="3">本部门数据权限</Radio>
                <Radio value="4">本部门及以下数据权限</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="state"
              label="状态"
              className="collection-create-form_last-form-item"
            >
              <Radio.Group>
                <Radio defaultChecked={true} value="0">
                  正常
                </Radio>
                <Radio value="1">停用</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item
              name="menuIds"
              label="菜单权限"
              className="collection-create-form_last-form-item"
            >
              {/* <input type="text" /> */}
              <div className="checkBox">
                <Checkbox onChange={onCheckExpand}>展开</Checkbox>
                <Checkbox onChange={onCheckAll} checked={allChecked}>
                  全选
                </Checkbox>
                <Checkbox onChange={onCheckFaSon}>父子联动</Checkbox>
              </div>
              <div
                className="myTree"
                style={{ maxHeight: "250px", overflowY: "auto" }}
              >
                <Tree
                  fieldNames={fieldNames}
                  checkable
                  onExpand={onTreeExpand}
                  expandedKeys={expandedKeys}
                  autoExpandParent={true}
                  onCheck={onTreeCheck}
                  checkedKeys={checkedKeys}
                  checkStrictly={checkStrictly}
                  onSelect={onTreeSelect}
                  selectedKeys={selectedKeys}
                  treeData={menuTreeData}
                />
              </div>
            </Form.Item>
          </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>
  );
}
