<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-row :gutter="10" class="mb8">
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="标签任务名称">
          <el-input
            v-model="queryForm.bizName"
            placeholder="请输入标签任务名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="plus"
          @click="openAddDialog"
          v-hasPermi="['meta:metatask:add']"
          >新建任务</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="edit"
          :disabled="singleOne"
          @click="openEditDialog(selectedRows[0])"
          v-hasPermi="['meta:metatask:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="top"
          :disabled="singleOne"
          @click="handleUp"
          v-hasPermi="['meta:metatask:up']"
          >上线</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="bottom"
          :disabled="singleTwo"
          @click="handleDown"
          v-hasPermi="['meta:metatask:down']"
          >下线</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="AlarmClock"
          :disabled="singleTwo"
          @click="handleDS"
          v-hasPermi="['meta:metatask:ds']"
          >调度</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="video-play"
          :disabled="singleTwo"
          @click="handleRun"
          v-hasPermi="['meta:metatask:run']"
          >运行</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="edit"
          :disabled="single"
          @click="handleLog"
          v-hasPermi="['meta:metatask:log']"
          >日志</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="delete"
          :disabled="multiple"
          @click="deleteSelected"
          v-hasPermi="['meta:metatask:delete']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="delete"
          :disabled="singleTwo"
          @click="handleDeleteSche"
          v-hasPermi="['meta:metatask:ds']"
          >删除调度</el-button
        >
      </el-col>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 表格 -->
    <el-table
          v-loading="loading"
          :data="bizList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="任务名称"
            align="center"
            key="bizName"
            prop="bizName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          
          />

          <el-table-column
            label="状态"
            align="center"
            key="status"
            prop="status"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
          >
          <template #default="scope">
                          <dict-tag
                :options="meta_task_status"
                :value="scope.row.status"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="调度ID"
            align="center"
            prop="schId"
            v-if="columns[3].visible"
            width="100"
          >
             <template #default="scope">
              <span>{{scope.row.schId}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[4].visible"
          >
             <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            prop="updateTime"
            v-if="columns[5].visible"
          >
             <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime) }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="创建人"
            align="center"
            key="createBy"
            prop="createBy"
            v-if="columns[6].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="修改人"
            align="center"
            key="updateBy"
            prop="updateBy"
            v-if="columns[7].visible"
            :show-overflow-tooltip="true"
          />

          <el-table-column label="操作" fixed="right" align="center" width="200">
            <template #default="{ row }">
              <el-button type="primary" link icon="Edit" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link icon="Delete" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryForm.pageNum"
      v-model:limit="queryForm.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="1600px"
      append-to-body
      :before-close="handleClose"
    >
      <el-form
        ref="bizFormRef"
        :model="form"
        :rules="rules"
        label-width="130px"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="标签任务名称" prop="bizName">
              <el-input v-model="form.bizName" style="width: 200px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="10">
          <el-form :model="leftQueryForm" inline size="small">
            <el-form-item label="系统名">
              <el-select
                v-model="leftQueryForm.ssysCd"
                placeholder="请选择系统"
                clearable
                filterable
                style="width: 180px"
              >
                <el-option
                  v-for="item in dsSysList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="表名">
              <el-input
                v-model="leftQueryForm.tabName"
                placeholder="请输入表名"
                clearable
                style="width: 180px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadLeftTable">查询</el-button>
            </el-form-item>
          </el-form>

          <el-table
            :data="leftTableData"
            height="300"
            border
            style="margin-top: 10px"
            @selection-change="handleLeftSelect"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="ssysCd" label="系统名" />
            <el-table-column prop="mdlName" label="模式名" />
            <el-table-column prop="tabEngName" label="表名" />
          </el-table>

          <pagination
            v-show="leftTotal > 0"
            :total="leftTotal"
            v-model:page="leftQueryForm.pageNum"
            v-model:limit="leftQueryForm.pageSize"
            @pagination="loadLeftTable"
          />
        </el-col>

        <el-col :span="4" class="flex-col-center">
          <el-button
            type="primary"
            @click="moveToRight"
            :disabled="leftSelected.length === 0"
          >
            &gt;
          </el-button>
          <el-button
            type="danger"
            style="margin-top: 10px"
            @click="moveToLeft"
            :disabled="rightSelected.length === 0"
          >
            &lt;
          </el-button>
        </el-col>

        <el-col :span="10">
          <el-table
            :data="rightTableData"
            height="360"
            border
            @selection-change="handleRightSelect"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="ssysCd" label="系统名" />
            <el-table-column prop="mdlName" label="模式名" />
            <el-table-column prop="tabEngName" label="表名" />
          </el-table>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 运行、调度、日志弹窗 -->
    <run-dialog
      ref="rundialog"
      :warningGroupList="warningGroupList"
      :environmentList="environmentList"
      :workerGroupList="workerGroupList"
      :processDefinitionCode="dsIds"
    />
    <ds-dialog
      ref="dsdialog"
      processDefinitionType="secTask"
      :warningGroupList="warningGroupList"
      :environmentList="environmentList"
      :workerGroupList="workerGroupList"
      :processDefinitionCode="dsIds"
      :getList="getList"
    />
    <log-dialog ref="logdialog" :defindName="defindName" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getMetaDataList } from '@/api/meta/metaInfo'
