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 { IndexConfigModel, IndexSourceModel } from '@/services/internalEvaluation/configuration/indexconfig';
import { WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { deleteRows, getDataList, selectDetailData, updateExistData, createData } from "@/services/internalEvaluation/configuration/indexconfig";
import { countChineseChars, firstCharIsNotNumber } from "../utils/rwacheckutils";
import { useModel } from '@umijs/max';

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

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

    // 页面数据
    var formDataList = new Array<IndexConfigModel>;
    const { fetchDict } = useModel('dict');

    const [indexSourceList, setIndexSourceList] = useState<IndexSourceModel[]>();

    useEffect(() => {

      }, []);

    // 修改查询查询
    const selectData = async (formdata : IndexConfigModel) => {
      const data = await selectDetailData(formdata);
      formRef.current?.setFieldsValue(data);
      setIndexSourceList(data.indexDataSource);
     }

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

     }

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

  // 插入或者更新数据
  const handleSave = async(data: IndexConfigModel,) => {
    data.indexDataSource = indexSourceList;
    if (editType == 'update' ) {
       await updateExistData(data);
       closeAndRefresh();
    }
    else if (editType == 'create' ) {
      await createData(data);
      closeAndRefresh();
    }
    setDetailVisible(false);
  }

    // 数据项配置页面展示元素
    const columns: ProColumns<IndexConfigModel>[] = [
        {
          title: '指标编号',
          dataIndex: 'indexNo',
          hideInTable: false,
        },
        {
          title: '指标名称',
          dataIndex: 'indexName',
          search: false,
          hideInTable: false,
          formItemProps:{
            rules:[
              {validator:validateFun.chineseRex,message:'请输入中文'},
            ]
          }
        },
        {
          title: '指标逻辑',
          dataIndex: 'indexLogic',
          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 indexSourceColumns: ProColumns<IndexSourceModel>[] = [
        {
          title: '指标数据来源编号',
          dataIndex: 'indexSourceNo',
          search: false,
          hideInTable: true,
        },
        {
          title: '指标编号',
          dataIndex: 'indexNo',
          search:false,
          hideInTable: true,
        },
        {
          title: '其他指标编号',
          dataIndex: 'otherIndexNo',
          hideInTable: false,
          valueType:'select',
          request:()=>fetchDict('@selectAllIndexToDict'),
          fieldProps: {
             treeDefaultExpandAll: true,
             treeCheckable:true,
           },
        },
        {
          title: '数据集编号',
          dataIndex: 'dataSetNo',
          search: false,
          hideInTable: false,
          valueType:'select',
          request:()=>fetchDict('@selectDataSet'),
          fieldProps: {
             treeDefaultExpandAll: true,
             treeCheckable:true,
           },
        },
        {
          title: '数据类型',
          dataIndex: 'dataSourceType',
          search: false,
          hideInTable: false,
          request:()=>fetchDict('INDEXSOURCETYPE'),
          valueType:'select',
          fieldProps: {
             treeDefaultExpandAll: true,
             treeCheckable:true,
           },
        },
        {
          title: '操作',
          valueType: 'option',
          width: 200,
          render: (text, record, _, action) => [
            <a
              key="editable"
              onClick={() => {
                action?.startEditable?.(record.indexSourceNo);
              }}
            >
              编辑
            </a>,
            <a
              key="delete"
              onClick={() => {
                setIndexSourceList(indexSourceList?.filter((item) => item.indexSourceNo !== record.indexSourceNo));
              }}
            >
              删除
            </a>,
          ],
        },
      ];

    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:IndexConfigModel) =>{
           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);
            setIndexSourceList([]);
          }}
          >
            新增
          </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="indexNo"  readonlyCond="update"
            rules={[
              { required: true, message: '请输入编号' },
              {
                validator:validateFun.account
              },
              {
                validator: (rule, value, callback)=> {
                  if (firstCharIsNotNumber(value)>0) {
                    callback('编号不能以数字开头');
                  } else {
                    callback();
                  }
    
                }
              }]}  label="指标编号"/>
            <SDFormText name="indexName" rules={[{validator:validateFun.chineseRex,message:'请输入中文'}]} label="指标名称"/>
            <SDFormText type="textarea" name="indexLogic"  label="指标逻辑"/>

            <SDAreaTtile title='数据来源'/>
            <EditableProTable<IndexSourceModel>
             rowKey="indexSourceNo"
             headerTitle="可编辑表格"
             columns={indexSourceColumns}
             value={indexSourceList}
             dataSource={indexSourceList}
             onChange={(value)=>{
              setIndexSourceList([...value]);
             }}
             recordCreatorProps={
              {
                position:'bottom',
                record: () => ({ indexSourceNo: (Math.random() * 1000000).toFixed(0),
                 })
              }
             }
            />
        </SDModalForm>
      )}
        </SDPage>

    );
}
export default indexconfig;
