import React, { useState, useEffect } from 'react';
import styles from './style/index.module.less';
import CustomCard from '@/components/CustomCard';
import Overview from './overview';
import { Space, Select, Switch, Table, TableColumnProps, Progress } from '@arco-design/web-react';
import {
  IconLoading,
  IconCheckCircle,
  IconCloseCircle,
  IconPauseCircle,
  IconMinusCircle,
  IconExclamationCircle,
  IconEye
} from '@arco-design/web-react/icon';
import { formatInstanceStatus, formatInstanceType, formatTimestamp, formatSeconds } from '@/utils/common';
import { getInstances } from '@/api/appIns';
import { getOverviewApp } from '@/api/overview';
import { getMyAppList } from '@/api/apps';

const Option = Select.Option;


const columns: TableColumnProps[] = [
  {
    title: '实例名称',
    dataIndex: 'name'
  },
  {
    title: '类型',
    dataIndex: 'type',
    render: (col, record, index) => (
      <span>
        {formatInstanceType(record.type)}
      </span>
    )
  },
  {
    title: '启动时间',
    dataIndex: 'startTime',
    render: (col, record, index) => (
      <span>
        {formatTimestamp(record.startTime)}
      </span>
    )
  },
  {
    title: '运行时长',
    dataIndex: 'duration',
    render: (col, record, index) => (
      <span>
     {record.duration > 1000 ? formatSeconds(`${record.duration / 1000}`) : `${record.duration} 毫秒`}
      </span>
    )
  },
  {
    title: '进度',
    dataIndex: 'progress',
    render: (col, record, index) => (
      <Progress percent={record.progress} size="large" />
    )
  },
  {
    title: '运行状态',
    dataIndex: 'state',
    render: (col, record, index) => (
      <span>
        {formatInstanceStatus(record.state)}
        {getIcon(record.state)}
      </span>
    )
  },
  {
    title: '操作',
    dataIndex: '',
    render: (col, record, index) => (
      <span>
        <IconEye style={{ fontSize: '26px', cursor: 'pointer' }} onClick={() => checkInstance(record)} />
      </span>
    )
  }
];

function checkInstance(instance) {
  console.log('instance:', instance);
}

function getIcon(type) {
  switch (type) {
    case 'RUNNING':
      return <IconLoading style={{ color: 'rgb(var(--arcoblue-4))', fontSize: '20px' }} />;
    case 'SUCCESS':
      return <IconCheckCircle style={{ color: 'rgb(var(--green-6))', fontSize: '20px' }} />;
    case 'FAILURE':
      return <IconCloseCircle style={{ color: 'rgb(var(--red-6))', fontSize: '20px' }} />;
    case 'PAUSED':
      return <IconPauseCircle style={{ color: 'rgb(var(--orange-6))', fontSize: '20px' }} />;
    case 'STOPPED':
      return <IconMinusCircle style={{ color: 'rgb(var(--red-4))', fontSize: '20px' }} />;
    case 'KILL':
      return <IconExclamationCircle style={{ color: 'rgb(var(--red-7))', fontSize: '20px' }} />;
    default:
      return '';
  }
}

