<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <el-tabs type="card" v-model="activeTab">
          <!-- 数据源标签页 -->
          <el-tab-pane label="数据源" name="dataSource">
            <div class="head-container">
              <el-input
                v-model="dbResoursName"
                placeholder="请输入数据源"
                clearable
                prefix-icon="search"
                style="margin-bottom: 20px"
              />
            </div>
            <div class="head-container">
              <el-tree
                :data="dbResourceOptions"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                node-key="id"
                default-expand-all
                highlight-current
                @node-click="handleNodeClick"
              >
              <template #default="{ node, data }">
              <span class="custom-tree-node">
        <i :class="getIconClass(data)"></i>

        <span>{{ data.name }}</span>
      </span>
    </template>
              </el-tree>
            </div>
          </el-tab-pane>
          <el-tab-pane label="报表" name="report">
            <div>敬请期待。。。。。</div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="任务名称" prop="metataskName">
            <el-input
              v-model="queryParams.metataskName"
              placeholder="请输入任务名称"
              clearable
              style="width: 240px"
          
            />
          </el-form-item>
          <el-form-item label="任务类型" prop="metataskType">
            <el-select
              v-model="queryParams.metataskType"
              placeholder="任务类型"
              clearable
              style="width: 240px"
            >
              <el-option
                v-for="dict in meta_task_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              style="width: 240px"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期" 
              end-placeholder="结束日期"
            ></el-date-picker>
          </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-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="plus"
              @click="handleAdd"
              v-hasPermi="['meta:metatask:add']"
              >新建任务</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="edit"
              
              :disabled="singleOne"
              @click="handleUpdate"
              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="handleDelete"
              v-hasPermi="['meta:metatask:delete']"
              >删除</el-button
            >
          </el-col>

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

        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="任务名称"
            align="center"
            key="metataskName"
            prop="metataskName"
            v-if="columns[1].visible"
            :show-overflow-tooltip="true"
          
          />
          <el-table-column
            label="任务类型"
            align="center"
            key="metataskType"
            prop="metataskType"
            v-if="columns[2].visible"
            :show-overflow-tooltip="true"
            width="180"
          >
            <template #default="scope">
              <dict-tag
                :options="meta_task_type"
                :value="scope.row.metataskType"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="所属数据源"
            align="center"
            key="dbRCode"
            prop="dbRCode"
            v-if="columns[3].visible"
            :show-overflow-tooltip="true"
          >    
            <template #default="scope">
              {{ getListNameById(scope.row.dbRCode) }}
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            align="center"
            key="status"
            prop="status"
            v-if="columns[4].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="调度时间"
            align="center"
            prop="dsTime"
            v-if="columns[5].visible"
            width="100"
          >
             <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            v-if="columns[6].visible"
            width="100"
          >
             <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="更新时间"
            align="center"
            prop="updateTime"
            v-if="columns[7].visible"
            width="100"
          >
             <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="描述"
            align="center"
            key="remark"
            prop="remark"
            v-if="columns[8].visible"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="创建人"
            align="center"
            key="createBy"
            prop="createBy"
            v-if="columns[9].visible"
            :show-overflow-tooltip="true"
            width="70"
          />
          <el-table-column
            label="修改人"
            align="center"
            key="updateBy"
            prop="updateBy"
            v-if="columns[10].visible"
            :show-overflow-tooltip="true"
            width="70"
          />

          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
        
          <template #default="{ row }">
  <el-button 
    link 
    type="primary" 
    :disabled="row.status === 'ONLINE'" 
    icon="Edit" 
    @click="handleUpdate(row)" 
    v-hasPermi="['meta:metatask:edit']"
  >
    修改
  </el-button>

  <el-button 
    link 
    type="primary" 
    icon="Delete" 
    :disabled="row.status === 'ONLINE'" 
    @click="handleDelete(row)" 
    v-hasPermi="['meta:metatask:delete']"
  >
    删除
  </el-button>

  <el-dropdown 
    link 
    @command="(command) => handleCommand(command, row)" 
  >
    <el-button link type="primary" icon="d-arrow-right">
      更多
    </el-button>
    <template #dropdown>

    <el-dropdown-menu>
      <el-dropdown-item 
        command="handleUp"
        icon="circle-check"
        :disabled="row.status === 'ONLINE'" 
        v-hasPermi="['meta:metatask:up']"
      >
        上线
      </el-dropdown-item>
      
      <el-dropdown-item 
        command="handleDown"
        icon="circle-check"
        :disabled="row.status === 'OFFLINE'" 
        v-hasPermi="['meta:metatask:down']"
      >
        下线
      </el-dropdown-item>

      <el-dropdown-item 
        command="handleDS"
        icon="circle-check"
        :disabled="row.status === 'OFFLINE'" 
        v-hasPermi="['meta:metatask:ds']"
      >
        调度
      </el-dropdown-item>

      <el-dropdown-item 
        command="handleRun"
        icon="circle-check"
        :disabled="row.status === 'OFFLINE'" 
        v-hasPermi="['meta:metatask:run']"
      >
        运行
      </el-dropdown-item>

      <el-dropdown-item 
        command="handleLog"
        icon="circle-check"
        v-hasPermi="['meta:metatask:log']"
      >
        日志
      </el-dropdown-item>
    </el-dropdown-menu>
    </template>
  </el-dropdown>
