<template>
  <div class="app-container">
    <div ref="topContainerRef">
      <TableSearch
        :queryParams="queryParams"
        :showSearch="showSearch"
        queryRef="queryRef"
        @refresh="resetQuery"
        @search="handleQuery"
      >
        <template #one>
          <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
            <el-form-item label="实例名称" prop="taskName">
              <el-input
                v-model="queryParams.taskName"
                clearable
                placeholder="请输入任务名称"
                style="width: 100%"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12" :sm="24" :xl="6" :xs="24" :xxl="6">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                :clearable="false"
                :disabledDate="
                  (time) => {
                    // 设置最大日期为今天
                    return time.getTime() > Date.now();
                  }
                "
                type="daterange"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </template>
      </TableSearch>
      <el-row :gutter="10" class="mb8">
        <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getInstList"
        ></right-toolbar>
      </el-row>
    </div>

    <div :style="containerHeight">
      <el-table
        v-loading="loading"
        height="100%"
        :data="instList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          align="center"
          label="id"
          prop="id"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="任务名称"
          prop="taskName"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="创建时间"
          prop="createTime"
          width="180"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="备注"
          prop="remark"
          show-overflow-tooltip
        />
        <el-table-column
          align="center"
          label="实例状态"
          prop="status"
          width="180"
        >
          <template #default="scope">
            <TableTags
              :options="[
                {
                  label: '已完成',
                  value: '0',
                  type: 'success',
                },
                {
                  label: '执行中',
                  value: '1',
                  type: 'warning',
                },
                {
                  label: '失败',
                  value: '2',
                  type: 'danger',
                },
              ]"
              :value="scope.row.status"
            ></TableTags>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="small-padding fixed-width"
          label="操作"
          width="180"
        >
          <template #default="scope">
            <el-button
              icon="Notebook"
              link
              type="primary"
              @click="handleOpenLogDialog(scope.row)"
              >日志
            </el-button>
            <el-button
              icon="DataLine"
              link
              type="primary"
              @click="handleOpenDashboard(scope.row)"
              >流程可视化
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="instTotal > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="instTotal"
        @pagination="getInstList"
      />
    </div>

    <!-- 添加或修改检测项日志对话框 -->
    <el-drawer
      v-model="open"
      :destroy-on-close="true"
      :size="580"
      :title="title"
      append-to-body
      modal-class="test-log"
      @close="cancel"
      @open="getLogList"
    >
      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in logList"
          :key="index.id"
          :hollow="true"
          :timestamp="item.createTime"
          placement="top"
          type="primary"
        >
          <el-descriptions
            :column="1"
            :title="item.taskName"
            border
            direction="vertical"
          >
            <el-descriptions-item label="节点类型">{{
              item.nodeType
            }}</el-descriptions-item>
            <el-descriptions-item label="消息">{{
              item.message
            }}</el-descriptions-item>
            <el-descriptions-item label="执行参数">
              <pre>{{ JSON.parse(item.paramsIn) }}</pre>
            </el-descriptions-item>
            <el-descriptions-item label="返回结果">
              <pre>{{ JSON.parse(item.paramsOut) }}</pre>
            </el-descriptions-item>
          </el-descriptions>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <!-- 添加或修改检测项日志对话框 -->
    <el-drawer
      v-model="openDashboard"
      :destroy-on-close="true"
      :size="580"
      :title="currentLog.taskName + '的流程'"
      append-to-body
      modal-class="rdashboad-log"
      @close="cancel"
    >
      <el-card
        v-for="item in taskRightList"
        shadow="hover"
        style="width: 100%; margin-bottom: 10px"
      >
        <div
          class="flex align-center"
          style="cursor: pointer"
          @click="handleFlowView(item)"
        >
          <div>{{ item.name }}</div>
          <div class="flex align-center" style="margin-left: 10px">
            <el-icon>
              <View />
            </el-icon>
          </div>
        </div>
      </el-card>
    </el-drawer>
  </div>
</template>

<script name="Log" setup>
import {
  addLog,
  delLog,
  getInst,
  getLog,
  listInst,
  updateLog,
} from "@/api/test/log";
import TableSearch from "@/components/TableSearch/index.vue";
import { View } from "@element-plus/icons-vue";
import TableTags from "@/components/TableTags/index.vue";
import { appendParamsToPath } from "@/utils/fn.js";
import { getTaskConfig } from "@/api/test/config.js";
import { onMounted } from "vue";

import { useContainerHeight } from "@/hooks/tableHeight";

const topContainerRef = ref();
const containerHeight = useContainerHeight(topContainerRef);

const { proxy } = getCurrentInstance();

const instList = ref([]);
const logList = ref([]);
const open = ref(false);
const openDashboard = ref(false);
const loading = ref(true);
const logLoading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const instTotal = ref(0);
const logTotal = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createTime: "",
    detectName: null,
    taskName: null,
  },
  logQueryParams: {
    pageNum: 1,
    pageSize: 100000,
    instId: null,
  },
  rules: {},
});

const { queryParams, form, rules, logQueryParams } = toRefs(data);
const startOn = computed(
  () => queryParams.value.createTime[0] + " 00:00:00" || undefined
);
const endOn = computed(
  () => queryParams.value.createTime[1] + " 23:59:59" || undefined
);

/** 查询任务实例列表 */
function getInstList() {
  loading.value = true;
  listInst(Object.assign(queryParams.value, { startOn, endOn })).then(
    (response) => {
      instList.value = response.rows;
      instTotal.value = response.total;
      loading.value = false;
    }
  );
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
  console.log(open.value)
}

// 表单重置
function reset() {
  logQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    instId: null,
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getInstList();
}

/** 重置按钮操作 */
function resetQuery() {
  console.log("11");
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加检测项日志";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLog(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改检测项日志";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["logRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLog(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getInstList();
        });
      } else {
        addLog(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getInstList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除检测项日志编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delLog(_ids);
    })
    .then(() => {
      getInstList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "test/log/export",
    {
      ...queryParams.value,
    },
    `log_${new Date().getTime()}.xlsx`
  );
}

/** 查询实例日志列表 */
function getLogList() {
  logLoading.value = true;
  getInst(logQueryParams.value).then((response) => {
    logList.value = response.rows;
    logTotal.value = response.total;
    logLoading.value = false;
  });
}

function handleOpenLogDialog(row) {
  console.log(row)
  console.log('open', open.value)
  logQueryParams.value.instId = row.id;
  open.value = true;
}

const currentLog = ref({});

const handleFlowView = (item) => {
  const params = {
    instId: currentLog.value.id,
    taskId: currentLog.value.taskId,
    itemId: item.id,
    name: item.name,
    state: "0",
    isLog: true,
  };

  const fullPath = appendParamsToPath("/flow", params);
  const p = window.open(fullPath, "_blank");
};

const handleOpenDashboard = (row) => {
  openDashboard.value = true;
  currentLog.value = row;
  getRightTaskList(row.taskId);
};

const taskRightList = ref([]);
//获取右侧编排数据
const getRightTaskList = (taskId) => {
  getTaskConfig({ taskId: taskId }).then((response) => {
    taskRightList.value =
      response.rows?.map((item) => {
        return {
          name: item.itemName,
          id: item.itemId,
        };
      }) || [];
  });
};

onMounted(() => {
  getInstList();
});
</script>
