import React, { useEffect, useRef, useState, } from 'react';
import type { EditableFormInstance, ProColumns, } from '@ant-design/pro-components';
import {
  baseFun,
  SDAreaTtile,
  SDButton,
  SDEditableTable,
  SDLayout,
  SDPage,
} from '@sundata/ui-frame';
import type { SysSqlEditDefOperateModel } from './../../../services/pubMng/defOperate';
import { vailOperName } from './../../../services/pubMng/defOperate';
import { saveOperateDefineList } from './../../../services/pubMng/defOperate';
import { getDataList } from './../../../services/pubMng/defOperate';
import { useModel } from '@umijs/max';


const DefOperate: React.FC = () => {

  /** 字段数据 */
  const [fieldDataSource, setFieldDataSource] = useState<readonly SysSqlEditDefOperateModel[]>();
  // 可编辑表格的引用
  const tableRef = useRef<EditableFormInstance>();
  const { fetchDict } = useModel('dict');
  
  /**关系维护 */
  const getListFun = async () => {
    const resu = await getDataList();
    setFieldDataSource(resu);
  }
  useEffect(() => {
    getListFun();
  }, []);

  const saveinfo = async () => {

     // 检查表格编辑状态
     const editingRows = tableRef.current?.getRowsData?.();
     if (editingRows && editingRows.length > 0) {
       baseFun.warning('参数列表中有正在编辑的参数，请确认或取消修改后再保存');
       return;
     }
    if (!fieldDataSource) {
      return;
    }
    for (let i = 0; i < fieldDataSource.length; i++) {
      if (fieldDataSource[i].operusemode == 'attribute' && fieldDataSource[i].datatype == "") {
        baseFun.warning("操作符" + fieldDataSource[i].opercode + "使用方式为属性时数据类型不能为空!");
        return;
      }
      for (let j = 0; j < fieldDataSource.length; j++) {
        if (fieldDataSource[i].opercode == fieldDataSource[j].opercode && i != j) {
          baseFun.warning("操作符" + fieldDataSource[i].opercode + "不唯一");
          return;
        }
        if (fieldDataSource[i].opername == fieldDataSource[j].opername && i != j) {
          baseFun.warning("操作符名称 " + fieldDataSource[i].opername + " 不唯一");
          return;
        }
      }
    }
    //保存
    await saveOperateDefineList([...(fieldDataSource || [])]);
    baseFun.info('处理完成');
  }


  const filedColumns: ProColumns<SysSqlEditDefOperateModel>[] = [
    {
      title: '使用方式',
      dataIndex: 'operusemode',
      valueType: 'select',
      search: false,
      request: () => fetchDict({ dictKey: 'operusemode' }),
      formItemProps: () => {
        return {
          rules: [{ required: true }],
        };
      },
    },
    {
      title: '操作符',
      dataIndex: 'opercode',
      search: false,
      valueType: 'text',
      //render:
      formItemProps: () => {
        return {
          rules: [
            { required: true },
          ],
        };
      },
    },
    {
      title: '操作参数',
      dataIndex: 'operpara',
      search: false,
      formItemProps: () => {
        return {
          rules: [{ max: 20, message: '最多20个字符' }],
        };
      },
    },
    {
      title: '操作名称',
      dataIndex: 'opername',
      search: false,
      formItemProps: () => {
        return {
          rules: [
            { max: 60, message: '最多60个字符' },
            { required: true },
            {
              validator: async (rule, value,) => {

                if (value) {
                  if (value.indexOf(" ") != -1) {
                    return Promise.reject(new Error("操作名称[" + value + "]不能含有空格!"));
                  }
                  if (value.indexOf(".") != -1) {
                    return Promise.reject(new Error("操作名称[" + value + "]不能含有点号!"));
                  }
                }
                const rs = await vailOperName(value);
                if (!rs) {
                  return Promise.reject(new Error("操作名称与编辑器变量名重复"));
                }
                return Promise.resolve();
              }
            },
          ],
        };
      },
    },
    {
      title: '数据类型',
      dataIndex: 'datatype',
      search: false,
      valueType: 'select',
      request: () => fetchDict({ dictKey: 'datatype' }),
    },
    {
      title: '操作说明',
      dataIndex: 'opercomment',
      search: false,
      ellipsis: true,
      valueType: 'textarea',
      formItemProps: () => {
        return {
          rules: [{ max: 200, message: '最多200个字符' }],
        };
      },
    },

  ];



  return (
    <SDPage 
    footer={[<SDButton autoLoading={true}  successMessage='' primary key='save' onClick={saveinfo} >保存</SDButton>]}
    >
      <SDAreaTtile title="数据操作定义"/>
      <SDLayout>
      <SDEditableTable
        columns={filedColumns}
        value={fieldDataSource || []}
        //insertDelete={false}
        editable={true}
        dragable={true}
        onChange={(value: any)=>{setFieldDataSource(value)}}
        formRef={tableRef}
        //bodyMaxHeight='calc(100vh - 350px)'
      />
      </SDLayout>
    </SDPage>
  );
};
export default DefOperate;
