import { PlusOutlined} from '@ant-design/icons';
import {ProTable} from '@ant-design/pro-components';
import {Button, Drawer, message} from 'antd';
import {useCallback, useEffect, useRef, useState} from 'react';
import {columnsFactory} from '../../../utils/columnsFactory.jsx';

import {BizConditionForm} from './BizConditionForm';
import {ProTableDefault, STATUS_TYPE} from '../../constants.js';
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {createCondition, deleteCondition, getConditions, getDomains} from "../MainPage/slice/thunks";
import {selectConditions} from "../MainPage/slice/selectors";
import {bizConditionToSQL} from "../../../utils/listTools";
import useI18NPrefix from "../../hooks/useI18NPrefix";

export const ConditionManage = () => {
  const t = useI18NPrefix('global');
  const baseColumns = [
    {
      title: t("columns.bizRuleName"),
      dataIndex: 'name',
    },
    {
      title: t("columns.bizRuleCode"),
      dataIndex: 'defaultConfig',
    },
    {
      title: t("columns.bizRuleDesc"),
      dataIndex: 'description',
    },
    {
      title: t("columns.english"),
      dataIndex: 'english',
    },
    {
      title: t("columns.index_s"),
      dataIndex: 'index_s',
    },
    {
      title: t("columns.status"),
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: STATUS_TYPE,
    },
  ]
  const dispatch = useAppDispatch();
  const formRef = useRef();
  const actionRef = useRef();
  const ref1 = useRef(null);
  const conditions = useAppSelector(selectConditions);
  const [columns, setColumns] = useState([]);
  const [record,setRecord]=useState({});

  /** 表单对话框 */
  const [open, setOpen] = useState(false);
  const handleCancel = () => {
    setOpen(false);
  };

  /** 初始渲染的钩子 */
  useEffect(() => {
    dispatch(getDomains())
    getColumns()
  }, []);

  /** 格式化表头 */
  const getColumns = () => {
    const columnInfo = columnsFactory({
      dataSource: baseColumns,
      onEdit:handleEdit,
      onDelete:handleDelete
    })
    setColumns(columnInfo)
  };

  /** 打开 新增、编辑 对话框 */
  const handleEdit=(row)=>{
    setRecord(row)
    setOpen(true)
  };

  /** 打开 新增、编辑 对话框 */
  const handleDelete=(row,reload)=>{
    dispatch(deleteCondition({
      id:row?.id,
      resolve(){
        message.success(t("validation.success"))
        reload()
      }
    }))

  };

  /** 提交表单 */
  const onSubmit = useCallback(
    (values)=> {
      const defaultConfig = values?.type==="logic" ? bizConditionToSQL(values?.filters) :values?.defaultConfig
      const params = {
        ...values,
        status:1,
        defaultConfig,
      }
      dispatch(createCondition({
        params,
        resolve(){
          message.success(t("validation.success"))
          actionRef.current?.reload()
        }
      }))
    },[]
  );
  return (
    <>
      <ProTable
        {...ProTableDefault}
        headerTitle={t("title.bizList")}
        actionRef={actionRef}
        columns={columns}
        dataSource={conditions}
        request={async (params) => {
          await dispatch(getConditions({params}))
        }}
        pagination={{
          pageSize: 20,
          onChange: (page) => console.log(page),
        }}
        toolBarRender={() => [
          <Button
            ref={ref1}
            key="button"
            icon={<PlusOutlined/>}
            onClick={() => handleEdit()}
            type="primary"
          >
            {t("button.create")}
          </Button>
        ]}
      />
      <Drawer
        title={t("title.bizCreate")}
        width={1230}
        styles={{body:{padding:'0'}}}
        open={open}
        maskClosable={false}
        destroyOnClose
        onClose={handleCancel}
        footer={[
          <Button key="previewer" style={{marginLeft:'45%'}} onClick={handleCancel}>
            {t("button.cancel")}
          </Button>,
          <Button key="submit" style={{marginLeft:15}} type="primary" onClick={()=>formRef?.current?.submit()}>
            {t("button.submit")}
          </Button>
        ]}
      >
        <BizConditionForm ref={formRef} data={record} onSubmit={onSubmit} />
      </Drawer>
    </>
  );
}
