import {ProCard, ProForm, ProFormSelect, ProFormText} from "@ant-design/pro-components";
import {CheckCardList} from "../../components/CheckCardList";
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {selectDBSource} from "../MainPage/slice/selectors";
import {useCallback, useEffect, useMemo, useRef, useState} from "react";
import {createOrUpdateDatabase, getDBSource, testConnect} from "../MainPage/slice/thunks";
import {DATABASE_TYPES} from "../../constants";
import {PlusOutlined} from "@ant-design/icons";
import {message, Tooltip} from "antd";
import useI18NPrefix from "../../hooks/useI18NPrefix";

export const DatabaseSourcePage=()=>{
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const formRef = useRef();
  const sourceRef = useRef();

  /** 数据源 */
  const dbSource = useAppSelector(selectDBSource);

  /** 临时数据源 */
  const [tempSource, setTempSource] = useState(null);

  /** 初始化获取列表*/
  useEffect(() => {
    dispatch(getDBSource())
  }, []);

  /** 数据源列表 */
  const dbSourceList = useMemo(
    ()=> {
      if (tempSource){
        let temp = dbSource.map(value=>({value, title: value.name}))
        temp.unshift(tempSource)
        return temp
      }
      return dbSource.map(value=>({value, title: value.name}))
    }
    ,[dbSource,tempSource]
  )

  /** 数据源点击回显 */
  const onCardSelect = useCallback((value)=>{
    sourceRef.current =value;
    if (value?.id){
      formRef?.current?.setFieldsValue(value)
    }else {
      formRef?.current?.resetFields();
    }
  },[])

  /** 搜索数据源*/
  const onSearch = useCallback((e)=>{

  },[])

  const onFinish=useCallback(()=>{
    setTempSource(null)
    let params = formRef.current?.getFieldsFormatValue();
    const sourceId = sourceRef?.current?.id
    if (sourceId){
      params.id = sourceId
    }
    dispatch(createOrUpdateDatabase({
      params,
      resolve(){
        dispatch(getDBSource())
      }
    }))
    if (!sourceId){
      formRef?.current?.resetFields();
    }
  },[])

  const submitter = {
    submitButtonProps: {
      style: {
        marginLeft: 20,
        marginTop: 20
      }
    },
    resetButtonProps: {
      style: {
        marginTop: 20,
        marginLeft: '40%'
      }
    }
  }

  /** 添加一个临时数据源*/
  const addDBSource = useCallback(() => {
    setTempSource({title:t("title.datasourceCreate"),value: {}})
  },[])

  /** 添加一个临时数据源*/
  const connectTest=useCallback(async ()=>{
    const params = await formRef.current?.validateFieldsReturnFormatValue?.();
    if (params){
      dispatch(testConnect({
        params,
        resolve(data){
          if (data){
            message.success(t("validation.connected"))
          }else {
            message.error(t("validation.connectFailure"))
          }
        }
      }))
    }
  },[])

  /** 自动填充 */
  const onFieldsChange = useCallback(()=>{
    const formValue = formRef.current?.getFieldsFormatValue();
    formRef.current?.setFieldValue(
      'url',
      `jdbc:mysql://${formValue?.host}:${formValue?.port}/${formValue?.name}?useUnicode=true&characterEncoding=UTF-8&useSSL=false`
    )
  },[])

  return (
    <ProCard gutter={8} ghost >
      <ProCard
        bordered
        colSpan="20%"
        title={t("title.datasource")}
        headerBordered
        style={{height:'84vh'}}
        extra={
          <Tooltip title={t("title.datasourceCreate")}>
            <a onClick={addDBSource}>
              <PlusOutlined/>
            </a>
          </Tooltip>
        }
      >
        <CheckCardList
          options={dbSourceList}
          onSelect={onCardSelect}
          onSearch={onSearch}
        />
      </ProCard>
      <ProCard bordered headerBordered title={t("title.datasourceConfig")} style={{height:'84vh'}}>
        <ProForm
          formRef={formRef}
          layout="horizontal"
          onFinish={onFinish}
          labelCol={{span: 6}}
          wrapperCol={{span: 14}}
          submitter={submitter}
        >
          <ProFormText
            name="name"
            label={t("formItem.datasourceName")}
            rules={[{required: true}]}
            fieldProps={{
              onChange:onFieldsChange
            }}
          />
          <ProFormSelect
            name="type"
            label={t("formItem.type")}
            rules={[{required: true}]}
            options={
              DATABASE_TYPES.map(value=>({title:value,value}))
            }
          />
          <ProFormText
            name="host"
            label={t("formItem.host")}
            rules={[{required: true}]}
            fieldProps={{
              onChange:onFieldsChange
            }}
          />
          <ProFormText
            name="port"
            label={t("formItem.port")}
            rules={[{required: true}]}
            fieldProps={{
              onChange:onFieldsChange
            }}
          />
          <ProFormText
            name="username"
            label={t("formItem.username")}
            rules={[{required: true}]}
          />
          <ProFormText.Password
            name="password"
            label={t("formItem.password")}
            rules={[{required: true}]}
          />
          <ProFormText
            name="url"
            label={t("formItem.url")}
            rules={[{required: true}]}
            fieldProps={{
              suffix:<a onClick={connectTest}>测试连接</a>,
              allowClear:false
            }}
          />
          <ProFormText
            name="description"
            label={t("formItem.datasourceDesc")}
          />
        </ProForm>
      </ProCard>
    </ProCard>
  )
}