import React, { useEffect, useRef, useState } from 'react';
import { useAccess } from '@umijs/max';
import { Button, message, Modal, Switch, Tag } from 'antd';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, FormOutlined, EyeOutlined } from '@ant-design/icons';
import {
  getPolicyInfoList,
  getPolicyInfoDetail,
  addPolicyInfo,
  updatePolicyInfo,
  deletePolicyInfo,
  changePolicyStatus,
} from '@/services/cms/policyInfo';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag, { DictValueEnumObj } from '@/components/DictTag';
import EditModal from './components/EditModal';
import DetailModal from './components/DetailModal';

const PolicyMgmt: React.FC = () => {
  const access = useAccess();
  const actionRef = useRef<ActionType>();
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [currentRow, setCurrentRow] = useState<API.PolicyInfo.PolicyInfoItem>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [userTypeEnum, setUserTypeEnum] = useState<DictValueEnumObj>({});

  useEffect(() => {
    getDictValueEnum('user_type', false, true).then((data) => {
      setUserTypeEnum(data);
    });
  }, []);

  const handleDelete = async (ids: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除选中的政策信息吗？',
      onOk: async () => {
        const res = await deletePolicyInfo(ids);
        if (res.code === 200) {
          message.success('删除成功');
          actionRef.current?.reload();
          setSelectedRowKeys([]);
        } else {
          message.error(res.msg || '删除失败');
        }
      },
    });
  };

  const handleStatusChange = async (id: number, checked: boolean) => {
    const newStatus = checked ? '0' : '1';
    const statusLabel = checked ? '启用' : '禁用';
    Modal.confirm({
      title: `确认${statusLabel}`,
      content: `确定要${statusLabel}该政策吗？`,
      onOk: async () => {
        const res = await changePolicyStatus(id, newStatus);
        if (res.code === 200) {
          message.success(`${statusLabel}成功`);
          actionRef.current?.reload();
        } else {
          message.error(res.msg || `${statusLabel}失败`);
        }
      },
    });
  };

  const columns: ProColumns<API.PolicyInfo.PolicyInfoItem>[] = [
    {
      title: '政策名称',
      dataIndex: 'zcmc',
      ellipsis: true,
    },
    {
      title: '政策类型',
      dataIndex: 'zclx',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '政策级别',
      dataIndex: 'zcLevel',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '标签',
      dataIndex: 'policyTag',
      hideInSearch: true,
      width: 160,
      render: (_, record) => {
        if (!record.policyTag) {
          return '-';
        }
        const tags = String(record.policyTag).split(',').filter(Boolean);
        return (
          <span style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
            {tags.map((tag) => (
              <DictTag key={tag} enums={userTypeEnum} value={tag.trim()} />
            ))}
          </span>
        );
      },
    },
    {
      title: '发文单位',
      dataIndex: 'sourceUnit',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '受理单位',
      dataIndex: 'acceptUnit',
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '发文时间',
      dataIndex: 'publishTime',
      hideInSearch: true,
      width: 110,
    },
    {
      title: '浏览数',
      dataIndex: 'viewNum',
      hideInSearch: true,
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      valueType: 'select',
      valueEnum: {
        '0': { text: '启用', status: 'Success' },
        '1': { text: '禁用', status: 'Error' },
      },
      fixed: 'right',
      render: (_, record) => {
        const canChangeStatus = access.hasPerms('cms:policyInfo:status');
        if (canChangeStatus) {
          return (
            <Switch
              checked={record.status === '0'}
              checkedChildren="启用"
              unCheckedChildren="禁用"
              onChange={(checked) => handleStatusChange(record.id, checked)}
            />
          );
        }
        return (
          <Tag color={record.status === '0' ? 'success' : 'error'}>
            {record.status === '0' ? '启用' : '禁用'}
          </Tag>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      width: 160,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          icon={<EyeOutlined />}
          onClick={async () => {
            const res = await getPolicyInfoDetail(record.id);
            if (res.code === 200) {
              setCurrentRow(res.data);
              setDetailModalVisible(true);
            }
          }}
        >
          详情
        </Button>,
        <Button
          key="edit"
          type="link"
          size="small"
          icon={<FormOutlined />}
          hidden={!access.hasPerms('cms:policyInfo:edit')}
          onClick={async () => {
            const res = await getPolicyInfoDetail(record.id);
            if (res.code === 200) {
              setCurrentRow(res.data);
              setEditModalVisible(true);
            }
          }}
        >
          编辑
        </Button>,
        <Button
          key="delete"
          type="link"
          size="small"
          danger
          icon={<DeleteOutlined />}
          hidden={!access.hasPerms('cms:policyInfo:remove')}
          onClick={() => handleDelete(String(record.id))}
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.PolicyInfo.PolicyInfoItem>
        headerTitle="政策信息列表"
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        scroll={{ x: 'max-content' }}
        rowSelection={{
          selectedRowKeys,
          onChange: setSelectedRowKeys,
        }}
        request={async (params) => {
          const res = await getPolicyInfoList({
            pageNum: params.current,
            pageSize: params.pageSize,
            searchValue: params.zcmc,
          });
          return { data: res.rows, total: res.total, success: true };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            icon={<PlusOutlined />}
            hidden={!access.hasPerms('cms:policyInfo:add')}
            onClick={() => {
              setCurrentRow(undefined);
              setEditModalVisible(true);
            }}
          >
            新增
          </Button>,
          selectedRowKeys.length > 0 && (
            <Button
              key="batchDelete"
              danger
              icon={<DeleteOutlined />}
              hidden={!access.hasPerms('cms:policyInfo:remove')}
              onClick={() => handleDelete(selectedRowKeys.join(','))}
            >
              批量删除
            </Button>
          ),
        ]}
      />
      <EditModal
        open={editModalVisible}
        values={currentRow}
        onCancel={() => {
          setEditModalVisible(false);
          setCurrentRow(undefined);
        }}
        onSubmit={async (values) => {
          const res = values.id
            ? await updatePolicyInfo(values)
            : await addPolicyInfo(values);
          if (res.code === 200) {
            message.success(values.id ? '修改成功' : '新增成功');
            setEditModalVisible(false);
            setCurrentRow(undefined);
            actionRef.current?.reload();
          } else {
            message.error(res.msg || '操作失败');
          }
        }}
      />
      <DetailModal
        open={detailModalVisible}
        data={currentRow}
        onCancel={() => {
          setDetailModalVisible(false);
          setCurrentRow(undefined);
        }}
      />
    </PageContainer>
  );
};

export default PolicyMgmt;
