import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux'
import { Table, Modal, message, Menu, Breadcrumb, Dropdown, Space, Form, Input, Button, Row, Col, Select } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AddFunc from './AddFunc';
// import './index.less';
import apiObj from '@api/index';
import FuncContext from './func-context';
import { pickCheckedTreeIds } from '@utils/index'
const { post, api, xPost } = apiObj;
const { Option } = Select;
function OrgManager() {
  useEffect(() => {
    //刷新列表
    getMenusTree();
  }, []);
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);   //列表数据
  const [visible, setVisible] = useState(false);   //删除禁用确认弹窗显示
  const [addVisible, setAddVisible] = useState(false);         //新增页面显示
  const [modalType, setModalType] = useState(1);
  const [id, setId] = useState('');    //当前操作功能id
  const [funcDetail, setFuncDetail] = useState(null);
  const [typeId, setTypeId] = useState('');
  const [title, setTitle] = useState('');
  const [type, setType] = useState('');
  //从state中取出状态、类型列表
  const userInfo = useSelector(state => {
    return state.userInfo;
  });
  const { sysId, sysName } = userInfo;
  const tipText = {
    1: '确定要删除该功能？',
    2: '确定要禁用该功能？',
  };
  //获取表格数据
  function getMenusTree(param = {}) {
    post(api.getMenusTree, param).then((res) => {
      if (res.data.code === 200) {
        const data = res.data.data;
        setDataSource(data);
      }

    })
  }
  //启用/禁用
  function enable(flag, id, type) {
    const param = { id: id, status: flag };
    xPost(api.disableMenu, param).then((res) => {
      if (res.data.code === 200) {
        getMenusTree();
        setVisible(false);
        message.success((flag ? '启用' : '禁用') + "成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  //删除
  function onDelete() {
    const param = { id: id };
    xPost(api.deleteMenu, param).then((res) => {
      if (res.data.code === 200) {
        getMenusTree();
        setVisible(false);
        message.success("删除成功");
      } else {
        message.warning(res.data.message || '操作失败');
      }
    }).catch(() => {
      message.error("接口出错");
    });
  }
  //显示弹窗
  function showModal(name, type, flag, id) {
    setTitle(name);
    setAddVisible(type)
    setType(flag)
    setId(id)
    if (flag == 2 || flag == 4) {
      getMenuById(id)
    } else if (flag == 1) {
      setFuncDetail({
        status: 1,
        parentId: 0,
        parentName: sysName
      })
    }
  }
  //新增子功能
  function addSubFunc(name, type, flag, id, parentName) {
    setTitle(name);
    setAddVisible(type)
    setType(flag)
    setFuncDetail({
      status: 1,
      parentId: id,
      parentName: parentName,
    })
  }
  //弹窗确认事件
  function handleOk() {
    if (modalType == 1) {
      onDelete();
    } else if (modalType == 2) {
      enable(0, id);
    }
  }
  const messageBox = (type, id) => {
    setVisible(true)
    setId(id)
    setModalType(type)
  }
  //弹窗取消
  function handleCancel() {
    setVisible(false);
  }
  function getMenuById(id) {
    xPost(api.getMenuById, { id: id, softwareId: sysId }).then((res) => {
      const { data, code } = res.data;
      if (code === 200) {
        const detail = data
        detail.softwares = [detail.softwareId]
        setFuncDetail(detail)
      } else {
        message.warning(res.data.message || '获取详情失败')
      }
    });
  }
  function cancel() {
    setAddVisible(false)
    setFuncDetail(null)
  }
  //表格渲染
  function RenderTable() {
    const columns = [
      { title: '组织机构层级', dataIndex: 'name', key: 'name' },
      { title: '类型', dataIndex: 'typeName', key: 'type', },
      {
        title: '链接地址', key: 'type', render: (row) => {
          if (row.children) {
            return '-'
          } else {
            return row.permission;
          }
        }
      },
      { title: '权限标识', dataIndex: 'code', key: 'code' },
      {
        title: '状态', key: 'status', render: (row) => {
          return (<span className={(row.status === '1') ? 'Enable' : 'Disable'}>{row.statusName}</span>);
        }
      },
      { title: '排序', dataIndex: 'orderNo', key: 'orderNo' },
      {
        title: '操作', width: 240, key: 'operation', render: (row) => {
          if (row.rootFlag) {
            return '-'
          }
          const menu = (
            <Menu>
              <Menu.Item key="0" className="menuItem">
                {row.status === '1' ? (<a onClick={() => messageBox(2, row.id)}>禁用</a>) : (<a onClick={() => enable(1, row.id)}>启用</a>)}
              </Menu.Item>
              <Menu.Item className="menuItem" key="1" onClick={() => messageBox(1, row.id)}>删除</Menu.Item>
            </Menu>
          );
          return (<Space size="middle">
            <a onClick={() => addSubFunc('新增子功能', true, 3, row.id, row.name)}>新增子功能</a>
            <a onClick={() => showModal('修改功能', true, row.parentId=='0'?2:4, row.id, row.softwareId)}>修改</a>
            <Dropdown overlay={menu} trigger={['click']}>
              <a className="ant-dropdown-link">
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </Space>)
        }
      },
    ];
    return (
      <Table
        pagination={false}
        scroll={{ y: 'calc(100vh - 280px)' }}
        className="components-table-demo-nested"
        rowKey={record => record.id}
        columns={columns}
        dataSource={dataSource}
      />
    )
  }
  const onFinish = (values: any) => {
    getMenusTree(values);
    console.log('筛选项:', values);
  };
  function userChange() {
    setAddVisible(false)
    setFuncDetail(null)
    getMenusTree();
  }
  return (
    <div className='wrapper'>
      <div className="table">
        <div className="table-header">
          <h2 className="table-title">功能管理</h2>
          <Button type="primary" icon={<PlusOutlined />} onClick={e => showModal('新增一级功能', true, 1)}>新增一级功能</Button>
        </div>
        <RenderTable />
      </div>
      {addVisible && funcDetail ?
        <Modal
          title={title}
          okText='确定'
          cancelText='取消'
          width={'45%'}
          visible={addVisible}
          onCancel={cancel}
          footer={null}
          forceRender={true}
        >
          <FuncContext.Provider value={{ type: type, id: id, detail: funcDetail }}>
            <AddFunc userChange={userChange} />
          </FuncContext.Provider>

        </Modal>
        : ''}
      <Modal
        title="提示"
        okText='确定'
        cancelText='取消'
        width={400}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>{tipText[modalType]}</p>
      </Modal>
    </div>
  )
}

export default OrgManager;