import React, {FC, useRef, useState} from 'react';
import {
  baseFun,
  SDAreaTtile,
  SDButton,
  SDEditableTable,
  SDFormDict,
  SDFormText,
  SDModalForm,
  SDOperate,
  SDPage,
  SDTable,
  validateFun
} from "@sundata/ui-frame";
import {ProColumns} from "@ant-design/pro-table";
import {
  deleteRows,
  getDataList,
  insertInterfaceService,
  InterfaceModel,
  selectDetailData, testCalc,
  updateInterfaceService
} from "@/services/internalEvaluation/configuration/Interface";

import {useModel} from '@umijs/max';
import {WomanOutlined} from "@ant-design/icons";
import {EditType} from "@sundata/ui-frame/lib/types";
import {FormInstance} from "antd/lib/form";
import {InterfaceParamModel} from "@/services/internalEvaluation/configuration/InterfaceParam";
import {ActionType, EditableProTable} from "@ant-design/pro-components";
import {Popconfirm} from "antd";


const InterfacePage: FC = () => {
  const {fetchDict} = useModel('dict');
  const interfaceDetailsRef = useRef<FormInstance<any>>();
  /** 表格引用对象，刷新表格使用 */
  const tableRef = useRef<ActionType>();

  // 新增、修改、查看详细信息弹窗的显隐控制
  const [detailVisible, setDetailVisible] = React.useState(false);
  // 编辑类型
  const [editType, setEditType] = React.useState<EditType>('create');

  // 存储请求参数列表
  const [paramList, setParamList] = useState<InterfaceParamModel[]>([]);

  const [operateInterfaceId, setOperateInterfaceId] = useState<string>('');

  // 页面展示元素
  const columns: ProColumns<InterfaceModel>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      search: false,
      hideInTable: true,
    },
    {
      title: '接口编号',
      dataIndex: 'interfaceNo',
      hideInTable: false,
    },
    {
      title: '接口名称',
      dataIndex: 'interfaceName',
      hideInTable: false,
    },
    {
      title: '接口类型',
      dataIndex: 'interfaceTypeCode',
      hideInTable: false,
      valueType: 'select',
      request: () => fetchDict('INTERFACE_TYPE'),
      fieldProps: {
        treeDefaultExpandAll: true,
        treeCheckable: true,
      },
    },
    {
      title: 'IP',
      dataIndex: 'interfaceIp',
      search: false,
      hideInTable: false,
    },
    {
      title: '端口',
      dataIndex: 'interfacePort',
      hideInTable: false,
    },
    {
      title: '地址',
      dataIndex: 'interfaceUrl',
      hideInTable: false,
    },
    {
      title: '最后修改时间',
      dataIndex: 'updateTime',
      search: false,
      hideInTable: false,
    },
    {
      title: '操作',
      dataIndex: 'operate',
      valueType: 'option',
      render: (_, record) => [
        <SDOperate
          key="roleCfg"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              selectDetailDataById(record);
              setDetailVisible(true)
              setEditType("display")
              // console.log("查看", record)
              // console.log(fetchDict('INTERFACE_TYPE'))
            }
          }
        >
          查看
        </SDOperate>,
        <SDOperate
          key="roleCfg"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={
            () => {
              console.log("修改方法", record)
              selectDetailDataById(record)
              setDetailVisible(true);
              setEditType('update')
            }}
        >
          修改
        </SDOperate>,
        <Popconfirm
          title={'警告'}
          description={'此操作是不可逆的，确认要删除数据吗？'}
          onConfirm={async () => {
            await deleteRows(record);
            tableRef.current?.reload();
          }}
        >
          <SDOperate
            key="roleCfg"
            icon={<WomanOutlined/>}
            successMessage=""
            onClick={() => {
              console.log("删除方法", record)
            }}
          >
            删除
          </SDOperate>
        </Popconfirm>,
        <SDOperate
          key="roleCfg"
          icon={<WomanOutlined/>}
          successMessage=""
          onClick={() => {
            console.log("测试...", record)
            testCalc1(record);
          }}
        >
          测试接口
        </SDOperate>

      ],
    },

  ];

  /**
   * 接口请求参数列表
   */
  const paramColumns: ProColumns<InterfaceParamModel>[] = [
    {
      title: '参数对象名称',
      dataIndex: 'paramObjName',
      hideInTable: false,
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入参数对象名称'
          }
        ]
      }
    },
    {
      title: '参数中文名称',
      dataIndex: 'paramChineseName',
      hideInTable: false,
      search: false,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入参数中文名称'
          }
        ]
      }
    },
    {
      title: '参数说明',
      dataIndex: 'paramDescription',
      hideInTable: false,
      search: false,
    },
    {
      title: '参数类型',
      dataIndex: 'paramTypeCode',
      hideInTable: false,
      search: false,
      valueType: 'select',
      request: () => fetchDict('INTERFACE_PARAM_TYPE'),
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择参数类型'
          }
          // {
          //   validator:(rules,value,callback) => {
          //     if (!value) {
          //       callback('请选择参数类型');
          //     } else {
          //       callback()
          //     }
          //   }
          // }
        ]
      }
    },
    {
      title: '是否为报文头',
      dataIndex: 'isHeader',
      hideInTable: false,
      search: false,
      valueType: 'radio',
      valueEnum: {
        true: {text: '是'},
        false: {text: '否'},
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择'
          }
        ]
      }
    },
    {
      title: '参数获取类型',
      dataIndex: 'paramRetrievalTypeCode',
      hideInTable: false,
      search: false,
      valueType: 'select',
      request: () => fetchDict('PARAM_GET_TYPE'),
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请选择参数获取类型'
          }
        ]
      }
    },
    {
      title: '参数获取内容',
      dataIndex: 'paramRetrievalTypeCont',
      search: false,
      hideInTable: false,
      valueType: 'textarea'
    },
  ];

  /**
   * 保存 或 修改的方法
   * @param record InterfaceModel 实体
   */
  const saveOrUpdateInfo = async (record: InterfaceModel) => {
    record.paramList = paramList;
    record.id = operateInterfaceId;
    const isSuccess = editType === 'create' ? await insertInterfaceService(record) : await updateInterfaceService(record) as boolean;
    if (isSuccess) {
      handleCloseModelForm();
      baseFun.info('保存成功');
    }
  }

  /**
   * 根据id查询接口详情信息
   * @param record InterfaceModel实体
   */
  const selectDetailDataById = async (record: InterfaceModel) => {
    const formDatas = await selectDetailData(record);
    interfaceDetailsRef.current?.setFieldsValue(formDatas);
    setParamList(formDatas.paramList);
    setOperateInterfaceId(formDatas.id)
  }

  const testCalc1 = async (record: InterfaceModel)=>{

    console.log (await testCalc(record).then((res)=>{
      console.log(res)
    }))
  }


  /**
   * 关闭弹窗操作
   */
  const handleCloseModelForm = () => {
    setDetailVisible(false);
    // interfaceDetailsRef.current?.resetFields();
    setParamList([]);
    setOperateInterfaceId('');
  }


  return (
    <SDPage>
      <SDTable
        title={'接口配置'}
        rowKey={"id"}
        actionRef={tableRef}
        request={
          async (formdata: InterfaceModel) => {
            const formDatas = await getDataList(formdata);
            return {data: formDatas}
          }
        }
        toolBarRender={
          () => [
            <SDButton
              key="roleCfg"
              successMessage=""
              onClick={() => {
                setDetailVisible(true);
                setEditType('create');
                setParamList([]);
              }}
            >
              新增
            </SDButton>,
          ]
        }
        columns={columns}

      />

      {detailVisible && (
        <SDModalForm
          successMessage={''}
          tableRef={tableRef}
          formRef={interfaceDetailsRef}
          title={(editType === 'create' ? '新增' : editType === 'update' ? '修改' : '查看') + "接口信息"}
          editType={editType}
          visible={detailVisible}
          doSubmit={re => saveOrUpdateInfo(re)}
          onVisibleChange={handleCloseModelForm}
        >
          <SDAreaTtile title={"基本信息"}/>
          {/*<SDFormText name="id" label="id" disabled={true} width={'md'}/>*/}
          <SDFormText name="interfaceNo" readonlyCond="update" label="接口编号" width={'md'} required={true}/>
          <SDFormText name="interfaceName" label="接口名称" width={'md'} required={true}/>
          <SDFormDict name="reqMethod" label="请求方式" dictKey={'INTERFACE_REQUEST_TYPE'} required={true}
                      width={'md'}/>
          <SDFormDict name="interfaceTypeCode" label="接口类型" dictKey={'INTERFACE_TYPE'} required={true}
                      width={'md'}/>
          {/*<SDFormText name="interfaceIp" label="IP" required={true}*/}
          {/*            rules={[{validator: validateFun.IP, message: '请输入正确的IP地址'}]} width={'md'}/>*/}
          <SDFormText name="interfaceIp" label="IP" required={true} width={'md'}/>
          <SDFormText name="interfacePort" label="端口" width={'md'} required={true}
                      rules={
                        [
                          {
                            validator: (a, value, callback) => {
                              if (value > 65535 || value < 1) {
                                callback('请输入正确的端口号（1-65535）');
                              } else {
                                callback();
                              }
                            }
                          }
                        ]
                      }
          />
          <SDFormText name="interfaceUrl" label="地址" width={'md'} required={true}/>
          <SDFormDict name="reqContentTypeCode" label="内容类型" dictKey={'INTERFACE_CONTENT_TYPE'} width={'md'}/>
          <SDFormDict name="respParamTypeCode" label="接收参数类型" dictKey={'RECEIVE_PARAM_TYPE'} width={'md'}/>
          <SDFormText name="reqBodyTemplate" label="报文体模板" type={'textarea'} width={'xl'}/>
          <SDFormText name="reqEncryptionLogic" label="加密逻辑" width={'xl'} type={'textarea'}/>
          <SDFormText name="decryptionLogic" label="解密逻辑" width={'xl'} type={'textarea'}/>
          <SDFormText name="processLogic" label="解密后处理逻辑" width={'xl'} type={'textarea'}/>
          <SDFormText name="classNameMapping" label="处理后对象映射" width={'md'}/>
          <SDFormText name="objNameMapping" label="映射后对象映射" width={'md'}/>
          {editType === 'display' && (
            <>
              <SDFormText name="createBy" label="创建人"/>
              <SDFormText name="createTime" label="创建时间"/>
              <SDFormText name="updateBy" label="最后修改人"/>
              <SDFormText name="updateTime" label="最后修改时间"/>
            </>
          )
          }
          <SDAreaTtile title={"请求参数"}/>

          <SDEditableTable<InterfaceParamModel>
            columns={paramColumns}
            value={paramList}
            onChange={
              (value) => {
                setParamList([...value]);
              }
            }
            editable={editType !== 'display'}
          />

        </SDModalForm>
      )}
    </SDPage>
  );
};


export default InterfacePage;
