<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="90px">
            <el-form-item label="点位名称" prop="monitorCode">
              <el-tree-select
                v-model="queryParams.monitorCode"
                :data="monitorTreeOptions"
                :props="monitorTreeProps"
                placeholder="请选择点位"
                clearable
                filterable
                check-strictly
                style="width: 240px"
              />
            </el-form-item>
            <el-form-item label="导出类型" prop="exportType">
              <el-input v-model="queryParams.exportType" placeholder="请输入导出类型" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="文件格式" prop="fileFormat">
              <el-select v-model="queryParams.fileFormat" placeholder="请选择文件格式" clearable style="width: 160px">
                <el-option v-for="item in fileFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="导出状态" prop="exportStatus">
              <el-select v-model="queryParams.exportStatus" placeholder="请选择导出状态" clearable style="width: 160px">
                <el-option v-for="item in exportStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="导出时间">
              <el-date-picker
                v-model="daterangeExportTime"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                style="width: 360px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['ems/base:dataExportTask:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['ems/base:dataExportTask:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['ems/base:dataExportTask:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['ems/base:dataExportTask:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" @queryTable="getList" />
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="dataExportTaskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="columns[0].visible" label="序号" type="index" width="60" align="center" />
        <el-table-column v-if="columns[1].visible" label="导出类型" align="center" prop="exportType" min-width="120" />
        <el-table-column v-if="columns[2].visible" label="点位名称" align="center" min-width="220" show-overflow-tooltip>
          <template #default="scope">
            <div>{{ resolveMonitorName(scope.row) }}</div>
            <div class="sub-text">{{ scope.row.metricCode || '-' }}</div>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[3].visible" label="导出开始时间" align="center" prop="timeStart" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.timeStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[4].visible" label="导出结束时间" align="center" prop="timeEnd" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.timeEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns[5].visible" label="文件格式" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="fileFormatOptions" :value="scope.row.fileFormat" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[6].visible" label="文件名称" align="center" prop="fileName" min-width="180" show-overflow-tooltip />
        <el-table-column v-if="columns[7].visible" label="导出状态" align="center" width="110">
          <template #default="scope">
            <dict-tag :options="exportStatusOptions" :value="scope.row.exportStatus" />
          </template>
        </el-table-column>
        <el-table-column v-if="columns[8].visible" label="备注" align="center" prop="remark" min-width="180" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="140" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['ems/base:dataExportTask:edit']" />
            </el-tooltip>
            <el-tooltip content="下载" placement="top">
              <el-button link type="primary" icon="Download" :disabled="!scope.row.fileUrl" @click="handleDownload(scope.row)" />
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['ems/base:dataExportTask:remove']" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <el-dialog :title="dialog.title" v-model="dialog.visible" width="720px" append-to-body>
      <el-form ref="dataExportTaskFormRef" :model="form" :rules="rules" label-width="104px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="点位名称" prop="monitorCode">
              <el-tree-select
                v-model="form.monitorCode"
                :data="monitorTreeOptions"
                :props="monitorTreeProps"
                placeholder="请选择点位"
                filterable
                check-strictly
                style="width: 100%"
                @change="handleMonitorChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="测量项编码">
              <el-input v-model="form.metricCode" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="导出类型" prop="exportType">
              <el-input v-model="form.exportType" placeholder="请输入导出类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件格式" prop="fileFormat">
              <el-select v-model="form.fileFormat" placeholder="请选择文件格式" style="width: 100%">
                <el-option v-for="item in fileFormatOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="导出开始时间" prop="timeStart">
              <el-date-picker clearable v-model="form.timeStart" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择导出开始时间" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="导出结束时间" prop="timeEnd">
              <el-date-picker clearable v-model="form.timeEnd" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择导出结束时间" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="导出条件" prop="exportCondition">
          <el-input v-model="form.exportCondition" type="textarea" :rows="3" placeholder="请输入导出条件说明" />
        </el-form-item>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="文件名称" prop="fileName">
              <el-input v-model="form.fileName" placeholder="请输入文件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-alert type="info" :closable="false" show-icon title="文件地址和导出状态由任务执行链路回填，页面不再允许人工录入，避免把生成结果字段误写成业务输入。" />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="DataExportTask" lang="ts">
import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import { listDataExportTask, getDataExportTask, delDataExportTask, addDataExportTask, updateDataExportTask } from '@/api/ems/base/dataExportTask';
import type { DataExportTaskVO, DataExportTaskQuery, DataExportTaskForm } from '@/api/ems/base/dataExportTask/types';
import type { EmsTreeNode } from '@/api/ems/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

interface MonitorTreeNode extends EmsTreeNode {
  label?: string;
  value?: string | number;
  children?: MonitorTreeNode[];
}

const fileFormatOptions = [
  { label: 'Excel', value: 'XLSX' },
  { label: 'CSV', value: 'CSV' },
  { label: 'JSON', value: 'JSON' }
];

const exportStatusOptions = [
  { label: '待执行', value: 'PENDING' },
  { label: '执行中', value: 'PROCESSING' },
  { label: '已完成', value: 'SUCCESS' },
  { label: '失败', value: 'FAIL' }
];

const monitorTreeOptions = ref<MonitorTreeNode[]>([]);
const monitorInfoMap = ref<Record<string, { monitorName?: string; metricCode?: string }>>({});

const dataExportTaskList = ref<DataExportTaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const daterangeExportTime = ref<string[]>([]);

