import { MyButtons, MyPageContainer, useCurrentPermissions } from '@/common';
import { Apis } from '@/gen/Apis';
import { HouseChargeTasksStatusEnum } from '@/gen/Enums';
import { ReloadOutlined } from '@ant-design/icons';
import { ProCard, ProDescriptions } from '@ant-design/pro-components';
import { Button, DatePicker, Select, Space, Spin, Tag } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useState } from 'react';
import TaskCreate from './modals/TaskCreate';
import TaskShow from './modals/TaskShow';

export default function Index({ title = '账单生成' }) {
  const [selectedProject, setSelectedProject] = useState<number | null>(null);
  const [selectedStandard, setSelectedStandard] = useState<number | null>(null);
  const [selectedChargeStandardName, setSelectedChargeStandardName] = useState<
    any | null
  >(null);
  const [projects, setProjects] = useState<any[]>([]);
  const [standards, setStandards] = useState<any[]>([]);
  const [tasks, setTasks] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentYear, setCurrentYear] = useState(dayjs().year());
  const [taskCreateOpen, setTaskCreateOpen] = useState(false);
  const [selectedMonth, setSelectedMonth] = useState<string | null>(null);
  const [taskShowOpen, setTaskShowOpen] = useState(false);
  const [selectedTask, setSelectedTask] = useState<any | null>(null);

  useEffect(() => {
    const fetchData = async () => {
      const data = await loadProjects();
      if (data) {
        setProjects(data);
      }
    };
    fetchData();
  }, []);

  useEffect(() => {
    if (selectedProject) {
      const fetchData = async () => {
        const data = await loadStandards();
        if (data) {
          setStandards(data);
        }
      };
      fetchData();
    } else {
      setStandards([]);
      setSelectedStandard(null);
      setTasks([]);
    }
  }, [selectedProject]);

  useEffect(() => {
    if (selectedProject && selectedStandard) {
      loadTasks();
    }
  }, [selectedProject, selectedStandard]);

  const loadProjects = async () => {
    try {
      setLoading(true);
      let res = await Apis.Asset.AssetProjects.Select({});
      return res?.data;
    } catch (error) {
      console.error('加载项目列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getCurrentPermissions = useCurrentPermissions();
  let ButtonAdd = (res: any) => {
    return getCurrentPermissions({
      add: (
        <TaskCreate
          title="账单生成任务"
          reload={loadTasks}
          item={{
            asset_projects_id: selectedProject,
            house_charge_standards_id: selectedStandard,
            month: res?.month,
            year: res?.year,
            name: res?.charge_standard_name,
          }}
        />
      ),
    });
  };
  let ButtonDo = (res: any) => {
    return getCurrentPermissions({
      do: (
        <Button
          type="primary"
          size="small"
          onClick={(e) => {
            e.stopPropagation();
            handleExecuteTask(res?.task);
          }}
        >
          {res?.isPending ? '执行' : '重新执行'}
        </Button>
      ),
    });
  };
  let ButtonShow = (res: any) => {
    return getCurrentPermissions({
      show: (
        <Button
          type="default"
          size="small"
          onClick={(e) => {
            e.stopPropagation();
            handleShowTask(res?.task);
          }}
        >
          详情
        </Button>
      ),
    });
  };
  let ButtonDel = (res: any) => {
    return getCurrentPermissions({
      delete: (
        <MyButtons.Delete
          size="small"
          onConfirm={() => {
            deleteTask(res?.task);
          }}
        />
      ),
    });
  };
  const loadStandards = async () => {
    if (!selectedProject) return;
    try {
      setLoading(true);
      let res = await Apis.HouseCharge.HouseChargeStandards.Select({
        asset_projects_id: selectedProject,
      });
      return res?.data;
    } catch (error) {
      console.error('加载收费标准列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadTasks = async (year?: number) => {
    if (!selectedProject || !selectedStandard) return;
    try {
      setLoading(true);
      const res = await Apis.HouseCharge.HouseChargeTasks.List({
        asset_projects_id: selectedProject,
        house_charge_standards_id: selectedStandard,
        bill_year: String(year || currentYear),
        perPage: 20,
      });
      if (res?.data) {
        setTasks(res.data || []);
      }
    } catch (error) {
      console.error('加载账单任务列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const getMonthTaskStatus = (month: number) => {
    const task = tasks.find(
      (t: any) =>
        t.bill_year === String(currentYear) &&
        t.bill_month === month &&
        t.house_charge_standards_id === selectedStandard,
    );
    if (!task) {
      return { status: 'none', label: '无账单', task: null };
    }
    const statusEnum =
      HouseChargeTasksStatusEnum[
        task.status as keyof typeof HouseChargeTasksStatusEnum
      ];
    return {
      status: task.status,
      label: statusEnum?.text || task.status,
      task,
    };
  };

  const handleGenerateBill = (month: number) => {
    if (!selectedStandard) {
      alert('请先选择收费标准');
      return;
    }
    const monthStr = `${currentYear}-${String(month).padStart(2, '0')}`;
    setSelectedMonth(monthStr);
    setTaskCreateOpen(true);
  };

  const handleExecuteTask = async (task: any) => {
    try {
      setLoading(true);
      await Apis.HouseCharge.HouseChargeTasks.ExecuteTask({
        id: task.id,
      });
      loadTasks();
    } catch (error) {
      console.error('执行任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const deleteTask = async (task: any) => {
    try {
      setLoading(true);
      await Apis.HouseCharge.HouseChargeTasks.Delete({
        id: task.id,
      });
      loadTasks();
    } catch (error) {
      console.error('删除任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleShowTask = (task: any) => {
    setSelectedTask(task);
    setTaskShowOpen(true);
  };

  return (
    <MyPageContainer
      title={title}
      enableTabs={true}
      tabKey="house_charge_tasks"
      tabLabel={title}
    >
      <Spin spinning={loading}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          <ProCard
            title="选择项目与收费标准"
            headerBordered
            extra={
              <Button
                type="default"
                onClick={() => loadTasks()}
                icon={<ReloadOutlined />}
              >
                刷新
              </Button>
            }
          >
            <ProDescriptions
              column={3}
              dataSource={{}}
              labelStyle={{ display: 'flex', alignItems: 'center' }}
            >
              <ProDescriptions.Item
                label="项目"
                contentStyle={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <Select
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  value={selectedProject || undefined}
                  onChange={(value) => {
                    setSelectedProject(value);
                    setSelectedStandard(null);
                  }}
                  placeholder="请选择项目"
                >
                  {projects.map((project) => (
                    <Select.Option key={project.value} value={project.value}>
                      {project.label}
                    </Select.Option>
                  ))}
                </Select>
              </ProDescriptions.Item>
              <ProDescriptions.Item
                label="收费标准"
                contentStyle={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <Select
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  value={selectedStandard || undefined}
                  onChange={(value, option) => {
                    console.log(value, option);
                    setSelectedChargeStandardName(option || '');
                    setSelectedStandard(value);
                  }}
                  disabled={!selectedProject}
                  placeholder="请选择收费标准"
                >
                  {standards.map((standard) => (
                    <Select.Option key={standard.value} value={standard.value}>
                      {standard.label}
                    </Select.Option>
                  ))}
                </Select>
              </ProDescriptions.Item>
              <ProDescriptions.Item
                label="选择年份"
                contentStyle={{
                  width: '100%',
                  display: 'flex',
                  alignItems: 'center',
                }}
              >
                <DatePicker
                  style={{ width: '100%' }}
                  picker="year"
                  format="YYYY"
                  value={dayjs().year(currentYear)}
                  onChange={(date: any) => {
                    if (date) {
                      const newYear = date.year();
                      setCurrentYear(newYear);
                      if (selectedProject && selectedStandard) {
                        loadTasks(newYear);
                      }
                    }
                  }}
                />
              </ProDescriptions.Item>
            </ProDescriptions>
          </ProCard>

          <ProCard
            title={`${currentYear}年账单生成情况 「${
              selectedChargeStandardName?.children || ''
            }」`}
            headerBordered
          >
            {!selectedProject || !selectedStandard ? (
              <div
                style={{
                  textAlign: 'center',
                  color: '#ff0000ff',
                  padding: '40px',
                  fontSize: '16px',
                }}
              >
                请先选择项目与收费标准！
              </div>
            ) : (
              <div
                style={{
                  display: 'grid',
                  gridTemplateColumns: 'repeat(4, 1fr)',
                  gap: '16px',
                }}
              >
                {Array.from({ length: 12 }, (_, i) => {
                  const month = i + 1;
                  const { status, label, task } = getMonthTaskStatus(month);
                  const isCompleted =
                    status === HouseChargeTasksStatusEnum.Completed.value;
                  const isProcessing =
                    status === HouseChargeTasksStatusEnum.InProgress.value;
                  const isPending =
                    status === HouseChargeTasksStatusEnum.Pending.value;
                  const isFailed =
                    status === HouseChargeTasksStatusEnum.Failed.value;
                  const isNone = status === 'none';

                  let tagColor = 'default';
                  let cardBgColor = '#ffffff';
                  let cardBorderColor = '#f0f0f0';

                  if (isCompleted) {
                    tagColor = 'success';
                    cardBgColor = '#f6ffed';
                    cardBorderColor = '#b7eb8f';
                  }
                  if (isProcessing) {
                    tagColor = 'processing';
                    cardBgColor = '#e6f7ff';
                    cardBorderColor = '#91d5ff';
                  }
                  if (isPending) {
                    tagColor = 'warning';
                    cardBgColor = '#fff7e6';
                    cardBorderColor = '#ffd591';
                  }
                  if (isFailed) {
                    tagColor = 'error';
                    cardBgColor = '#fff1f0';
                    cardBorderColor = '#ffa39e';
                  }
                  if (isNone) {
                    tagColor = 'default';
                    cardBgColor = '#ffffff';
                    cardBorderColor = '#f0f0f0';
                  }

                  return (
                    <div
                      key={month}
                      style={{
                        border: `1px solid ${cardBorderColor}`,
                        borderRadius: '8px',
                        padding: '20px',
                        textAlign: 'center',
                        backgroundColor: cardBgColor,
                        cursor: isNone ? 'pointer' : 'default',
                        transition: 'all 0.3s ease',
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
                      }}
                      onMouseEnter={(e) => {
                        if (isNone) {
                          e.currentTarget.style.backgroundColor = '#e6f7ff';
                          e.currentTarget.style.borderColor = '#1890ff';
                          e.currentTarget.style.boxShadow =
                            '0 4px 12px rgba(24, 144, 255, 0.15)';
                        } else {
                          // 为不同状态添加对应的悬停效果
                          if (isCompleted) {
                            e.currentTarget.style.backgroundColor = '#d9f7be';
                            e.currentTarget.style.borderColor = '#95de64';
                          } else if (isProcessing) {
                            e.currentTarget.style.backgroundColor = '#bae7ff';
                            e.currentTarget.style.borderColor = '#69c0ff';
                          } else if (isPending) {
                            e.currentTarget.style.backgroundColor = '#ffecb3';
                            e.currentTarget.style.borderColor = '#ffc53d';
                          } else if (isFailed) {
                            e.currentTarget.style.backgroundColor = '#ffccc7';
                            e.currentTarget.style.borderColor = '#ff7875';
                          }
                          e.currentTarget.style.boxShadow =
                            '0 4px 12px rgba(0, 0, 0, 0.1)';
                        }
                      }}
                      onMouseLeave={(e) => {
                        if (isNone) {
                          e.currentTarget.style.backgroundColor = '#ffffff';
                          e.currentTarget.style.borderColor = '#f0f0f0';
                        } else {
                          // 恢复为原始状态颜色
                          e.currentTarget.style.backgroundColor = cardBgColor;
                          e.currentTarget.style.borderColor = cardBorderColor;
                        }
                        e.currentTarget.style.boxShadow =
                          '0 2px 8px rgba(0, 0, 0, 0.06)';
                      }}
                    >
                      <div
                        style={{
                          fontSize: '16px',
                          fontWeight: 'bold',
                          marginBottom: '12px',
                        }}
                      >
                        {currentYear}年-
                        {month}月
                      </div>
                      <div>
                        <Tag color={tagColor} style={{ fontSize: '14px' }}>
                          {label}
                          {task?.task_count ? `(${task.task_count})` : ''}
                        </Tag>
                      </div>
                      <div>
                        {task?.start_date
                          ? `${task.start_date} 至 ${task.end_date}`
                          : ''}
                      </div>
                      {isNone && (
                        <Space
                          style={{
                            marginTop: '16px',
                            justifyContent: 'center',
                          }}
                        >
                          <ButtonAdd
                            year={currentYear}
                            month={month}
                            charge_standard_name={
                              task?.charge_standard_name ||
                              selectedChargeStandardName?.children
                            }
                          />
                        </Space>
                      )}
                      {(isPending || isFailed || isCompleted) && task && (
                        <Space
                          style={{
                            marginTop: '16px',
                            justifyContent: 'center',
                          }}
                        >
                          {(isPending || isFailed) && <ButtonDo task={task} />}
                          {isCompleted && (
                            <>
                              <ButtonShow task={task} />
                              <ButtonDel task={task} />
                            </>
                          )}
                        </Space>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </ProCard>
        </div>
      </Spin>

      <TaskShow
        title="任务详情"
        open={taskShowOpen}
        setOpen={setTaskShowOpen}
        item={selectedTask}
      />
    </MyPageContainer>
  );
}