</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-col>
    </el-row>

    <el-dialog v-model="open" width="600px" append-to-body>
      <template #title>
      <el-cascader
        v-model="form.metataskType"
        :options="metataskTypeOptions"
        :props="{ expandTrigger: 'hover' }"
        @change="handleChangeType"
      ></el-cascader>
    </template>
      <el-form ref="taskForm" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="metataskName">
              <el-input
                v-model="form.metataskName"
                placeholder="请输入任务名称"
                maxlength="30"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="采集方式" prop="acquisitionType">
              <el-select
                v-model="form.acquisitionType"
                placeholder="请选择采集方式"
                maxlength="30"
                style="width: 80%"
              >
                <el-option
                  v-for="dict in meta_task_acq"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据源" prop="dbRCode">
              <el-select
                v-model="form.dbRCode"
                placeholder="请选择数据源"
                maxlength="30"
                disabled
                style="width: 80%"
              >
                <el-option
                  v-for="dict in dbResourceOldList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库" prop="dbCode">
              <el-input
                v-model="form.dbCode"
                placeholder="请输入数据库"
                maxlength="30"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="模式列表" prop="dbSName">
              <el-input
                v-model="form.dbSName"
                placeholder="请输入模式列表"
                maxlength="30"
                style="width: 80%"
              />
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input
                v-model="form.remark"
                type="textarea"
                placeholder="请输入内容"
                style="width: 80%"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
    </el-dialog>
    <run-dialog ref="rundialog"
     :warningGroupList="warningGroupList"
     :environmentList="environmentList"
     :workerGroupList="workerGroupList"
     :processDefinitionCode="dsIds"
     />
     <ds-dialog ref="dsdialog"
     :warningGroupList="warningGroupList"
     :environmentList="environmentList"
     :workerGroupList="workerGroupList"
     :processDefinitionCode="dsIds"
     />
     <log-dialog ref="logdialog"
     :defindName="defindName"
  
     />
  </div>
</template>
<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}
.custom-tree-node i {
  margin-right: 8px; /* 图标与文本之间的间距 */
}
</style>
<script setup name="MetaTask">
import { ref, reactive, onMounted, watch } from "vue";
import { listmetatask, getmetatask, delmetatask, addmetatask, updatemetatask, downOrUpmetatask, datasourcetree, datasourceall } from "@/api/meta/metatask";
import runDialog from "./runDialog";
import dsDialog from "./dsDialog";
import logDialog from "./logsDialog";
const { proxy } = getCurrentInstance();
const { meta_task_type, meta_task_acq, meta_task_status,meta_task_at } = proxy.useDict("meta_task_type", "meta_task_acq", "meta_task_status", "meta_task_at");

// Component setup
const activeTab = ref("dataSource");
const loading = ref(true);
const ids = ref([]);
const dsIds = ref([]);
const single = ref(true);
const singleOne = ref(true); // Online, Edit, Delete
const singleTwo = ref(true); // Offline, Logs, Scheduling
const multiple = ref(true);
const showSearch = ref(true);
const total = ref(0);
const userList = ref(null);
const title = ref("");
const warningGroupList = ref(undefined);
const environmentList = ref(undefined);
const workerGroupList = ref(undefined);
const defindName = ref("");
const dbResourceOptions = ref(undefined);
const dbRCodeList = ref(undefined);
const dbSCodeList = ref([
  { value: "scheam", label: "scheam" },
  { value: "scheam2", label: "scheam2" }
]);
const metataskTypeOptions = ref([
  { value: "0", label: "元数据采集", children: [{ value: "00", label: "表字段" }, { value: "01", label: "存储过程" }] },
  { value: "1", label: "元数据加工" }
]);
const open = ref(false);
const dbResoursName = ref(undefined);
const clickNode = ref(undefined);
const dateRange = ref([]);
const postOptions = ref([]);