import { datasourceall} from "@/api/meta/metatask";
import {
  listTaskBizConfig,
  addTaskBizConfig,
  updateTaskBizConfig,
  getTaskBizRelaList,
  downOrUpmetatask,
  dsmetataskdelete,
  dsmetataskSec,
  delTaskBizConfig,
} from '@/api/taskMetadataConfig/metadataConfig'
import runDialog from '../../meta/metatask/runDialog'
import dsDialog from '../../meta/metatask/dsDialog'
import logDialog from '../../meta/metatask/logsDialog'

const { proxy } = getCurrentInstance()
const { meta_task_status } = proxy.useDict('meta_task_status')
const getDeptTree = async () => {
  const response = await datasourceall();
  warningGroupList.value = response.data.alertGroups;
  environmentList.value = response.data.environment;
  workerGroupList.value = response.data.workerGroup;
  

};

const userStore = useUserStore()
const dsSysList = userStore.dsSysList

const queryForm = reactive({
  bizName: '',
  pageNum: 1,
  pageSize: 10,
})

const leftQueryForm = reactive({
  ssysCd: '',
  tabName: '',
  pageNum: 1,
  pageSize: 10,
})

const bizList = ref([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const title = ref('')

const bizFormRef = ref(null)

const form = reactive({
  onum: null,
  bizName: '',
})

const rules = {
  bizName: [{ required: true, message: '请输入标签任务名称', trigger: 'blur' }],
}

const selectedRows = ref([])

const leftTableData = ref([])
const leftTotal = ref(0)
const leftSelected = ref([])

const rightTableData = ref([])
const rightSelected = ref([])

const warningGroupList = ref([])
const environmentList = ref([])
const workerGroupList = ref([])

const dsIds = ref([]);
const defindName = ref('')
const columns = reactive([
  { key: 0, label: '任务ID', prop: 'onum', visible: true },
  { key: 1, label: '任务名称', prop: 'bizName', visible: true },
  { key: 2, label: '状态', prop: 'status', visible: true },
  { key: 3, label: '调度ID', prop: 'schId', visible: true },
  { key: 4, label: '创建时间', prop: 'createTime', visible: true },
  { key: 5, label: '更新时间', prop: 'updateTime', visible: true },
  { key: 6, label: '创建人', prop: 'createBy', visible: true },
  { key: 7, label: '修改人', prop: 'updateBy', visible: true }
])
function handleSelectionChange(val) {
  selectedRows.value = val
  dsIds.value = selection.map((item) => item.dsIds);

}

function handleLeftSelect(rows) {
  leftSelected.value = rows
}
function handleRightSelect(rows) {
  rightSelected.value = rows
}

async function getList() {
  loading.value = true
  try {
    const res = await listTaskBizConfig(queryForm)
    bizList.value = res.rows || []
    total.value = res.total || 0
  } catch {
    ElMessage.error('获取列表失败，请重试')
  } finally {
    loading.value = false
  }
}

async function loadLeftTable() {
  try {
    const res = await getMetaDataList(leftQueryForm)
    leftTableData.value = res.data.rows || []
    leftTotal.value = res.data.total || 0
  } catch {
    ElMessage.error('加载左侧表数据失败')
  }
}

async function loadRightTable(onum) {
  try {
    const res = await getTaskBizRelaList(onum)
    rightTableData.value = res.data || []
  } catch {
    ElMessage.error('加载右侧表数据失败')
  }
}

function buildKey(row) {
  return `${row.ssysCd}||${row.mdlName}||${row.tabEngName}`
}

function moveToRight() {
  const existingKeys = new Set(rightTableData.value.map(buildKey))
  leftSelected.value.forEach(item => {
    if (!existingKeys.has(buildKey(item))) {
      let additem=item
      additem.onum=item.extractOnum
      rightTableData.value.push(item)
    }
  })
}

function moveToLeft() {
  const removeKeys = new Set(rightSelected.value.map(buildKey))
  rightTableData.value = rightTableData.value.filter(
    item => !removeKeys.has(buildKey(item))
  )
}

function resetQuery() {
  queryForm.bizName = ''
  queryForm.pageNum = 1
  getList()
}

function handleSearch() {
  queryForm.pageNum = 1
  getList()
}

function openAddDialog() {
  title.value = '新增标签任务'
  Object.assign(form, {
    onum: null,
    bizName: '',
  })
  rightTableData.value = []
  open.value = true
}

function openEditDialog(row) {
  if (!row) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  title.value = '编辑标签任务'
  Object.assign(form, row)
  loadRightTable(row.onum)
  open.value = true
}

function submitForm() {
  bizFormRef.value.validate(async valid => {
    if (!valid) return
    let tabonums=[]
    rightTableData.value.forEach(item=>{
      tabonums.push(item.onum)

    })
    console.log( rightTableData.value,"sss")
    const submitData = { ...form,tabOnumList:tabonums }
    try {
      if (title.value.includes('新增')) {
        await addTaskBizConfig(submitData)
        ElMessage.success('新增成功')
      } else {
        await updateTaskBizConfig(submitData)
        ElMessage.success('编辑成功')
      }
      open.value = false
      getList()
    } catch {
      ElMessage.error('操作失败，请重试')
    }
  })
}

function handleClose(done) {
  bizFormRef.value.resetFields()
  done()
}

function deleteSelected() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录删除')
    return
  }
  const onlineRows = selectedRows.value.filter(row => row.status === 'ONLINE')
  if (onlineRows.length > 0) {
    ElMessage.warning('请选择下线状态的记录进行删除')
    return
  }
  ElMessageBox.confirm(
    `确定删除选中的 ${selectedRows.value.length} 条记录吗？`,
    '提示',
    { type: 'warning' }
  )
    .then(async () => {
      try {
        for (const row of selectedRows.value) {
          await delTaskBizConfig(row.onum, row.dsIds)
        }
        ElMessage.success('删除成功')
        getList()
      } catch {
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => {})
}

// 操作按钮状态控制
const singleOne = computed(() => selectedRows.value.length !== 1)
const singleTwo = computed(() => selectedRows.value.length !== 1)
const single = computed(() => selectedRows.value.length !== 1)
const multiple = computed(() => selectedRows.value.length === 0)



function handleUp() {
  if (singleOne.value) return

  const selected = selectedRows.value[0]
  if (selected.status === 'ONLINE') {
    ElMessage.warning('该任务已是上线状态')
    return
  }

  ElMessageBox.confirm('确定要上线该任务吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await downOrUpmetatask(selected.onum, 'ONLINE')
        ElMessage.success('上线成功')
        getList()
      } catch (err) {
        ElMessage.error('上线失败，请重试')
      }
    })
    .catch(() => {})
}

