import React, { useState, useCallback, useEffect } from 'react';
import { Modal, Spin, Tabs, notification, message, Checkbox, Divider } from 'antd';
import { SetUserRelationList, setUserRelation, setUserRelations } from '@/services/userManage/api';
import ListCardItem from './components/listCardItem';
const CheckboxGroup = Checkbox.Group;

const RelateRoleModal = props => {
  const {
    currentUser,
    currentSelectOrg,
    userIDs,
    visible,
    rolelist,
    stationlist,
    multiRelateRoles,
    onCancel,
    onSelect,
    loading,
    multiRoleList,
    multistationList,
    mult,
  } = props;
  const { TabPane } = Tabs;
  const [roleValueList, setRoleValueList] = useState({}); // 勾选的角色列表
  const [stationValueList, setStationValueList] = useState({}); // 勾选的站点列表
  const authority = localStorage.getItem('panda-oms-authority');
  const [activeKey, setActiveKey] = useState('1');

  const getRoleValueCallback = useCallback((value, index) => {
    console.log(value);
    roleValueList[index] = value;
    console.log(roleValueList);
    setRoleValueList({ ...roleValueList });
    console.log({ ...roleValueList });
  }, []);

  const getStationValueCallback = useCallback((value, index) => {
    console.log(value);
    stationValueList[index] = value;
    console.log(stationValueList);
    setStationValueList({ ...stationValueList });
  }, []);

  useEffect(() => {
    if (!visible) {
      setActiveKey('1');
    }
    console.log(currentUser);
    console.log(multiRoleList);
    console.log(multistationList);
  }, [visible]);

  // 提交-关联角色
  const submitRole = () => {
    console.log(1212121212);
    SetUserRelationList(
      currentUser.userID,
      Object.keys(roleValueList)
        .map(k => roleValueList[k])
        .flat(),
      Object.keys(stationValueList)
        .map(k => stationValueList[k])
        .flat(),
    )
      .then(res => {
        if (res.code == 0) {
          onCancel();
          // 跳转到新组织机构下的用户表
          if (currentSelectOrg !== '-1') {
            onSelect([currentSelectOrg]);
          }
          notification.success({
            message: '提交成功',
            duration: 2,
          });
        } else {
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };
  // 提交-批量关联角色
  const submitRoles = () => {
    console.log(64634676437);
    setUserRelations(
      userIDs,
      Object.keys(roleValueList)
        .map(k => roleValueList[k])
        .flat()
        .toString(),
      Object.keys(stationValueList)
        .map(k => stationValueList[k])
        .flat()
        .toString(),
    )
      .then(res => {
        if (res.code === 0) {
          onCancel();
          // 跳转到组织重新请求该机构下用户数据,查找用户时currentSelectOrg为'-1'，不需要重新请求
          if (currentSelectOrg !== '-1') {
            onSelect([currentSelectOrg]);
          }
          notification.success({
            message: '提交成功',
            duration: 2,
          });
        } else {
          console.log(1);
          notification.error({
            message: '提交失败',
            description: res.msg,
          });
        }
      })
      .catch(err => {
        message.error(err);
      });
  };
  const onChangeList = () => {};
  const title = (
    <span>
      <span style={{ marginRight: '20px' }}>批量关联角色</span>
      <span style={{ color: 'red' }}>提示：批量关联角色会覆盖原有角色</span>
    </span>
  );
  const title1 = (
    <span>
      <span>
        关联权限
        <span style={{ fontWeight: 'bold', color: 'rgb(24, 144, 255)' }}>
          【{currentUser.userName}】
        </span>
      </span>
    </span>
  );
  const onChange = e => {
    console.log(e);
    setActiveKey(e);
  };
  if (mult == 'Yes') {
    return (
      <Modal
        title={title}
        visible={visible}
        onOk={submitRoles}
        maskClosable={false}
        destroyOnClose
        onCancel={onCancel}
        okText="确认"
        cancelText="取消"
        width="500px"
      >
        <Spin spinning={loading} tip="loading">
          <Tabs activeKey={activeKey} onChange={onChange} style={{ marginTop: '-16px' }}>
            <TabPane tab="角色" key="1">
              {visible &&
                rolelist.map((role, index) => (
                  <ListCardItem
                    style={{ display: 'none' }}
                    itemid={index}
                    key={`item${index}key`}
                    userList={role.roleList}
                    multiRoleList={multiRoleList}
                    mult={mult}
                    OUName={role.visibleTitle}
                    getValueCallback={getRoleValueCallback}
                  />
                ))}
            </TabPane>
            <TabPane tab="站点" key="2">
              {visible &&
                stationlist.map((station, index) => (
                  <ListCardItem
                    itemid={index}
                    key={`item${index}key`}
                    userList={station.stationList}
                    multistationList={multistationList}
                    mult={mult}
                    OUName={station.visibleTitle}
                    getValueCallback={getStationValueCallback}
                  />
                ))}
            </TabPane>
          </Tabs>
        </Spin>
      </Modal>
    );
  }
  return (
    <Modal
      title={multiRelateRoles ? title : title1}
      visible={visible}
      onOk={multiRelateRoles ? submitRoles : submitRole}
      onCancel={onCancel}
      maskClosable={false}
      okText="确认"
      cancelText="取消"
      width="500px"
    >
      <Spin spinning={loading} tip="loading">
        <Tabs activeKey={activeKey} onChange={onChange} style={{ marginTop: '-16px' }}>
          <TabPane tab="角色" key="1">
            {visible &&
              rolelist.map((role, index) => (
                <ListCardItem
                  itemid={index}
                  key={`item${index}key`}
                  userList={role.roleList}
                  mult={mult}
                  OUName={role.visibleTitle}
                  getValueCallback={getRoleValueCallback}
                />
              ))}
          </TabPane>
          <TabPane tab="站点" key="2">
            {visible &&
              stationlist.map((station, index) => (
                <ListCardItem
                  itemid={index}
                  key={`item${index}key`}
                  userList={station.stationList}
                  mult={mult}
                  OUName={station.visibleTitle}
                  getValueCallback={getStationValueCallback}
                />
              ))}
          </TabPane>
        </Tabs>
      </Spin>
    </Modal>
  );
};

export default RelateRoleModal;