const Instance = () => {
  const [instanceData, setInstanceData] = useState({
    list: [],
    totalCount: 0,
    totalPage: 0,
    currentPage: 1,
    pageSize: 10
  });
  const [searchOptions, setSearchOptions] = useState([]);
  const [overviewData, setOverviewData] = useState({
    avgTime: 0,
    runningNum: 0,
    successNum: 0,
    failureNum: 0
  });
  const [searchParams, setSearchParams] = useState({
    appId: '',
    state: '',
    type: '',
    durationDesc: false
  });


  const Selector = () => {
    return (
      <Select
        placeholder="输入搜索应用"
        style={{ width: 200 }}
        allowClear
        showSearch
        value={searchParams.appId || undefined}
        filterOption={(inputValue, option) => option.props.children.toLowerCase().indexOf(inputValue.toLowerCase()) >= 0}
        onChange={(value) => handleSearchParamChange('appId', value || '')}
      >
        {searchOptions.map((option: any, index) => (
          <Option key={option.id} value={option.id}>
            {option.name}
          </Option>
        ))}
      </Select>
    );
  };

  const RunStatus = () => {
    const stateList = [
      {
        label: '暂停',
        value: 'PAUSED'
      },
      {
        label: '中止',
        value: 'KILL'
      },
      {
        label: '运行中',
        value: 'RUNNING'
      },
      {
        label: '停止',
        value: 'STOPPED'
      },
      {
        label: '失败',
        value: 'FAILURE'
      },
      {
        label: '成功',
        value: 'SUCCESS'
      }
    ];
    return (
      <Select
        placeholder="无"
        style={{ width: 154 }}
        allowClear
        value={searchParams.state || undefined}
        onChange={(value) => handleSearchParamChange('state', value || '')}
      >
        {stateList.map((option, index) => (
          <Option key={option.value} value={option.value}>
            {option.label}
          </Option>
        ))}
      </Select>
    );
  };

  const Type = () => {
    const typeDict = [
      {
        label: '定时任务',
        value: 'TIMER'
      },
      {
        label: '运行应用',
        value: 'MANUAL'
      },
      {
        label: '运行子流程',
        value: 'MANUAL_SUB'
      }
    ];
    return (
      <Select
        placeholder="无"
        style={{ width: 154 }}
        allowClear
        value={searchParams.type || undefined}
        onChange={(value) => handleSearchParamChange('type', value || '')}
      >
        {typeDict.map((option, index) => (
          <Option key={option.value} value={option.value}>
            {option.label}
          </Option>
        ))}
      </Select>
    );
  };

  // 处理搜索参数变化
  const handleSearchParamChange = (field: string, value: string | boolean) => {
    const newSearchParams = {
      ...searchParams,
      [field]: value
    };
    setSearchParams(newSearchParams);

    // 重置到第一页并重新获取数据
    fetchData({
      ...newSearchParams,
      currPage: 1
    });
  };

  // 获取实例列表和概览数据
  const fetchData = async (params: any = {}) => {
    const requestParams: any = {
      appId: params.appId !== undefined ? params.appId : searchParams.appId,
      state: params.state !== undefined ? params.state : searchParams.state,
      type: params.type !== undefined ? params.type : searchParams.type,
      currPage: params.currPage || instanceData.currentPage,
      pageSize: params.pageSize || instanceData.pageSize,
      total: 0,
      durationDesc: params.durationDesc !== undefined ? params.durationDesc : searchParams.durationDesc
    };

    if (!requestParams.state) delete requestParams.state;
    if (!requestParams.type) delete requestParams.type;
    if (!requestParams.appId) delete requestParams.appId;

    const res: any = await getInstances(requestParams);
    if (res.code === 200) {
      setInstanceData({
        ...res.data,
        currentPage: params.currPage || instanceData.currentPage,
        pageSize: params.pageSize || instanceData.pageSize
      });
    }
    const overviewData: any = await getOverviewApp(requestParams.appId);
    if (overviewData.code === 200) setOverviewData(overviewData.data);
  };

  const getSearchOptions = async () => {
    const res: any = await getMyAppList({
      currPage: 1,
      pageSize: 999
    });
    if (res.code === 200) setSearchOptions(res.data.list);
  };

  useEffect(() => {
    fetchData();
    getSearchOptions();
  }, []);

  const handlePageChange = (page: number) => {
    fetchData({ currPage: page });
  };

  const handlePageSizeChange = (pageSize: number) => {
    fetchData({ pageSize, currPage: 1 });
  };

  return (
    <>
      <div className={styles['instanceContainer']}>
        <CustomCard>
          <Overview overviewData={overviewData} />
          <Space
            size={50}
            style={{ marginTop: '20px', marginBottom: '30px' }}
          >
            <div className={styles['handleRow']}>
              <span>应用：</span>
              {Selector()}
            </div>
            <div className={styles['handleRow']}>
              <span>运行状态：</span>
              {RunStatus()}
            </div>
            <div className={styles['handleRow']}>
              <span>类型：</span>
              {Type()}
            </div>
            <div className={styles['handleRow']}>
              <span>运行时长倒序：</span>
              <Switch
                checked={searchParams.durationDesc}
                onChange={(checked) => handleSearchParamChange('durationDesc', checked)}
              />
            </div>
          </Space>
          <Table
            columns={columns}
            data={instanceData.list}
            pagination={{
              total: instanceData.totalCount,
              current: instanceData.currentPage,
              pageSize: instanceData.pageSize,
              showTotal: true,
              sizeOptions: [10, 20, 30, 50],
              onChange: handlePageChange,
              onPageSizeChange: handlePageSizeChange
            }}
          />
        </CustomCard>
      </div>
    </>
  );
};

export default Instance;