import {forwardRef, memo, useCallback, useRef} from "react";
import {Button, Modal, Select, Space, Switch} from "antd";
import {EditableTags} from "../../../components/EditableTags";
import {useAppSelector} from "../../../../redux/configureStore";
import {selectRoles} from "../../MainPage/slice/selectors";

const component = forwardRef(({
  open,
  values,
  onCancel,
  onChange,
  onSubmit
},ref)=>{
  /** 角色列表 */
  const roles = useAppSelector(selectRoles);

  const dataRef = useRef({});

  // const onTagClose = useCallback((tags)=>{
  //   dataRef.current.tags = tags
  //   onChange && onChange(dataRef.current)
  // },[values]);

  /** 选择角色回调 */
  const onRolesChange = useCallback((value,option) => {
    dataRef.current.roles = option
    dataRef.current.tags = values
    onChange && onChange(dataRef.current)
  },[values]);

  /** 权限配置回调 */
  const onSwitchChange = useCallback((type,check)=>{
    dataRef.current[type] = check
    dataRef.current.tags = values
    onChange && onChange(dataRef.current)
  },[values])

  const onFinish = useCallback(()=>{
    onSubmit && onSubmit(dataRef.current)
  },[])

  return (
    <Modal
      width={800}
      title="批量授权"
      open={open}
      footer={[
        <Button key="previewer" onClick={()=>{}}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={onFinish} style={{marginRight:"40%",marginTop:50}}>
          保存
        </Button>
      ]}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
    >
      <EditableTags
        style={{width:'95%',height:200}}
        tagStyle={{marginBottom:10}}
        options={values}
        // onClose={onTagClose}
        // closable={true}
      />
      <span>授权对象：</span>
      <Select
        showSearch
        style={{width:'70%'}}
        mode="multiple"
        placeholder="选择授权角色"
        maxTagCount="responsive"
        optionFilterProp="label"
        onChange={onRolesChange}
        options={roles.map(item=>({label:item.name,value:item.id}))}
      />
      <Space style={{marginTop: 15}} size="large">
        <span>
          允许创建新版本 <Switch checkedChildren="开" unCheckedChildren="关" onChange={(e)=>onSwitchChange("version",e)}/>
        </span>
        <span>
          允许查看指标 <Switch checkedChildren="开" unCheckedChildren="关" onChange={(e)=>onSwitchChange("detail",e)}/>
        </span>
        <span>
          允许发布指标 <Switch checkedChildren="开" unCheckedChildren="关" onChange={(e)=>onSwitchChange("publish",e)}/>
        </span>
      </Space>
    </Modal>
  )
})

export const VolumeAuthPanel = memo(component)