const columns = ref<FieldOption[]>([
  { key: 0, label: '序号', visible: true, children: [] },
  { key: 1, label: '导出类型', visible: true, children: [] },
  { key: 2, label: '点位名称', visible: true, children: [] },
  { key: 3, label: '导出开始时间', visible: true, children: [] },
  { key: 4, label: '导出结束时间', visible: true, children: [] },
  { key: 5, label: '文件格式', visible: true, children: [] },
  { key: 6, label: '文件名称', visible: true, children: [] },
  { key: 7, label: '导出状态', visible: true, children: [] },
  { key: 8, label: '备注', visible: true, children: [] }
]);

const queryFormRef = ref<ElFormInstance>();
const dataExportTaskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const monitorTreeProps = {
  label: 'label',
  value: 'value',
  children: 'children'
};

const createFormData = (): DataExportTaskForm => ({
  id: undefined,
  exportType: undefined,
  monitorCode: undefined,
  monitorName: undefined,
  metricCode: undefined,
  timeStart: undefined,
  timeEnd: undefined,
  exportCondition: undefined,
  fileFormat: 'XLSX',
  fileName: undefined,
  fileUrl: undefined,
  exportStatus: 'PENDING',
  remark: undefined
});

const data = reactive<PageData<DataExportTaskForm, DataExportTaskQuery>>({
  form: createFormData(),
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    exportType: undefined,
    monitorCode: undefined,
    fileFormat: undefined,
    exportStatus: undefined,
    params: {}
  },
  rules: {
    monitorCode: [{ required: true, message: '点位不能为空', trigger: 'change' }],
    exportType: [{ required: true, message: '导出类型不能为空', trigger: 'blur' }],
    fileFormat: [{ required: true, message: '文件格式不能为空', trigger: 'change' }],
    timeStart: [{ required: true, message: '导出开始时间不能为空', trigger: 'change' }],
    timeEnd: [{ required: true, message: '导出结束时间不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

const normalizeMonitorTree = (nodes: MonitorTreeNode[] = []): MonitorTreeNode[] =>
  nodes.map((node) => {
    const children = Array.isArray(node.children) ? normalizeMonitorTree(node.children) : [];
    const label = node.monitorName || node.label || node.name || node.monitorCode || String(node.value ?? '');
    const value = node.monitorCode || node.value || node.monitorId || node.objId || node.id;
    const key = String(value ?? '');
    if (key) {
      monitorInfoMap.value[key] = {
        monitorName: node.monitorName || label,
        metricCode: node.metricCode as string | undefined
      };
    }
    return {
      ...node,
      label,
      value,
      children
    };
  });

const syncQueryTimeRange = () => {
  queryParams.value.params = queryParams.value.params || {};
  queryParams.value.params.beginTimeStart = daterangeExportTime.value?.[0];
  queryParams.value.params.beginTimeEnd = daterangeExportTime.value?.[1];
};

const resolveMonitorName = (row?: Partial<DataExportTaskVO> | Partial<DataExportTaskForm> | null) =>
  row?.monitorName || monitorInfoMap.value[String(row?.monitorCode || '')]?.monitorName || row?.monitorCode || '-';

const loadMonitorOptions = async () => {
  const response = await getMonitorInfoTree({
    monitorTypeList: [5, 6, 7, 8, 9, 10]
  } as any);
  monitorInfoMap.value = {};
  monitorTreeOptions.value = normalizeMonitorTree(((response as any).data ?? response ?? []) as MonitorTreeNode[]);
};

const getList = async () => {
  loading.value = true;
  try {
    syncQueryTimeRange();
    const res = await listDataExportTask(queryParams.value);
    dataExportTaskList.value = ((res as any).rows ?? []) as DataExportTaskVO[];
    total.value = Number((res as any).total ?? 0);
  } finally {
    loading.value = false;
  }
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = createFormData();
  dataExportTaskFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  daterangeExportTime.value = [];
  handleQuery();
};

const handleSelectionChange = (selection: DataExportTaskVO[]) => {
  ids.value = selection.map((item) => item.id as string | number);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加数据导出任务';
};

const handleUpdate = async (row?: DataExportTaskVO) => {
  reset();
  const targetId = row?.id ?? ids.value[0];
  if (!targetId) {
    return;
  }
  const res = await getDataExportTask(targetId);
  form.value = {
    ...createFormData(),
    ...((res as any).data ?? {})
  };
  dialog.visible = true;
  dialog.title = '修改数据导出任务';
};

const handleMonitorChange = (monitorCode?: string | number) => {
  const matched = monitorInfoMap.value[String(monitorCode || '')];
  // 点位编码和测量项编码都来自点位档案，页面只让用户选业务点位，避免技术编码手填出错。
  form.value.monitorName = matched?.monitorName;
  form.value.metricCode = matched?.metricCode;
};

const submitForm = () => {
  dataExportTaskFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) {
      return;
    }
    buttonLoading.value = true;
    try {
      handleMonitorChange(form.value.monitorCode);
      form.value.exportStatus = form.value.exportStatus || 'PENDING';
      if (form.value.id) {
        await updateDataExportTask(form.value);
      } else {
        await addDataExportTask(form.value);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};

const handleDelete = async (row?: DataExportTaskVO) => {
  const targetIds = row?.id ?? ids.value;
  await proxy?.$modal.confirm(`是否确认删除数据导出任务编号为"${targetIds}"的数据项？`);
  await delDataExportTask(targetIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const handleExport = () => {
  syncQueryTimeRange();
  proxy?.download(
    'ems/base/dataExportTask/export',
    {
      ...queryParams.value
    },
    `dataExportTask_${new Date().getTime()}.xlsx`
  );
};

const handleDownload = (row: DataExportTaskVO) => {
  if (!row.fileUrl) {
    return;
  }
  window.open(row.fileUrl, '_blank');
};

onMounted(async () => {
  await loadMonitorOptions();
  await getList();
});
</script>

<style scoped>
.sub-text {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  line-height: 18px;
}
</style>
