import { Upload } from 'antd';
import { useRef, useState } from 'react';
import { baseFun, SDButton, SDForm, SDFormText, SDLayout, SDModal, SDOperate } from '@sundata/ui-frame';
import { getDetail, ImpmTypeConfigModel, uploadAction } from '../services/pubMng/excelMng';
import type { ActionType, ProFormInstance } from '@ant-design/pro-components';
import { UploadOutlined } from '@ant-design/icons';

export type SDImpDialogProps = {
  /**组件标识,组件内唯一 */
  key: string;
  /** 导入类型，格式：模板代码&导入序号&导入期次；导入序号和导入期次可为空 */
  type: string;
  /**上传按钮调用的方法 */
  onclick?: () => any;
  /** */
  //disTemplate?: boolean;
  /**窗口大小 */
  impDialogSize?: 'l' | 'm' | 's' | 'large' | 'medium' | 'small';
  /** */
  visible: boolean;
  //onVisibleChange: React.Dispatch<React.SetStateAction<boolean>>; /** 弹出窗口显示状态发生改变后的处理方法 */
  /** 关联表格的引用对象，应与对应ProTable的actionRef一致，用于刷新表格 */
  tableRef?: React.MutableRefObject<ActionType | undefined>;
  /**回调函数,上传后返回数据 */
  callback?: (data: any) => any;
  /**用于关闭弹窗 例：onCancel={()=>setVisible(false)} */
  onCancel?: () => any;
  /**展示期次，true-展示 false/undefined-不展示 */
  showTerm?: boolean;
  /** moment规则的日期格式，可使用中文 */
  dateFmt?: string;
};

const SDImpDialog: React.FC<SDImpDialogProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  console.log(props.type);
  const [disModal, setDisModal] = useState<boolean>(props.visible);
  const mType: string[] = props.type.split('@');
  /**上传文件 */
  const [fileState, setFileState] = useState<File>();
  /**上传属性 */
  const fileProps = {
    onRemove: () => {
      setFileState(undefined);
    },
    beforeUpload(info: any) {
      setFileState(info);
    },
    customRequest: (options: { onSuccess: () => void; }) => {
      options?.onSuccess?.();
    },
  };
  /**上传提交 */
  const uploadSubmit = async () => {
    let type = props.type;
    if(props.showTerm){
      let term = formRef.current?.getFieldValue("term");
      if(!term){
        baseFun.warning('未选择期次');
        return;
      }
      if(typeof term === 'string'){//传参转换
        const date = new Date(term);
        const year = date.getFullYear();
        const month = (date.getMonth() < 10 ? '0' + (date.getMonth() + 1) : date.getMonth());
        term =`${year}${month}`;
      }else{//日期控件切换转换
        term = term.format("YYYYMM");
      }
      if(mType.length>1){
        type = `${mType[0]}@${mType[1]}@${term}`
      }
    }
    
    if (!fileState) {
      baseFun.warning('未上传文件');
      return;
    }
    const res = await uploadAction(fileState, type);
    // if (res.success) {
    //   baseFun.info('导入成功');
    // } else {
    //   baseFun.error(res.message || '导入失败');
    // }
    baseFun.info(res._msg)
    if (props.callback) props.callback(res);
  };

  const download = () => {
    baseFun.download('/api/admin/excelmanage/importAndAuditp/importExcelModel.do', {
      mType: mType[0],
    });
  };

  const getDetailReq = async () => {
    const data: ImpmTypeConfigModel = await getDetail({ mtype: mType[0] });
    if(mType.length==3 && mType[2]){
      return {mtypename: data.mtypename,term: mType[2]}
    }else{
      return {mtypename: data.mtypename,term: null}
    }
  };

  return (
    <SDModal
      title=""
      visible={disModal}
      footer={[ <SDButton successMessage='' autoLoading primary onClick={uploadSubmit}>保存</SDButton>,
       <SDButton onClick={download}>下载模板文件</SDButton>,
      ]}
      size={props.impDialogSize ? props.impDialogSize : 's'}
      onCancel={() => {
        setDisModal(false);
        //props.onVisibleChange(false);
        props.tableRef?.current?.reload();
        props.tableRef?.current?.clearSelected?.();
        if(props.onCancel)props.onCancel();
      }}
    >
      <SDLayout >
        <SDForm
          editType={'create'}
          request={getDetailReq}
          formRef={formRef}
        >
          {props.showTerm && 
            <SDFormText name="term" required type='prodmonth'label="期次" dateFmt={props.dateFmt?props.dateFmt:'YYYYMM'}/>
          }
          <SDFormText name="mtypename" readonlyCond="both" label="模板名称" />
          
          <Upload maxCount={1} {...fileProps} name="file">
          <div style={{paddingLeft:'3.4vw'}}>
                上传文件: &nbsp;&nbsp;<SDOperate icon={<UploadOutlined />}>上传</SDOperate>
            </div>
          </Upload>
          
        </SDForm>
      </SDLayout>
    </SDModal>
  );
};
export default SDImpDialog;
