import React, { useEffect, useRef, useState } from "react";
import type { ProColumns, ActionType, ProFormInstance } 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 { DataSetConfigModel } from '@/services/internalEvaluation/configuration/datasetconfig';
import { WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { deleteRows, getDataList, selectDetailData, updateExistData, createData } from "@/services/internalEvaluation/configuration/datasetconfig";
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 datasetconfig : React.FC<widowRush> = (prop:widowRush) => {

    /** 编辑方式，查看、修改、新增按钮时设置，详细信息表单中使用 */
    const [editType, setEditType] = useState<EditType>(prop.editType || 'display');
    /** 是否显示详细信息窗口 */
    const [detailVisible, setDetailVisible] = useState<boolean>(false);
    const [currentRow, setCurrentRow] = useState<DataSetConfigModel>();
    /** 表格引用对象，刷新表格使用   */
    const actionRef = useRef<ActionType>();
    const formRef = useRef<FormInstance<any>>();
    const templateRef = useRef<FormInstance<any>>();

    // 页面数据
    var formDataList = new Array<DataSetConfigModel>;
 
    useEffect(() => {

      }, []);
    
    // 修改查询查询
    const selectData = async (formdata : DataSetConfigModel) => {
      const data = await selectDetailData(formdata);
      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: DataSetConfigModel,) => {
    
    if (editType == 'update' ) {
       await updateExistData(data);
       closeAndRefresh();
    }
    else if (editType == 'create' ) {
      await createData(data);
      closeAndRefresh();
    }
    setDetailVisible(false);
  }
     
    // 数据项配置页面展示元素
    const columns: ProColumns<DataSetConfigModel>[] = [
        {
          title: '数据集编号', 
          dataIndex: 'dataSetNo',
          hideInTable: false,
        },
        {
          title: '数据集名称', 
          dataIndex: 'dataSetName',
          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>,
           
          ],
        },

      ];
    
    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:DataSetConfigModel) =>{
           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);
          }}
          >
            新增
          </SDButton>
         ]}
         formRef={formRef}
         setDetailVisible={() => {setDetailVisible(true)}}
         setEditType={setEditType}
         setCurrentRow={setCurrentRow}
         />

        {detailVisible && (
        <SDModalForm          
          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);
            }}>关闭</SDButton>
          ]}
          tableRef={actionRef}
          formRef={formRef}
        >
            <SDAreaTtile title='数据集配置信息'/>
            <SDFormText name="dataSetNo"  readonlyCond="update" required={true} rules={[
          { required: true, message: '请输入编号' },
          {
            validator:validateFun.account
          },
          {
            validator: (rule, value, callback)=> {
              if (firstCharIsNotNumber(value)>0) {
                callback('编号不能以数字开头');
              } else {
                callback();
              }

            }
          }
        ]} label="数据集编号"/>
            <SDFormText name="dataSetName" rules={[{validator:validateFun.chineseRex,message:'请输入中文'}]} label="数据集名称"/>
            <SDFormDict dictKey="@selectDataSource" name="dataSourcesNos" rules={[{required:true}]} multiple={true} label="数据源编号"/>
        </SDModalForm>
      )}
        </SDPage>
        
    );
}
export default datasetconfig;