import React, { Fragment, useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import {
  getJobIndexList,
  getJobIndexSingle,
  saveJobIndex,
  updateJobIndex,
  deleteJobIndex,
} from '@/services/recruitmentDataCollection/metricAdmin';
import { Button, FormInstance, message, Modal } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { DeleteOutlined, FormOutlined, PlusOutlined, EyeOutlined } from '@ant-design/icons';
import EditJobIndexRow from './edit';

function JobIndexList() {
  const access = useAccess();

  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<API.JobIndex.JobIndexItem>();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [mode, setMode] = useState<'view' | 'edit' | 'create'>('create');
  const [loading, setLoading] = useState<boolean>(false);

  // 删除处理
  const handleRemoveOne = async (indexId: any) => {
    const hide = message.loading('正在删除');
    if (!indexId) return true;
    try {
      const resp = await deleteJobIndex({ indexId });
      hide();
      if (resp.code === 200) {
        message.success('删除成功，即将刷新');
      } else {
        message.error(resp.msg);
      }
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  // 查看详情
  const handleViewDetail = async (indexId: any) => {
    setLoading(true);
    try {
      const res = await getJobIndexSingle(indexId);
      if (res.code === 200) {
        setCurrentRow(res.data);
        setModalVisible(true);
        setMode('view');
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 编辑
  const handleEdit = async (indexId: any) => {
    setLoading(true);
    try {
      const res = await getJobIndexSingle(indexId);
      if (res.code === 200) {
        setCurrentRow(res.data);
        setModalVisible(true);
        setMode('edit');
      } else {
        message.error(res.msg);
      }
    } catch (error) {
      message.error('获取编辑数据失败');
    } finally {
      setLoading(false);
    }
  };

  const columns: ProColumns<API.JobIndex.JobIndexItem>[] = [
    {
      title: '指标ID',
      dataIndex: 'indexId',
      valueType: 'text',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '指标名称',
      dataIndex: 'indexName',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '指标描述',
      dataIndex: 'indexDesc',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '是否启用',
      dataIndex: 'isActive',
      valueType: 'select',
      align: 'center',
      valueEnum: {
        '0': { text: '启用' },
        '2': { text: '未启用' },
      },
      fieldProps: {
        options: [
          { label: '启用', value: '0' },
          { label: '未启用', value: '2' },
        ],
        defaultValue: '0',
        allowClear: false,
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'indexId',
      width: 300,
      render: (indexId, record) => (
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8 }}>
          <Button
            type="link"
            size="small"
            key="view"
            icon={<EyeOutlined />}
            loading={loading}
            hidden={!access.hasPerms('jobIndex:view')}
            onClick={() => handleViewDetail(indexId)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            size="small"
            key="edit"
            icon={<FormOutlined />}
            loading={loading}
            hidden={!access.hasPerms('jobIndex:update')}
            onClick={() => handleEdit(indexId)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            key="delete"
            icon={<DeleteOutlined />}
            hidden={!access.hasPerms('jobIndex:delete')}
            onClick={async () => {
              Modal.confirm({
                title: '删除',
                content: '确定删除该指标吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                  const success = await handleRemoveOne(indexId);
                  if (success) {
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  }
                },
              });
            }}
          >
            删除
          </Button>
        </div>
      ),
    },
  ];

  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.JobIndex.JobIndexItem>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="indexId"
          key="jobIndexIndex"
          columns={columns}
          search={{
            labelWidth: 'auto',
          }}
          request={async (
            params: API.JobIndex.ListParams & {
              pageSize?: number;
              current?: number;
            },
          ) => {
            const queryParams = {
              ...params,
              isActive: params.isActive || '0', //默认查询启用
            };
            const res = await getJobIndexList({ ...queryParams } as API.JobIndex.ListParams);
            return {
              data: res.rows,
              total: res.total,
              success: true,
            };
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('jobIndex:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
                setMode('create');
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
        />
      </div>
      <EditJobIndexRow
        open={modalVisible}
        mode={mode}
        onSubmit={async (values: API.JobIndex.JobIndexItem) => {
          try {
            let resData;
            if (values.indexId) {
              resData = await updateJobIndex(values as API.JobIndex.UpdateParams);
            } else {
              resData = await saveJobIndex(values as API.JobIndex.AddParams);
            }
            if (resData.code === 200) {
              setModalVisible(false);
              setCurrentRow(undefined);
              if (values.indexId) {
                message.success('修改成功');
              } else {
                message.success('新增成功');
              }
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } else {
              message.error(resData.msg || '操作失败');
            }
          } catch (error) {
            message.error('操作失败');
          }
        }}
        values={currentRow}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
      />
    </Fragment>
  );
}

export default JobIndexList;