const data = reactive({
  form: { metataskId: undefined,
  metataskType: "00",
  metataskName: undefined,
  dbRName: undefined,
  dbCode: undefined,
  dbName: undefined,
  dbRCode: undefined,
  dbSName: undefined,
  dbSCode: undefined,
  remark: undefined,
  acquisitionType: "0",
  dsId: undefined,
  acTarget: "0"},
  queryParams: {
  pageNum: 1,
  pageSize: 10,
  dbRcode: undefined,
  dsId: undefined,
  metataskName: undefined,
  metataskType: undefined,
  dbRCode: undefined
  },
  rules: {
    metataskName: [
    { required: true, message: "任务名称不能为空", trigger: "blur" },
    { min: 2, max: 20, message: "任务名称长度必须介于 2 和 20 之间", trigger: "blur" }
  ],
  dbSCode: [{ required: true, message: "模式列表不能为空", trigger: "blur" }],
  acquisitionType: [{ required: true, message: "采集方式不能为空", trigger: "blur" }],
  acTarget: [{ required: true, message: "采集目标不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);
const defaultProps = {
  children: "children",
  label: "name"
};
const selectRowData = ref({});
const dbResourceOldList = ref([]);

const columns = [
  { key: 0, label: `任务ID`, visible: true },
  { key: 1, label: `任务名称`, visible: true },
  { key: 2, label: `任务类型`, visible: true },
  { key: 3, label: `所属数据源`, visible: true },
  { key: 4, label: `状态`, visible: true },
  { key: 5, label: `调度时间`, visible: true },
  { key: 6, label: `创建时间`, visible: true },
  { key: 7, label: `更新时间`, visible: true },
  { key: 8, label: `描述`, visible: true },
  { key: 9, label: `创建人`, visible: true },
  { key: 10, label: `修改人`, visible: true }
];
const chooseRows = ref([]);


// Watcher for dynamic changes
watch(dbResoursName, (val) => {

    proxy.$refs["tree"].filter(val);


});
// watch(filterText, (val) => {
//   treeRef.value!.filter(val)
// })
// On mounted
onMounted(() => {
  getList();
  getDeptTree();
});

// Methods
const handleChangeType = (value) => {
  form.value.metataskType = value[value.length - 1];
  if (form.value.metataskType === '00') form.value.acTarget = '0';
  else if (form.value.metataskType === '01') form.value.acTarget = '1';
  console.log(form.value.metataskType ,"改变metataskType ")
};

const getList = async () => {
  loading.value = true;
  const response = await listmetatask(proxy.addDateRange(queryParams.value, dateRange.value));
  userList.value = response.rows;
  total.value = response.total;
  loading.value = false;
};

const getDeptTree = async () => {
  const response = await datasourceall();
  warningGroupList.value = response.data.alertGroups;
  environmentList.value = response.data.environment;
  workerGroupList.value = response.data.workerGroup;
  
  const treeResponse = await datasourcetree();
  if (treeResponse.success && treeResponse.rows.length > 0) {
    dbResourceOldList.value = treeResponse.rows;
    const childrenList = dbResourceOldList.value.map(element => ({ ...element, parentId: "100" }));
    dbResourceOptions.value = [{ id: 100, name: "数据源", parentId: 0, children: childrenList }];
  }
};

const getListNameById =  (id) => {
  const item = dbResourceOldList.value.find(item => item.id == id);
  return item!=null ? item.name : '';

};

const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

const handleNodeClick = (data) => {
  clickNode.value = data;
  queryParams.value.dbRCode = data.id;
  handleQuery();
};

const cancel = () => {
  open.value = false;
  reset();
};

const reset = () => {
  form.value= {
    metataskId: undefined,
    metataskType: "00",
    metataskName: undefined,
    dbRName: undefined,
    dbCode: undefined,
    dbName: undefined,
    dbRCode: clickNode.value?.id,
    dbSName: undefined,
    dbSCode: undefined,
    remark: undefined,
    acquisitionType: "0",
    dsId: undefined,
    acTarget: "0"
  };

  proxy.resetForm("taskForm");
};

const getIconClass = (data) => {
  let icon=""
  if (data.parentId == '0') icon= 'Monitor'; 
  if (data.parentId == '100') icon= 'Coin'; 
  console.log(icon)
  return icon; 
};

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

const resetQuery = () => {
  dateRange.value = [];

  proxy.resetForm("queryForm");

  queryParams.value.dbRCode = clickNode.value?.id;
  proxy.tree.setCurrentKey(null);
  handleQuery();
};

const handleSelectionChange = (selection) => {
  selectRowData.value = selection[0];
  chooseRows.value = selection;
  ids.value = selection.map((item) => item.metataskId);
  dsIds.value = selection.map((item) => item.dsIds);
  singleOne.value = selection.length !== 1 || selectRowData.value.status === "ONLINE";
  singleTwo.value = selection.length !== 1 || selectRowData.value.status === "OFFLINE";
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

const handleCommand = (command, row) => {
  switch (command) {
    case "handleUp":
      handleUp(row);
      break;
    case "handleDown":
      handleDown(row);
      break;
    case "handleDS":
      handleDSRow(row);
      break;
    case "handleRun":
      handleRunRow(row);
      break;
    case "handleLog":
      handleLogRow(row);
      break;
    default:
      break;
  }
};

const handleAdd = () => {
  if (!clickNode.value) {
    $message.warning("请选择数据源节点!");
    return;
  }
  reset();
  open.value = true;
};

const handleUpdate = async (row) => {
  reset();
  const metataskId = row.metataskId || ids.value;
  const response = await getmetatask(metataskId);
  form.value = response.data;
  open.value = true;

 
};

const handleUp = async (row) => {
  const metataskIds = String(row.metataskId || ids.value);
  await proxy.$modal.confirm(`是否确认上线任务编号为"${metataskIds}"的数据项？`);
  await downOrUpmetatask(metataskIds, "ONLINE");
  getList();
  proxy.$modal.msgSuccess("上线成功");
};

const handleDown = async (row) => {
  const metataskIds = String(row.metataskId || ids.value);
  await proxy.$modal.confirm(`是否确认下线任务编号为"${metataskIds}"的数据项？`);
  await downOrUpmetatask(metataskIds, "OFFLINE");
  getList();
  proxy.$modal.msgSuccess("下线成功");
};
const dsdialog = ref(null);
const rundialog = ref(null);
const logdialog = ref(null);
const handleDS = (row) => {
  if (dsdialog.value) {

    dsdialog.value.show(dsIds.value); // Pass ids or any required data
      }
};

const handleRun = (row) => {
  rundialog.value.show(dsIds.value);
};

const handleLog = (row) => {
  defindName.value = `${selectRowData.value.metataskName}-${selectRowData.value.dsTypes === "0" ? "表字段采集" : "存储过程采集"}`;

  if (logdialog.value) {
    logdialog.value.show(defindName.value);
      }

};


const handleDSRow  = (row) => {
  if (dsdialog.value) {

    dsdialog.value.show(row.dsIds); // Pass ids or any required data
      }
};

const handleRunRow  = (row) => {
  rundialog.value.show(row.dsIds);
};

const handleLogRow = (row) => {
  defindName.value = `${row.metataskName}-${row.dsTypes === "0" ? "表字段采集" : "存储过程采集"}`;

  if (logdialog.value) {
    logdialog.value.show(defindName.value);
      }

};

const submitForm = async () => {

    proxy.$refs["taskForm"].validate(async (valid) => {
    if (valid) {
      const submitForm = { ...form.value };
      submitForm.dbCode = clickNode.value.type;
      submitForm.dbRName = clickNode.value.name;
      if (submitForm.metataskId !== undefined) {

        await updatemetatask(submitForm);
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      } else {
        await addmetatask(submitForm);
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      }
    }
  });
};

const handleDelete = async (row) => {
  let isDelete = true;
  if (row.status === 'ONLINE') {
    proxy.$modal.msgWarning("请选择下线数据进行删除");
    isDelete = false;
  }
  if (chooseRows.value.length > 0) {
    chooseRows.value.forEach(b => {
      if (b.status === 'ONLINE') {
        proxy.$modal.msgWarning("请选择下线数据进行删除");
        isDelete = false;
      }
    });
  }
  if (isDelete) {
    const metataskIds = row.metataskId || ids.value;
    const dsidsVo = row.dsIds || dsIds.value;
    await proxy.$modal.confirm(`是否确认删除任务编号为"${metataskIds}"的数据项？`);
    await delmetatask(metataskIds, dsidsVo);
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }
};
</script>

