import React, {useEffect, useRef, useState} from "react";
import {type ProColumns, type ActionType, type ProFormInstance, EditableProTable} from '@ant-design/pro-components';
import type {FormInstance} from 'antd'
import {
  SDPage,
  SDFormText,
  SDModalForm,
  SDTable,
  SDButton,
  SDSubmitButton,
  EditType,
  SDAreaTtile,
  SDOperate,
  baseFun,
  validateFun,
  SDFormDict,
} from "@sundata/ui-frame";
import type {
  DataSourcesModel,
  QueryLogicModel,
  DataItemConfigModel,
  InputParamModel
} from '@/services/internalEvaluation/configuration/datasources';
import {WomanOutlined} from "@ant-design/icons";
import {ProductProps} from "@/sundataImport";
import {
  deleteRows,
  getDataList,
  selectDetailData,
  updateExistData,
  createData
} from "@/services/internalEvaluation/configuration/datasources";
import {countChineseChars, firstCharIsNotNumber} from "../utils/rwacheckutils";

type widowRush = {
  onCancel: () => void;
  onChangeVisible(visible: boolean, type: string): unknown;
  onChangeVisdible: (visible: boolean, type ?: 'none' | 'raload') => void;
} & ProductProps;
const datasources: React.FC<widowRush> = (prop: widowRush) => {

  /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
  const [editType, setEditType] = useState<EditType>(prop.editType || 'display');
  /** 是否显示详细信息窗口 */
  const [detailVisible, setDetailVisible] = useState<boolean>(false);

  const [typeStatus, setTypeStatus] = useState<number>(0);

  const [currentRow, setCurrentRow] = useState<DataSourcesModel>();
  /** 表格引用对象，刷新表格使用   */
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance<any>>();
  const templateRef = useRef<FormInstance<any>>();
  const [inputParamList, setInputParamList] = useState<InputParamModel[]>();
  const [queryLogicList, setQueryLogicList] = useState<QueryLogicModel[]>();
  const [dataItemConfigList, setDataItemConfigList] = useState<DataItemConfigModel[]>();

  // 页面数据
  var formDataList = new Array<DataSourcesModel>;

  useEffect(() => {

  }, []);

  // 修改查询查询
  const selectData = async (formdata: DataSourcesModel) => {
    const data = await selectDetailData(formdata);
    if (data.dataSourcesType === "JDBC") {
      setTypeStatus(1)
    }else if (data.dataSourcesType === "INTERFACE") {
      setTypeStatus(2);
    } else {
      setTypeStatus(0);
    }
    setInputParamList(data.inputParam);
    setQueryLogicList(data.queryLogic);
    setDataItemConfigList(data.dataItemConfig);
    formRef.current?.setFieldsValue(data);
  }

  // 删除
  const delRows = async (record: any) => {
    baseFun.confirm('确认删除？', async () => {
      await deleteRows(record);
      baseFun.info("删除成功");
      closeAndRefresh();
    });

  }

  //关闭窗口刷新父页面
  const closeAndRefresh = () => {
    actionRef.current?.reloadAndRest?.();
  }

  // 插入或者更新数据
  const handleSave = async (data: DataSourcesModel) => {
    data.inputParam = inputParamList;
    data.queryLogic = queryLogicList;
    data.dataItemConfig = dataItemConfigList;

    if (editType == 'update') {
      await updateExistData(data);
      closeAndRefresh();
    } else if (editType == 'create') {
      await createData(data);
      closeAndRefresh();
    }
    setDetailVisible(false);
    setTypeStatus(0)
  }

  // 页面展示元素
  const columns: ProColumns<DataSourcesModel>[] = [
    {
      title: '数据来源名称',
      dataIndex: 'dataSourcesName',
      hideInTable: false,
    },
    {
      title: '数据来源编号',
      dataIndex: 'dataSourcesNo',
      search: false,
      hideInTable: false,
    },
    {
      title: '数据来源类型',
      dataIndex: 'dataSourcesType',
      search: false,
      hideInTable: false,
    },
    // {
    //   title: '数据源（请求接口）',
    //   dataIndex: 'requestInterface',
    //   search: false,
    //   hideInTable: false,
    // },
    {
      title: '操作',
      dataIndex: 'operate',
      valueType: 'option',
      render: (_, record) => [
        <SDOperate
          key="roleCfg"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              selectData(record);
              setDetailVisible(true);
              setEditType('update');
            }}
        >
          修改
        </SDOperate>,
        <SDOperate
          key="roleCfg"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={() => {
            delRows(record)
          }}
        >
          删除
        </SDOperate>,

      ],
    },

  ];


  // 输入参数页面展示元素
  const inputParamColumns: ProColumns<InputParamModel>[] = [
    {
      title: '数据来源编号',
      dataIndex: 'dataSourcesNo',
      search: false,
      hideInTable: true,
    },
    {
      title: '参数编号',
      dataIndex: 'paramNo',
      hideInTable: false,
    },
    {
      title: '参数名称',
      dataIndex: 'paramName',
      search: false,
      hideInTable: false,
      formItemProps: {
        rules: [
          {validator: validateFun.chineseRex, message: '请输入中文'},
        ]
      }
    },
    {
      title: '参数说明',
      dataIndex: 'paramDescribe',
      search: false,
      hideInTable: false,
    },
    {
      title: '参数中文名称',
      dataIndex: 'paramCName',
      search: false,
      hideInTable: false,
      formItemProps: {
        rules: [
          {validator: validateFun.chineseRex, message: '请输入中文'},
        ]
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.paramNo);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setInputParamList(...[inputParamList?.filter((item) => item.paramNo !== record.paramNo)]);
            console.log(inputParamList);
          }}
        >
          删除
        </a>,
      ],
    },
  ];


  // 查询逻辑页面展示元素
  const queryLogicColumns: ProColumns<QueryLogicModel>[] = [
    {
      title: '数据来源编号',
      dataIndex: 'dataSourcesNo',
      search: false,
      hideInTable: true,
    },
    {
      title: '查新逻辑编号',
      dataIndex: 'queryLogicNo',
      hideInTable: false,
    },
    {
      title: 'selectSql脚本',
      dataIndex: 'selectSqlScript',
      search: false,
      hideInTable: false,
    },
    {
      title: '脚本说明',
      dataIndex: 'scriptDescription',
      search: false,
      hideInTable: false,
    },
    {
      title: '数据项名称',
      dataIndex: 'dataItemName',
      search: false,
      hideInTable: false,
      formItemProps: {
        rules: [
          {
            validator: validateFun.account
          },
          {
            validator: (rule, value, callback) => {
              if (firstCharIsNotNumber(value) > 0) {
                callback('编号不能以数字开头');
              } else {
                callback();
              }

            }
          }
        ]
      }
    },
    {
      title: '数据项中文名称',
      dataIndex: 'dataItemCName',
      search: false,
      hideInTable: false,
      formItemProps: {
        rules: [
          {validator: validateFun.chineseRex, message: '请输入中文'},
        ]
      }
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.queryLogicNo);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setQueryLogicList(queryLogicList?.filter((item) => item.queryLogicNo !== record.queryLogicNo));
          }}
        >
          删除
        </a>,
      ],
    },

  ];

  // 数据项配置页面展示元素
  const dataItemConfigColumns: ProColumns<DataItemConfigModel>[] = [
    {
      title: '数据来源编号',
      dataIndex: 'dataSourcesNo',
      search: false,
      hideInTable: true,
    },
    {
      title: '数据项编号',
      dataIndex: 'dataItemNo',
      hideInTable: false,
    },
    {
      title: '数据项名称',
      dataIndex: 'dataItemName',
      search: false,
      hideInTable: false,
    },
    {
      title: '数据项路径',
      dataIndex: 'dataItemRoute',
      search: false,
      hideInTable: false,
    },
    {
      title: '数据项SQL',
      dataIndex: 'dataItemSql',
      search: false,
      hideInTable: false,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.dataItemNo);
          }}
        >
          编辑
        </a>,
        <a
          key="delete"
          onClick={() => {
            setDataItemConfigList(dataItemConfigList?.filter((item) => item.dataItemNo !== record.dataItemNo));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <SDPage>
      <SDTable
        title="查询表格"
        rowKey="customerName"
        request={async (formdata: DataSourcesModel) => {
          const formDatas = await getDataList(formdata);
          // 解构数组（导出用）
          formDataList = [...formDatas];
          return {data: formDatas}
        }}
        columns={columns}
        actionRef={actionRef}
        toolBarRender={(_: any, {selectedRows}: any) => [
          <SDButton
            successMessage=""
            onClick={() => {
              setEditType('create');
              setDetailVisible(true);
              setInputParamList([]);
              setQueryLogicList([]);
              setDataItemConfigList([]);
            }}
          >
            新增
          </SDButton>
        ]}
        formRef={formRef}
        setDetailVisible={() => {
          setDetailVisible(true)
        }}
        setEditType={setEditType}
        setCurrentRow={setCurrentRow}
      />

      {detailVisible && (
        <SDModalForm
          onValuesChange={(a,b) => {
            if (a.dataSourcesType === "JDBC"){
              setTypeStatus(1);
            }else if (a.dataSourcesType === "INTERFACE"){
              setTypeStatus(2);
            }else if (b.dataSourcesType === undefined){
              setTypeStatus(0);
            }
          }}
          title={'详细信息'}
          editType={editType}
          params={currentRow}
          visible={detailVisible}
          onVisibleChange={() => {
            setDetailVisible(false)
          }}
          footer={[
            <SDSubmitButton editType={editType} formRef={formRef} doSubmit={handleSave}>保存</SDSubmitButton>,
            <SDButton
              key="closeUpdate"
              successMessage=''
              onClick={() => {
                setDetailVisible(false);
                setTypeStatus(0)
              }}>关闭</SDButton>
          ]}
          tableRef={actionRef}
          formRef={formRef}
        >
          <SDAreaTtile title='数据来源信息'/>
          <SDFormText name="dataSourcesNo" rules={[
            {required: true, message: '请输入编号'},
            {
              validator: validateFun.account
            },
            {
              validator: (rule, value, callback) => {
                if (firstCharIsNotNumber(value) > 0) {
                  callback('编号不能以数字开头');
                } else {
                  callback();
                }

              }
            }
          ]} label="数据来源编号" readonlyCond="update"/>
          <SDFormText name="dataSourcesName"
                      rules={[{validator: validateFun.chineseRex, message: '请输入中文'}]} label="数据来源名称"/>
          <SDFormDict dictKey="DATASOURCETYPE" name="dataSourcesType" rules={[{required: true}]} label="数据来源类型"/>
          { typeStatus === 2 &&  <SDFormDict dictKey="@selectInterFaceData" name="requestInterfaces" rules={[{required: true}]}
                      label="数据源（请求接口）"/> }

          {typeStatus === 2 && <>
          <SDAreaTtile title='输入参数'/>
          <EditableProTable<InputParamModel>
            rowKey="paramNo"
            columns={inputParamColumns}
            value={inputParamList}
            dataSource={inputParamList}
            onChange={(value) => {
              setInputParamList([...value]);
            }}
            recordCreatorProps={
              {
                position: 'bottom',
                record: () => ({paramNo: (Math.random() * 1000000).toFixed(0)})
              }
            }
          /> </>}
          {typeStatus === 1 && <>
          <SDAreaTtile title='查询逻辑'/>
          <EditableProTable<QueryLogicModel>
            rowKey="queryLogicNo"
            columns={queryLogicColumns}
            value={queryLogicList}
            dataSource={queryLogicList}
            onChange={(value) => {
              setQueryLogicList([...value]);
            }}
            recordCreatorProps={
              {
                position: 'bottom',
                record: () => ({
                  queryLogicNo: (Math.random() * 1000000).toFixed(0),
                })
              }
            }
          /> </> }
          {typeStatus === 2 && <>
          <SDAreaTtile title='数据项配置'/>
          <EditableProTable<DataItemConfigModel>
            rowKey="dataItemNo"
            columns={dataItemConfigColumns}
            value={dataItemConfigList}
            dataSource={dataItemConfigList}
            onChange={(value) => {
              setDataItemConfigList([...value]);
            }}
            recordCreatorProps={
              {
                position: 'bottom',
                record: () => ({
                  dataItemNo: (Math.random() * 1000000).toFixed(0),
                })
              }
            }
          /> </> }

        </SDModalForm>
      )}
    </SDPage>

  );
}
export default datasources;
