import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, FormInstance, Input, Space, Table, Tooltip, Upload } from 'antd';
import { EditType, SDForm, SDFormDict, SDFormText, SDModal, SDModalForm, SDOperate, SDPage, SDSubmitButton, SDTable, baseFun, SDButton, validateFun, SDFormItem } from '@sundata/ui-frame';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import { WomanOutlined } from '@ant-design/icons';
import { result } from 'lodash';
import { deleteGovFinancialAssetComp, exportExcelModel, getGovFinancialAssetComp, GovFinancialAssetCompModel, inserteGovFinancialAssetComp, selectGovFinancialAssetComp, templateUpload, uploadAction } from '@/services/rwa/govFinancialAssetComp';
import { countChineseChars } from '@/services/rwa/product/rwacheckutils';

type bbb ={

}//中央政府投资的金融资产管理公司清单表

const govFinancialAssetCompts: React.FC<bbb>= (prop : bbb) => {

    const [editType, setEditType] = useState<EditType>('update');
    const formRef = useRef<FormInstance<any>>();
      /** 当前行对象，查看详情、修改时，作为详细信息表单的查询条件 */
    const [currentRow,setCurrentRow] = useState<GovFinancialAssetCompModel>();
    const [dataSource, setDataSource] = useState<any>() ;
    const [detailVisible, setDetailVisible] = useState<boolean>(false);

    const [visible,setVisible] = useState<boolean>(false);//弹窗是否显示
    const [deadline,setdeadline] = useState<boolean>(false);//弹窗是否显示
    const [secName,setSecName] = useState<boolean>(false);//弹窗是否显示
    const [importVisible, setImportVisible] = useState<boolean>(false);
    const tableActionRef = useRef<ActionType>();
    const actionRef = useRef<ActionType>();
          /**上传文件 */
  const [fileData, setFileData] = useState<File>();

    const closeAndRefresh = ()=>{
        setVisible(false);
        actionRef.current?.reloadAndRest?.();
      }
      var formDataList = new Array<GovFinancialAssetCompModel>;

      const selectdata = async (record:any)=>{
        const sd =await selectGovFinancialAssetComp(record.name);
        
        // if (sd.deadline ==='' || sd.deadline ===null){
        //   setSecName(true);
        //   setdeadline(false);
        //   console.log('1');
        // }else {
        //   console.log('3');
        //   setdeadline(true);
        //   setSecName(false)
        // }
        console.log(sd);
        formRef.current?.setFieldsValue(sd);
     }  
     const inst =  async(formData : GovFinancialAssetCompModel) => {
        setEditType('create')
        console.log(formData);
        formRef.current?.getFieldValue(formData);
       const insSovere =await inserteGovFinancialAssetComp(formData)  
       closeAndRefresh();
       console.log(insSovere);
       if(insSovere){
        baseFun.info ("保存成功");
       }else{
        baseFun.error(insSovere);
       }
         ;
      }
      
       const del = async(record:any)=>{
        baseFun.confirm("请确认是否继续操作。",async()=>{
          await deleteGovFinancialAssetComp(record.name)  
          closeAndRefresh();
          baseFun.info("删除成功");
        })
        }
        const disdata = async (record:any)=>{
            const sd =await selectGovFinancialAssetComp(record.name);
            (record.qualfiedCreditToolType,record.secClassificationCd);
          formRef.current?.setFieldsValue(sd);
         // return {data :sd};   
       }
       const columns: ProColumns<GovFinancialAssetCompModel>[] = [
        {
            title : '计算实例号',
           dataIndex : 'calcindex',
           width:150,
           search: false,
           hideInTable: true,
            },
           
           {
            title : '缓释分类',
           dataIndex : 'crmClass',
           search: false,
           hideInTable: true,
           width:150
            },
           
           {
            title : '数据日期',
           dataIndex : 'dataDate',
           width:150,
           search: false,
           hideInTable: true,
            },
           
           {
            title : '截止数据日期',
           dataIndex : 'edate',
           width:150,
           search: false,
           hideInTable: true,
            },
           
           {
            title : '交易对手名称',
           dataIndex : 'name',
           width:150
            },
           
           
           {
            title : '缓释工具类型',
           dataIndex : 'qualfiedCreditToolTypeName',
           search: false,
           hideInTable:true,
           width:150
            },
            {
              title : '缓释工具类型',
             dataIndex : 'qualfiedCreditToolName',
             search: false,
             width:150
              }, 
           
           {
            title : '起始数据日期',
           dataIndex : 'sdate',
           width:150,
           search: false,
           hideInTable: true,
            },
           
           {
            title : '年月',
           dataIndex : 'term',
           width:150,
           search: false,
           hideInTable: true,
            },
           
           {
            title : '缓释权重',
           dataIndex : 'weight',
           search: false,
           hideInTable: true,
           width:150
            },    
            
           {
            title : '备注',
           dataIndex : 'notes',
           search: false,
           hideInTable: true,
           width:150
            },
            {
                title: '操作',
                dataIndex: 'operate',
                valueType: 'option',
                render: (_, record) => [
                  <SDOperate
                    key="roleCfg"
                    icon={<WomanOutlined />}
                    successMessage=""
                    
                    onClick={()=>{ 
                      selectdata(record);
                      
                    setVisible(true);
                    setEditType('update')
                     } }
                  >
                    修改
                  </SDOperate>,
                  <SDOperate
                  key="roleCfg"
                  icon={<WomanOutlined />}
                  successMessage=""
                  
                  onClick={()=>{ 
                    del(record);
                    
                   } }
                >
                  删除
                </SDOperate>,
                ],
              },       
       ]
                 /**上传提交 */
  const uploadSubmit = async () => {
    if (!fileData) {
      baseFun.warning('未上传文件');
      return;
    }
    const res = await uploadAction(fileData);
    if ('导入成功'===res) {
      baseFun.info("处理完成");
    } else {
      baseFun.error(res);
    }
    setEditType('update');
    setDetailVisible(false);
};


   // 模板下载
   const templateUploadAction = async() => {
    await templateUpload("govFinancialAssetComp");
   // baseFun.info("处理完成");
  }
    /**上传属性 */
    const fileProps = {
      onRemove: () => {
      setFileData(undefined);
     },
      beforeUpload(info: any) {
      setFileData(info);
    },
  };
return(
<SDPage>
    <SDTable
    title="查询表格"
    rowKey="secClassificationCd"
    request={async(formData : GovFinancialAssetCompModel)=>{
        const sd = await getGovFinancialAssetComp(formData);
        formDataList =[...sd];
        return {data :sd };
      }}
      columns={columns}
      actionRef={actionRef}
      formRef={formRef}
   //   operations={["create"]}
      //handleRemove={deletedata}
       setCurrentRow={setCurrentRow}
       setEditType={setEditType}
       setDetailVisible={setVisible}  
       toolBarRender={(_, { selectedRows }) => [
        <SDButton
          key="export"
          successMessage=''
          onClick={async () => {
            exportExcelModel("govFinancialAssetComp",formDataList);
            baseFun.info('处理完成');
          }}
        >
          全部导出
        </SDButton>,
      <SDButton
      key="import"
      successMessage=''
      onClick={() => {
        baseFun.confirm("请注意本功能意在覆盖本表所有数据，请谨慎使用！",()=>{ setImportVisible(true);})
      }}
    >
      覆盖导入
    </SDButton>,
     ]}    
    ></SDTable>


{importVisible && (
         <SDModalForm
        title={'上传文件窗口'}
        visible={importVisible}
        editType={editType}
        onVisibleChange={() => {setImportVisible(false)}}
        tableRef={actionRef}
        footer={[
        <SDSubmitButton  editType={'update'}  formRef={formRef}  successMessage=""
          doSubmit={async() => {await uploadSubmit()}} >提交</SDSubmitButton>,
          <SDButton
          key="template"
          onClick={() => {
            templateUploadAction();
          }}
        >
          模板下载
        </SDButton>
        ]
        }
        >
         <SDFormItem nestType="form">
            <Upload maxCount={1} {...fileProps} name="rfile">
              <div style={{ paddingLeft: '5.5vw' }}>
                选择上传文件: &nbsp;&nbsp;<SDOperate>上传</SDOperate>
              </div>
            </Upload>
        </SDFormItem>
        </SDModalForm>
      )}
{ visible &&( 
<SDModalForm  
   visible={visible}
   //rowKey="cust_NAME" 
   editType={editType} 
   //request={selectdata}
   //params={setDataSource}
   onVisibleChange={() => { setVisible(false) }}
   initialValues={{crmClass :'保证'}}
   footer={[<SDSubmitButton  editType={editType} successMessage=""   formRef={formRef} doSubmit={inst} >保存</SDSubmitButton>,
  <SDButton successMessage="" onClick={()=>closeAndRefresh()}>关闭</SDButton>]}
   formRef={formRef}
 >

<SDFormText name="crmClass"   label="缓释分类"  />
<SDFormText name="name"   label="交易对手名称"  />
<SDFormDict name="qualfiedCreditToolTypeName"   label="合格信用风险缓释工具类型"  dictKey='qualfiedCreditToolTypeName' />
<SDFormText name="weight"   label="缓释权重"   rules={ [{validator: validateFun.double,message:"请输入数字类型" }
      ,{pattern :RegExp(`^\\d+\\.{${0},${1}}\\d{${0},${4}}$`),message:"小数位超位" }]}  
      oldValue="%"  />
<SDFormText name="notes"   label="备注" rules={[{validator:(rules,value,callback)=>{
            let chineseCount = countChineseChars(value);
            if (chineseCount > 500) {
                callback('最多500个汉字');
            } else if (chineseCount<=0) {
                callback('请输入汉字');
            } else{
              callback();
            }
         }}]} />
<div style={{display:"none"}}> 
<SDFormText name="calcindex"   label="计算实例号"  />
<SDFormText name="dataDate"   label="数据日期"  />
<SDFormText name="edate"   label="截止数据日期"  />
<SDFormText name="sdate"   label="起始数据日期"  />
<SDFormText name="term"   label="年月"  />
</div>
</SDModalForm>
)
}   

</SDPage>

)

};export default govFinancialAssetCompts


