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, getConditions, getDomains} from "../MainPage/slice/thunks";
import {LOGIC_TYPE} from "../IndexDefine/constants";
import {selectConditions} from "../MainPage/slice/selectors";

const baseColumns = [
  {
    title: '限定规则名称',
    dataIndex: 'name',
  },
  {
    title: '限定规则编码',
    dataIndex: 'code',
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueType: 'select',
    valueEnum: STATUS_TYPE,
  },
  {
    title: '规则描述',
    dataIndex: 'desc',
  },
  {
    title: '英文名称',
    dataIndex: 'english',
  },
  {
    title: '关联指标',
    dataIndex: 'index_s',
  }
]

export const ConditionManage = () => {
  //console.log('cond')
  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
    })
    setColumns(columnInfo)
  };

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

  /** 提交表单 */
  const onSubmit = useCallback(
    (values)=> {
      // 组织数据
      const {attributes,name,domainId,modelId} = values;
      let defaultConfig = "";
      if (attributes){
        for (let i = attributes.length - 1; i >= 0; i--) {
          const {value,logic,fields,condition} = attributes[i];
          const cdt = condition?condition:""
          if (LOGIC_TYPE[logic]==="包含" || LOGIC_TYPE[logic]==="不包含"){
            defaultConfig +=` ${cdt} ${fields} ${logic} '%${value}%'`
            continue
          }
          if (LOGIC_TYPE[logic]==="为空"||LOGIC_TYPE[logic]==="不为空"){
            defaultConfig +=` ${cdt} ${fields} ${logic}`
            continue
          }
          defaultConfig +=` ${cdt} ${fields} ${logic} ${value} `
        }
      }
      const params = {
        status:1,
        defaultConfig,
        name,
        modelId,
        domainId
      }
      console.log(params)
      dispatch(createCondition({
        params,
        resolve(){
          message.success("保存成功")
          actionRef.current?.reload()
        }
      }))
    },[]
  );
  return (
    <>
      <ProTable
        {...ProTableDefault}
        headerTitle="业务限定列表"
        actionRef={actionRef}
        columns={columns}
        dataSource={conditions}
        request={async (params) => {
          await dispatch(getConditions({params}))
        }}
        pagination={{
          pageSize: 5,
          onChange: (page) => console.log(page),
        }}
        toolBarRender={() => [
          <Button
            ref={ref1}
            key="button"
            icon={<PlusOutlined/>}
            onClick={() => handleEdit()}
            type="primary"
          >
            新建
          </Button>
        ]}
      />
      <Drawer
        title="创建业务限定"
        width={1230}
        styles={{body:{padding:'0'}}}
        open={open}
        maskClosable={false}
        destroyOnClose
        onClose={handleCancel}
        footer={[
          <Button key="previewer" style={{marginLeft:'45%'}} onClick={handleCancel}>
            取消
          </Button>,
          <Button key="submit" style={{marginLeft:15}} type="primary" onClick={()=>formRef?.current?.submit()}>
            保存
          </Button>
        ]}
      >
        <BizConditionForm ref={formRef} data={record} onSubmit={onSubmit} />
      </Drawer>
    </>
  );
}
