import React, { Fragment, useRef, useState, useEffect } 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 { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
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 [isActiveEnum, setIsActiveEnum] = useState<any>([]);

  useEffect(() => {
    getDictValueEnum('enable_status', true).then((data) => {
      setIsActiveEnum(data);
    });
  }, []);

  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: isActiveEnum,
      fieldProps: {
        allowClear: false,
        defaultValue: '1',
      },
      render: (_, record) => {
        return <DictTag enums={isActiveEnum} value={record.isActive} />;
      },
    },
    {
      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('recruitmentDataCollection:metricAdmin:view')}
            onClick={() => handleViewDetail(indexId)}
          >
            查看详情
          </Button>
          <Button
            type="link"
            size="small"
            key="edit"
            icon={<FormOutlined />}
            loading={loading}
            hidden={!access.hasPerms('recruitmentDataCollection:metricAdmin:edit')}
            onClick={() => handleEdit(indexId)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            danger
            key="delete"
            icon={<DeleteOutlined />}
            hidden={!access.hasPerms('recruitmentDataCollection:metricAdmin: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 || '1', //默认查询启用
            };
            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('recruitmentDataCollection:metricAdmin:add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
                setMode('create');
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
          ]}
        />
      </div>
      <EditJobIndexRow
        open={modalVisible}
        mode={mode}
        isActiveEnum={isActiveEnum}
        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;
