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";
import useI18NPrefix from "../../../hooks/useI18NPrefix";

const component = forwardRef(({
  open,
  values,
  onCancel,
  onChange,
  onSubmit
},ref)=>{
  const t = useI18NPrefix('global');
  /** 角色列表 */
  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)
  },[open])

  return (
    <Modal
      width={800}
      title={t("title.batchAuth")}
      open={open}
      footer={[
        <Button key="previewer" onClick={onCancel}>
          {t("button.cancel")}
        </Button>,
        <Button key="submit" type="primary" onClick={onFinish} style={{marginRight:"40%",marginTop:50}}>
          {t("button.save")}
        </Button>
      ]}
      maskClosable={false}
      destroyOnClose
      onCancel={onCancel}
    >
      <EditableTags
        style={{width:'95%',height:200}}
        tagStyle={{marginBottom:10}}
        options={values}
        // onClose={onTagClose}
        // closable={true}
      />
      <span>{t("title.authGoal")}：</span>
      <Select
        showSearch
        style={{width:'70%'}}
        mode="multiple"
        placeholder={t("placeholder.role")}
        maxTagCount="responsive"
        optionFilterProp="label"
        onChange={onRolesChange}
        options={roles.map(item=>({label:item.name,value:item.id}))}
      />
      <Space style={{marginTop: 15}} size="large">
        <span>
          {t("columns.allowCreateVersion")} <Switch onChange={(e)=>onSwitchChange("version",e)}/>
        </span>
        <span>
          {t("columns.allowDetail")+t("columns.metric")} <Switch onChange={(e)=>onSwitchChange("detail",e)}/>
        </span>
        <span>
          {t("columns.allowPublish")+t("columns.metric")} <Switch onChange={(e)=>onSwitchChange("publish",e)}/>
        </span>
      </Space>
    </Modal>
  )
})

export const VolumeAuthPanel = memo(component)
