import React, { useEffect, useRef, useState } from "react";
import type { ProColumns, ActionType } 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, SDFormDict, } from "@sundata/ui-frame";
import {getDataList,deleteRows,selectDetailData,fetchDetailData,
  updateExistData,exportExcelModel,uploadAction,templateUpload,seleDictCodeName} from '@/services/rwa/rwa_calc_config_acquisition/rule';
import { WomanOutlined } from "@ant-design/icons";
import { ProductProps } from "@/sundataImport";
import { useModel } from '@umijs/max';
import { max } from "lodash";
import { SysListModel } from "@/services/rwa/rwa_calc_config_acquisition/rule";

type widowRush = {
  subjectCodes:string;
  onOrOff:string;
  resultType:string;
  ruleNo:string;
  onCancel:  () => void;
  onChangeVisible(visible: boolean, type: string): unknown;
  onChangeVisdible:(visible:boolean,type ?: 'none' | 'raload' )=>void;
}& ProductProps;
// 总账取数
const rule : React.FC<widowRush> = (prop:widowRush) => {

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

    // 页面数据
    var formDataList = new Array<SysListModel>;
    /**上传文件 */
    const [fileData, setFileData] = useState<File>();
    // 导入窗口显示
    const [importVisible, setImportVisible] = useState<boolean>(false);
 
    useEffect(() => {

      }, []);
    
    // 修改查询查询
    const selectData = async (formdata : SysListModel) => {
      const data = await selectDetailData(formdata);
      formRef.current?.setFieldsValue(data);
     }

    // 作废
    const delRows =async(record:any)=>{ 
       baseFun.confirm('请确认是否继续操作',async() =>{
        if (record.state == '失效') {
          baseFun.info("此数据已为失效状态");
          return;
        } else {
          await deleteRows(record.ruleNo);
          baseFun.info("作废成功");
        }
        closeAndRefresh();
       });
       
     }

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

  // 插入或者更新数据
  const handleSave = async(data: SysListModel,) => {
    
    if (editType == 'update' ) {
      if (currentRow?.ruleNo) {
        await updateExistData(data,currentRow?.ruleNo);
        closeAndRefresh();
      } else {
        baseFun.error("当前行为空");
        return;
      }
    } else if (editType == 'create' ) {
      await fetchDetailData(data);
      closeAndRefresh();
    }
    setDetailVisible(false);
  }

  // 模板下载
  const templateUploadAction = async() => {
    // 模板下载(模板code:ListOfPublicSector)
    await templateUpload("ListOfPublicSector");
  }

  /**上传属性 */
  const fileProps = {
      onRemove: () => {
      setFileData(undefined);
     },
      beforeUpload(info: any) {
      setFileData(info);
    },
  };

  /**上传提交 */
  const uploadSubmit = async () => {
      if (!fileData) {
        baseFun.warning('未上传文件');
        return;
      }
      const res = await uploadAction(fileData);
      if ('' === res) {
        // baseFun.info("处理完成");
        closeAndRefresh()
      } else {
        baseFun.error(res);
      }
      setEditType('update');
      setDetailVisible(false);
  };
     
    // 页面展示元素
    const columns: ProColumns<SysListModel>[] = [
        {
          title: '计算实例号',
          dataIndex: 'calcindex',
          search: false,
          hideInTable: true,
        },
        {
          title: '起始数据日期',
          dataIndex: 'startDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '截止数据日期',
          dataIndex: 'endDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '年月',
          dataIndex: 'term',
          search: false,
          hideInTable: true,
        },
        {
          title: '数据日期',
          dataIndex: 'dataDate',
          search: false,
          hideInTable: true,
        },
        {
          title: '规则编号', 
          dataIndex: 'ruleNo',
          hideInTable: false,
        },
        {
          title: '规则名称',
          dataIndex: 'ruleName',
          hideInTable: false,
        },
        {
          title: '科目代码',
          dataIndex: 'subjectCodes',
          hideInTable: false,
        },
        {
          title: '科目名称', 
          dataIndex: 'subjectNames',
          hideInTable: false,
        },
        {
          title: '表内风险暴露分类', 
          dataIndex: 'ledgerRiskexposureNo',
          hideInTable: false,
          valueType: 'treeSelect',
          request: () => fetchDict('@positiveRiskType'),
          fieldProps: {
           treeDefaultExpandAll: true,
        //   treeCheckable:true,
          },
        },
        {
          title: '表外项目分类', 
          dataIndex: 'ledgerOffObjectNo',
          hideInTable: false,
          valueType: 'treeSelect',
          request: () => fetchDict('@positiveOffProjectType'),
          fieldProps: {
           treeDefaultExpandAll: true,
       //    treeCheckable:true,
          },
        },
        {
          title: '状态', 
          dataIndex: 'state',
          search: false,
          hideInTable: false,
        },
        {
          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={()=>{
              selectData(record);
              setEditType('display')
              setDetailVisible(true)} }
          >
            查看
          </SDOperate>,
          <SDOperate
          key="roleCfg"
          icon={<WomanOutlined />}
          successMessage=""
          onClick={()=>{delRows(record) } }
        >
          作废
        </SDOperate>,
          ],
        },

      ];
    
    return (
        <SDPage>
        <SDTable
         title="查询表格"
         rowKey="customerName"
         request={async (formdata:SysListModel) =>{
           const formDatas = await getDataList(formdata);
           // 解构数组（导出用）
           formDataList=[...formDatas];
           return {data: formDatas}
         }  }
         columns={columns}
         operations={["create"]}
         toolBarRender={(_, { selectedRows }) => [
          <SDButton
            key="export"
            successMessage=''
            onClick={() => {
               baseFun.confirm('确认导出数据？',async() => {  exportExcelModel(formDataList,"rule")});
            }}
          >
            全部导出
          </SDButton>,
        ]}
         actionRef={actionRef}
         formRef={formRef}
         setDetailVisible={() => {setDetailVisible(true)}}
         setEditType={setEditType}
         setCurrentRow={()=>{setCurrentRow}}
         />

        {detailVisible && (
        <SDModalForm          
          title={'详细信息'}
          editType={editType}
          params={currentRow}
          visible={detailVisible}
          initialValues={
            {
              getdataMode:'取实际余额',
              subjectCodes:prop.subjectCodes,
              resultType:prop.resultType,
              onOrOff:prop.onOrOff
            }
          }
          onVisibleChange={() => {setDetailVisible(false)}}
          onValuesChange={async (changevalues) => {
            if (changevalues.subjectCodes != undefined) {
              const value = await seleDictCodeName(changevalues.subjectCodes);
              formRef.current?.setFieldValue('subjectNames',value);
            }
            if (changevalues.resultType != undefined) {
              if (changevalues.resultType == '1') {
                formRef.current?.setFieldValue('onOrOff','表内');
              } else if (changevalues.resultType == '2') {
                formRef.current?.setFieldValue('onOrOff','表外');
              } else {
                formRef.current?.setFieldValue('onOrOff','');
              }
            }
          }}
          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="ruleNo" rules={[{max:20, message:'名称长度不能超过20位'}]} label="规则编号"/>
            <SDFormText name="ruleName" label="规则名称" rules={[{max:30, message:'名称长度不能超过30位'}]} />
            <SDFormDict name="subjectCodes" dictKey="SUBJECTCODE"  label="科目代码" />
            <SDFormText name="subjectNames"  label="科目名称" />
            <SDFormDict name="accountingDirection" dictKey="ACCOUNTING_DIRECTION"  label="记账方向"/> 
            <SDFormDict name="calcMode" dictKey="CALC_METHOD" label="计算方式"/>
            <SDFormDict name="getdataMode"  label="取值方式" dictKey="GETDATA_MODE" />
            <SDFormDict name="resultType" dictKey="RESULT_TYPE"  label="计算项" />
            <SDFormText name="onOrOff"  label="表内外标识" />
            <SDFormDict name="ledgerRiskexposureNo"  label="表内风险暴露分类" dictKey="@positiveRiskType" />
            <SDFormDict name="ledgerOffObjectNo"  label="表外项目分类"  dictKey="@positiveOffProjectType"/>
            <SDFormDict name="ledgerStageId"  label="所属阶段" dictKey="@stageinId" />
            <SDFormText name="ledgerGetdataRule" 
            type="textarea" label="总账取数规则"/>
         
        </SDModalForm>
        
      )}
        </SDPage>
        
    );
}
export default rule;