import React, { useEffect, useRef, useState } from "react";
import { type ProColumns, type ActionType, type ProFormInstance, ProTable, EditableProTable } from '@ant-design/pro-components';
import type {FormInstance} from 'antd'
import  {Upload} from 'antd'
import { SDPage,SDFormText,SDModalForm,SDTable,SDFormItem,SDButton,SDSubmitButton,EditType, SDAreaTtile, SDOperate, baseFun,SDModal, validateFun, SDLayout, SDFormDict, } from "@sundata/ui-frame";
import { DataQualityRuleDefineModel, isNotExist } from '@/services/rwa/product/dataquality/dataqualityruledefine';
import {getDataList,deleteRows,createRowData,updateRowData,selectDetailData} from '@/services/rwa/product/dataquality/dataqualityruledefine';
import { PlusSquareTwoTone, WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { ReportCalculationModel } from "@/services/rwa/product/report_form_config_reportcreater/reportfillingconfig";
import { useModel } from "@umijs/max";
import { countChineseChars } from "@/services/rwa/product/rwacheckutils";
type widowRush = {
  onCancel:  () => void;
  onChangeVisible(visible: boolean, type: string): unknown;
  onChangeVisdible:(visible:boolean,type ?: 'none' | 'raload' )=>void;
}& ProductProps;
const dataqualityruledefine : React.FC<widowRush> = (prop:widowRush) => {

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


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

    /** 字段关系序号编辑 */
    var dataIndex = 1;

    useEffect(() => {
      }, []);
    
      const { fetchDict } = useModel('dict');  
    // 修改查询查询
    const selectData = async (formdata : DataQualityRuleDefineModel) => {
      const data = await selectDetailData(formdata);
      formRef.current?.setFieldValue("checkTableName",data.checkTableNames);
      const {checkTableName,...data1} =data
      formRef.current?.setFieldsValue(data1);
     }

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

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

  // 插入或者更新数据
  const handleSave = async(data: DataQualityRuleDefineModel,) => {
    
    if (editType == 'update' ) {
       await updateRowData(data);
       closeAndRefresh();
       setDetailVisible(false);
       baseFun.info("保存成功")
    } else if (editType == 'create' ) {
      const sd = await isNotExist(data.checkRuleNo);
      if(Number(sd)>1){
      await createRowData(data);
      closeAndRefresh();
      setDetailVisible(false);
      baseFun.info("保存成功")
      }else{
        baseFun.warning("规则编号已存在,请重新输入！");
      }
    }
    
  }


     
    // 页面展示元素
    const columns: ProColumns<DataQualityRuleDefineModel>[] = [
      {
        title: '序号',
        dataIndex: 'index',
        search: false,
        render: (text, record, index) => { index  = index + 1;dataIndex = index; return index},
        width:100,
        ellipsis:true
      },
        {
          title: '计算实例号',
          dataIndex: 'calcIndex',
          search: false,
          hideInTable: true,
        },
        {
          title: '起始数据日期',
          dataIndex: 'startDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '截止数据日期',
          dataIndex: 'endDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '规则编号', 
          dataIndex: 'checkRuleNo',
          hideInTable: false,
        },
        {
          title: '规则名称', 
          dataIndex: 'checkRuleName',
          hideInTable: false,
        },
        {
          title: '被检查表', 
          dataIndex: 'checkTableNames',
       //   request:()=>fetchDict({dictKey:'@checkTableName'}),
          hideInTable: false,
        },
        {
          title: '状态', 
          dataIndex: 'checkStates',
          hideInTable: true,
          valueType:'treeSelect',
          request:()=>fetchDict("YESORNO"),
          fieldProps:{
            treeCheckable:true,
          }
      },
        {
            title: '状态', 
            dataIndex: 'checkState',
            hideInTable: false,
            search:false,
            valueType:'treeSelect',
            request:()=>fetchDict("YESORNO"),
            fieldProps:{
              treeCheckable:true,
            }
        },
        {
          title: '操作',
          dataIndex: 'operate',
          valueType: 'option',
          render: (_, record) => [
            <SDOperate
              key="roleCfg"
              icon={<WomanOutlined />}
              successMessage=""
              onClick={
                ()=>{ 
                selectData(record);
                setCurrentRow(record);
                setDetailVisible(true);
                setEditType('update');
               } }
            >
              修改
            </SDOperate>,
            <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""
            onClick={()=>{delRows(record) } }
          >
            废止
          </SDOperate>,
          <SDOperate
            key="roleCfg"
            icon={<WomanOutlined />}
            successMessage=""
            onClick={()=>{
                selectData(record);
                setDetailVisible(true);
                setEditType('display');
             } }
           >
            查看
          </SDOperate>,
           
          ],
        },
      ];

   
    
    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:DataQualityRuleDefineModel) =>{
           const formDatas = await getDataList(formdata);
           // 解构数组（导出用）
           formDataList=[...formDatas];
           return {data: formDatas}
         }  }
         columns={columns}
         toolBarRender={(_, { selectedRows }) => [
          <SDButton
            key="export"
            icon={<PlusSquareTwoTone/>}
            successMessage=''
            onClick={() => {
                setEditType('create');
                setDetailVisible(true);
            }}
          >
            新增
          </SDButton>,
        ]}
         actionRef={actionRef}
         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}  successMessage='' formRef={formRef} doSubmit={handleSave} >保存</SDSubmitButton>,
          <SDButton
            key="closeUpdate"
            successMessage=''
            onClick={() => {
               setDetailVisible(false);
            }}>关闭</SDButton>
          ]}
          tableRef={actionRef}
          formRef={formRef}
        >
            <SDAreaTtile title='规则信息'/>
            <SDFormText name="checkRuleNo" readonlyCond="update" required={true} label="规则编号" rules={[{max:60,message:'最多50个字符'}]}/>
            <SDFormText name="checkRuleName" label="规则名称" rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 30) {
                callback('最多30个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]}/>
            <SDFormDict name="checkRate"  label="检查频率" dictKey="CHECK_RATE" />
            <SDFormText name="adjustDate" label="天数调整"/>
            <SDFormDict name="checkRuleType" label="校验类型" dictKey="CHECK_RULE_TYPE"/>
            <SDFormDict name="checkTableName" label="被检查表"  dictKey="@checkTableName" multiple={true}/>
            <SDFormDict name="ruleStageId" label="所属阶段" dictKey="@ruleStageId"/>
            <SDFormText type="textarea" name="checkProposal" label="处理方案建议"  rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 200) {
                callback('最多200个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]}/>
            <SDFormText type="textarea" name="checkRuleDesc"  label="检查规则说明"  rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 200) {
                callback('最多200个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]}/>
            <SDFormText type="textarea" name="checkRule"  label="检查规则sql"/>
        
            
        </SDModalForm>
        
      )}
        </SDPage>
        
    );
}
export default dataqualityruledefine;