function handleDown() {
  if (singleTwo.value) return

  const selected = selectedRows.value[0]
  if (selected.status === 'OFFLINE') {
    ElMessage.warning('该任务已是下线状态')
    return
  }

  ElMessageBox.confirm('确定要下线该任务吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await downOrUpmetatask(selected.onum, 'OFFLINE')
        ElMessage.success('下线成功')
        getList()
      } catch (err) {
        ElMessage.error('下线失败，请重试')
      }
    })
    .catch(() => {})
}
function handleDS() {
  if (singleTwo.value) return

  dsdialog.value.show(selectedRows.value[0].dsIds,selectedRows.value[0].onum); // Pass ids or any required data
  }

  function handleRun() {
  if (singleTwo.value) return;

  const selected = selectedRows.value[0];
  if (selected.status !== 'ONLINE') {
    ElMessage.warning('仅支持对已上线状态的任务进行运行操作');
    return;
  }
  rundialog.value.show(selected.dsIds);
}


function handleLog() {
  if (single.value) return
  defindName.value = selectedRows.value[0].bizName
  logdialog.value.open()
}

function handleDeleteSche() {
  if (singleTwo.value) return
  ElMessageBox.confirm('确定删除调度吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await dsmetataskSec(selectedRows.value[0].onum)
        ElMessage.success('删除调度成功')
        getList()
      } catch {
        ElMessage.error('删除调度失败')
      }
    })
    .catch(() => {})
}

function formatDateTime(val) {
  if (!val) return ''
  const date = new Date(val)
  const Y = date.getFullYear()
  const M = (date.getMonth() + 1).toString().padStart(2, '0')
  const D = date.getDate().toString().padStart(2, '0')
  const h = date.getHours().toString().padStart(2, '0')
  const m = date.getMinutes().toString().padStart(2, '0')
  const s = date.getSeconds().toString().padStart(2, '0')
  return `${Y}-${M}-${D} ${h}:${m}:${s}`
}

onMounted(() => {
  getList()
  getDeptTree()
  loadLeftTable()
})

// refs to dialog components
const rundialog = ref(null)
const dsdialog = ref(null)
const logdialog = ref(null)
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
.flex-col-center {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
