import React, { Fragment, useEffect, useRef, useState } from 'react';
import { FormattedMessage, useAccess } from '@umijs/max';
import { Button, FormInstance, message } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { AlignLeftOutlined, FormOutlined, PlusOutlined } from '@ant-design/icons';
import EditCompanyListRow from './edit';
import {
  addCmsIndustryIndustryt,
  delCmsIndustryList,
  exportCmsIndustry,
  getCmsIndustryTreeList,
  updateCmsIndustryIndustryt,
} from '@/services/classify/industry';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';

// 定义行业数据类型（替代API.ClassifyIndustry.IndustryRow）
interface IndustryItem {
  id: number;
  industryName: string;
  orderNum?: number;
  status?: string;
  children?: IndustryItem[];
}

const handleRemoveOne = async (id: string) => {
  // 参数改为id
  const hide = message.loading('正在删除');
  try {
    const resp = await delCmsIndustryList(id);
    hide();
    if (resp.code === 200) {
      message.success('删除成功，即将刷新');
    } else {
      message.error(resp.msg);
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const handleExport = async (values: any) => {
  // 简化类型定义
  const hide = message.loading('正在导出');
  try {
    await exportCmsIndustry(values);
    hide();
    message.success('导出成功');
    return true;
  } catch (error) {
    hide();
    message.error('导出失败，请重试');
    return false;
  }
};

// 处理树形数据的函数（移到组件外部）
function processTreeData(data: any[]): IndustryItem[] {
  return data.map((item) => ({
    id: item.id,
    industryName: item.label,
    orderNum: item.sort || 0,
    status: item.status || '0',
    key: item.id, // ProTable需要的唯一key
    children: item.children ? processTreeData(item.children) : undefined,
  }));
}

function ManagementList() {
  const access = useAccess();
  const formTableRef = useRef<FormInstance>();
  const actionRef = useRef<ActionType>();

  const [currentRow, setCurrentRow] = useState<IndustryItem>(); // 使用新类型
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [industryStatusEnum, setIndustryStatusEnum] = useState<any>([]);

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

  const columns: ProColumns<IndustryItem>[] = [
    // 使用新类型
    {
      title: '行业名称',
      dataIndex: 'industryName',
      valueType: 'text',
      align: 'center',
    },
    {
      title: '显示顺序',
      dataIndex: 'orderNum',
      valueType: 'text',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      valueType: 'select',
      valueEnum: industryStatusEnum,
      render: (_, record) => {
        return <DictTag enums={industryStatusEnum} value={record.status} />;
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      align: 'center',
      dataIndex: 'id', // 改为id
      width: 300,
      render: (id, record) => [
        <Button
          type="link"
          size="small"
          key="view"
          icon={<AlignLeftOutlined />}
          hidden={!access.hasPerms('area:business:List.view')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          详情
        </Button>,
        <Button
          type="link"
          size="small"
          key="edit"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('area:business:List.update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        // <Button
        //   type="link"
        //   size="small"
        //   danger
        //   key="batchRemove"
        //   icon={<DeleteOutlined />}
        //   hidden={!access.hasPerms('area:subway:List')}
        //   onClick={async () => {
        //     Modal.confirm({
        //       title: '删除',
        //       content: '确定删除该项吗？',
        //       onOk: async () => {
        //         const success = await handleRemoveOne(id.toString());
        //         if (success && actionRef.current) {
        //           actionRef.current.reload();
        //         }
        //       },
        //     });
        //   }}
        // >
        //   删除
        // </Button>,
      ],
    },
  ];

  return (
    <Fragment>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<IndustryItem>
          actionRef={actionRef}
          formRef={formTableRef}
          rowKey="id" // 改为id
          columns={columns}
          search={false}
          defaultExpandAllRows={true}
          childrenColumnName="children"
          pagination={false}
          request={async () => {
            try {
              const res = await getCmsIndustryTreeList();
              return {
                data: processTreeData(res.data || []),
                success: true,
              };
            } catch (error) {
              console.error('获取数据失败:', error);
              return { data: [], success: false };
            }
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('manage:List:add')}
              onClick={() => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>,
            <Button
              key="export"
              hidden={!access.hasPerms('system:user:export')}
              onClick={async () => {
                const searchVal = formTableRef.current?.getFieldsValue();
                handleExport(searchVal);
              }}
            >
              <PlusOutlined />
              <FormattedMessage id="pages.searchTable.export" defaultMessage="导出" />
            </Button>,
          ]}
        />
      </div>
      <EditCompanyListRow
        open={modalVisible}
        onSubmit={async (values) => {
          let resData;
          if (values.id) {
            // 改为id
            resData = await updateCmsIndustryIndustryt(values);
          } else {
            resData = await addCmsIndustryIndustryt(values);
          }
          if (resData.code === 200) {
            setModalVisible(false);
            setCurrentRow(undefined);
            message.success(values.id ? '修改成功' : '新增成功');
            actionRef.current?.reload();
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        industryStatusEnum={industryStatusEnum}
        values={currentRow}
        mode={
          currentRow?.id // 改为id
            ? access.hasPerms('area:business:List.update')
              ? 'edit'
              : 'view'
            : 'create'
        }
      />
    </Fragment>
  );
}

export default ManagementList;
