<template>
  <div class="serivce-home scroll-y">
    <div class="wrap">
      <MinHeader :is-auth="true" :is-statuser="true" @addForm="addServiceDialogShow">
        <template #header>
          <div class="status flex-wrap">
            <div class="manageTitle">服务管理</div>
            <div class="status0"><span class="icon"></span>启动</div>
            <div class="status2"><span class="icon"></span>异常</div>
            <div class="status1"><span class="icon"></span>停止</div>
          </div>
        </template>
      </MinHeader>
      <div class="app-containers">
        <DataTable :is-Status="true" :table-header="tableColumns" :table-data="tableData" :table-btn-group="tableBtnGroup" btn-group-width="310px" :table-property="{ rowKey: 'ID' }" @btn-click="tableButtonClickHandler" />
      </div>
      <Dialog :width="serviceDialogWidth" :flag="serviceDialogVisible" :type="serviceDialogType" :del-name="delName" :msg-title="msgTitle" @del-remove="delSubmitHandler" @del-rest="delDialogHide" @submit-form="serviceSubmitHandler" @reset-form="addServiceDialogHide">
        <el-form ref="serviceFormRef" class="service-form" :model="serviceForm" :rules="serviceFormRules" label-position="right" label-width="90px" size="mini">
          <el-row :gutter="36" type="flex">
            <el-col :span="12">
              <el-form-item label="服务名称" prop="serviceName">
                <el-input v-model="serviceForm.serviceName" placeholder="请输入服务名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="前序输出编号" label-width="120px" prop="serviceOutputID">
                <el-input v-model="serviceForm.serviceOutputID" placeholder="请输入前序输出编号" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型" prop="serviceType">
                <el-select v-model="serviceForm.serviceType" clearable>
                  <el-option :value="1" label="管理前端" />
                  <el-option :value="2" label="管理后端" />
                  <el-option :value="3" label="业务前端" />
                  <el-option :value="4" label="业务后端" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="14px">
                <el-radio-group v-model="serviceForm.isAsynchronous">
                  <el-radio :label="1">同步</el-radio>
                  <el-radio :label="0">异步</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <div class="flex">
                <el-form-item label="数据来源" prop="dataSourceID">
                  <el-select v-model="serviceForm.dataSourceID" clearable>
                    <el-option v-for="dataSource in selectOptionMap[
                        queryTemplateIDMap.dataSourceName
                      ]" :key="dataSource.dataSourceID" :value="dataSource.dataSourceID" :label="dataSource.dataSourceName" />
                  </el-select>
                </el-form-item>
                <el-button type="primary" size="small" style="height: 28px; line-height: 0px" @click="addDataSourceDialogShow">新增</el-button>
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据来源对象" label-width="120px" prop="sourceObjectName">
                <el-input v-model="serviceForm.sourceObjectName" placeholder="请输入数据来源对象名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务描述" prop="serviceDescribe">
                <el-input v-model="serviceForm.serviceDescribe" placeholder="请输入描述" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生命周期ID键名" prop="lifeCycleCol" label-width="120px">
                <el-input v-model="serviceForm.lifeCycleCol" placeholder="请输入生命周期ID键名" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="取值规则" prop="computingMethod">
                <el-input v-model="serviceForm.computingMethod" placeholder="请输入取值规则" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="检测规则" prop="validationExpression">
                <el-input v-model="serviceForm.validationExpression" placeholder="请输入检测规则" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }" resize="none" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="启动时间" prop="startTime">
                <el-date-picker v-model="serviceForm.startTime" type="datetime" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" placeholder="请选择启动时间" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="停止时间" prop="stopTime">
                <el-date-picker v-model="serviceForm.stopTime" type="datetime" format="YYYY-MM-DD HH:mm" value-format="YYYY-MM-DD HH:mm" placeholder="请选择停止时间" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="失败重试次数" prop="retryCount" label-width="100px">
                <el-input v-model="serviceForm.retryCount" type="number" placeholder="请输入重试次数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="循环次数" prop="loopCount">
                <el-input v-model="serviceForm.loopCount" type="number" placeholder="请输入循环次数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="循环频率" prop="frequencyCount">
                <el-input v-model="serviceForm.frequencyCount" type="number" placeholder="请输入循环频率" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="循环频率单位" prop="frequencyUnit" label-width="100px">
                <el-select v-model="serviceForm.frequencyUnit" clearable>
                  <el-option label="天" :value="24 * 60 * 60 * 1000" />
                  <el-option label="小时" :value="60 * 60 * 1000" />
                  <el-option label="分钟" :value="60 * 1000" />
                  <el-option label="秒" :value="1000" />
                  <el-option label="毫秒" :value="1" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日志存储位置" label-width="100px" prop="logDataSourceID">
                <el-select v-model="serviceForm.logDataSourceID">
                  <el-option v-for="dataSource in selectOptionMap[
                      queryTemplateIDMap.dataSourceName
                    ]" :key="dataSource.dataSourceID" :value="dataSource.dataSourceID" :label="dataSource.dataSourceName" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="日志过滤条件" label-width="100px" prop="logList">
                <el-input v-model="serviceForm.logList" placeholder="请输入日志过滤条件" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </Dialog>
      <Dialog type="add" width="500px" :flag="dataSourceDialogVisible" msg-title="新增数据来源" @submit-form="dataSourceSubmitHandler" @reset-form="dataSourceDialogHide">
        <el-form ref="sourceFormRef" label-width="100px" :model="sourceForm">
          <el-form-item label="数据源名称">
            <el-input v-model="sourceForm.dataSourceName" size="small" />
          </el-form-item>
          <el-form-item label="协议名称">
            <el-select size="small" style="width: 100%" v-model="sourceForm.protocolID" placeholder="请选择活动区域">
              <el-option v-for="protocol in selectOptionMap[
                  queryTemplateIDMap.protocolName
                ]" :key="protocol.protocolID" :label="protocol.protocolName" :value="protocol.protocolID" />
            </el-select>
          </el-form-item>
          <el-form-item label="连接参数">
            <el-input size="small" type="textarea" rows="3" v-model="sourceForm.connectConfig" />
          </el-form-item>
        </el-form>
      </Dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
import DataTable from "@/components/tableTemp/index.vue";
import MinHeader from "@/components/minheader/index.vue";
import Dialog from "@/components/dialog/index.vue";
import { ElMessage, FormInstance } from "element-plus";
import {
  CommonTableColumn,
  CommonQueryResult,
  SelectOption,
  SelectOptionQueryResult,
} from "~/common";
import request from "@/utils/axiosReq";
import { Query, GeneralDataReception } from "@/api/webApi";

const router = useRouter();

const queryTemplateIDMap = reactive<{
  [x: string]: number;
}>({});
const selectOptionMap = reactive<{
  [id: number]: SelectOption[];
}>({});
const getSelectOptionOfColumn = (columns: CommonTableColumn[]) => {
  columns.forEach(async ({ columnName, listqueryTemplateID }) => {
    if (listqueryTemplateID !== null && !queryTemplateIDMap[columnName]) {
      queryTemplateIDMap[columnName] = listqueryTemplateID;
      if (!selectOptionMap[listqueryTemplateID]) {
        selectOptionMap[listqueryTemplateID] = [];
        selectOptionMap[listqueryTemplateID] = await getSelectOptions(
          listqueryTemplateID
        );
      }
    }
  });
};
const getSelectOptions = async (id: number) => {
  try {
    const {
      code,
      returnData: { listValues },
      message,
    }: SelectOptionQueryResult = await Query({
      id,
      dataContent: [],
    });
    if (Number(code) !== 0) {
      throw new Error(message ?? "失败");
    }
    const options = listValues.map(({ k, v, setlabel, setvalue }) => ({
      k,
      v,
      setlabel,
      setvalue,
      [setlabel]: k,
      [setvalue]: v,
    }));
    return options;
  } catch (error) {
    console.error(error);
    return [];
  }
};
onMounted(async () => {
  queryTemplateIDMap.protocolName = DATACONTENT_ID.protocolOptions;
  selectOptionMap[queryTemplateIDMap.protocolName] = await getSelectOptions(
    queryTemplateIDMap.protocolName
  );
});

// 表格
const tableColumns = ref<CommonTableColumn[]>([]);
const tableData = ref<any[]>([]);
const page = ref(0);
const noMore = ref(false);
const rowTitle = ref("");
onMounted(() => {
  getTableData();
});
const resetTable = () => {
  page.value = 0;
  noMore.value = false;
  tableData.value = [];
  getTableData();
};
const getTableData = async () => {
  try {
    const {
      code,
      returnData: { columnSet, listValues },
      message,
    }: CommonQueryResult = await Query({
      id: DATACONTENT_ID.sysServiceTable,
      dataContent: [],
      needPage: ++page.value,
    });
    if (Number(code) !== 0) {
      throw new Error(message || "失败");
    }
    if (listValues.length === 0) {
      page.value--;
      noMore.value = false;
    }
    const titleColumn = columnSet.find((column) => column.needShow === 1);
    if (titleColumn) {
      rowTitle.value = titleColumn.columnName;
    }
    getSelectOptionOfColumn(columnSet);
    tableColumns.value = columnSet;
    tableData.value.push(...listValues);
  } catch (error) {
    page.value--;
    console.error(error);
  }
};
const tableBtnGroup = [
  {
    name: "查看",
    className: "editBtn",
    param: 1,
  },
  {
    name: "编辑",
    className: "editBtn",
    param: 2,
  },
  {
    name: "停止",
    className: "editBtn",
    param: 3,
  },
  {
    name: "删除",
    className: "delBtn",
    param: 4,
  },
];
const tableButtonClickHandler = (rowIndex: number, row: any, param: number) => {
  switch (param) {
    case 1:
      router.push({
        path: "/systemSettings/serviceTopology",
        query: {
          serviceID: row["serviceID"],
          serviceName: row["serviceName"],
        },
      });
      break;
    case 2:
      router.push({
        path: "/systemSettings/serviceEdit",
        query: {
          serviceID: row["serviceID"],
          runState: row["runState"],
        },
      });
      break;
    case 3:
      changeServiceState(row["serviceID"], row["runState"]);
      break;
    case 4:
      delID = row["serviceID"];
      delDialogShow(row);
      break;
    default:
      break;
  }
};
const changeServiceState = async (serviceID: number, runState: string) => {
  const operate = runState === "运行" ? "stop" : "start";
  try {
    const {
      code,
      returnData: { listValues },
      message,
    } = await Query({
      id: DATACONTENT_ID.sysServiceNodeList,
      dataContent: [serviceID],
    });
    if (Number(code) !== 0) {
      throw new Error(message ?? "失败");
    }
    if (!listValues.length) {
      throw new Error("无部署机器");
    }
    Promise.all(
      listValues.map((node) => {
        request({
          url: `${node.serviceURL}${operate}`,
          method: "post",
          data: {
            serviceId: serviceID,
          },
        });
      })
    )
      .then((results: any) => {
        if (results.every((result) => Number(result.code) === 0)) {
          ElMessage.success("操作成功");
        } else {
          ElMessage.error("操作失败");
        }
      })
      .catch((error) => {
        throw new Error(error);
      });
  } catch (error) {
    console.error(error);
  }
};

// 新增/删除服务-弹窗
const serviceDialogVisible = ref(false); // 弹窗开关
const serviceDialogType = ref(""); // 弹窗类型是否删除
const serviceDialogWidth = computed(() =>
  serviceDialogType.value === "del" ? "600px" : "878px"
);
const delName = ref(""); // 删除对象名
let delID; // 删除对象ID
const msgTitle = ref(""); // 服务弹窗-标题
const delDialogShow = (row) => {
  serviceDialogType.value = "del";
  msgTitle.value = "删除服务";
  delName.value = row["serviceName"];
  serviceDialogVisible.value = true;
};
const delDialogHide = () => {
  serviceDialogVisible.value = false;
};
const delSubmitHandler = async () => {
  try {
    await deleteService();
    delDialogHide();
    resetTable();
  } catch (error) {
    console.error(error);
  }
};
const deleteService = async () => {
  try {
    const dataContent = {
      serviceID: delID,
      event: 3,
    };
    const { code, message } = await GeneralDataReception({
      serviceId: SERVICE_ID.sysServiceEdit,
      dataContent: JSON.stringify(dataContent),
    });
    if (Number(code) === 0) {
      ElMessage.success(message ?? "成功");
    } else {
      throw new Error(message ?? "失败");
    }
  } catch (error) {
    return Promise.reject(error);
  }
};
const addServiceDialogShow = () => {
  serviceDialogType.value = "add";
  msgTitle.value = "新增服务管理";
  serviceDialogVisible.value = true;
  console.log(queryTemplateIDMap, selectOptionMap);
};
const addServiceDialogHide = () => {
  serviceFormRef.value?.resetFields();
  serviceDialogVisible.value = false;
};
// 新增服务-表单
const serviceFormRef = ref<FormInstance | null>(null);
const serviceForm = reactive({
  serviceName: "",
  serviceOutputID: null,
  serviceType: null,
  dataSourceID: null,
  sourceObjectName: "",
  lifeCycleCol: "",
  isAsynchronous: 1,
  threads: null,
  datatype: null,
  computingMethod: "",
  validationExpression: "",
  startTime: null,
  stopTime: null,
  retryCount: null,
  loopCount: null,
  frequencyCount: null,
  frequencyUnit: null,
  serviceDescribe: "",
  logDataSourceID: null,
  logList: "",
});
const serviceFormRules = {
  serviceName: [
    {
      required: true,
      message: "请输入服务名称",
      trigger: ["change", "blur"],
    },
  ],
};
const serviceSubmitHandler = () => {
  serviceFormRef.value!.validate(async (valid) => {
    if (valid) {
      try {
        await createService();
        addServiceDialogHide();
        resetTable();
      } catch (error) {
        console.error(error);
      }
    }
  });
};
const createService = async () => {
  try {
    Object.keys(serviceForm).forEach((key) => {
      if (
        ![
          "sourceObjectName",
          "lifeCycleCol",
          "computingMethod",
          "validationExpression",
          "logList",
        ].includes(key) &&
        serviceForm[key] === ""
      ) {
        serviceForm[key] = null;
      }
    });
    const dataContent = { ...serviceForm, event: 1 };
    const { code, message } = await GeneralDataReception({
      serviceId: SERVICE_ID.sysServiceEdit,
      dataContent: JSON.stringify(dataContent),
    });
    if (Number(code) === 0) {
      ElMessage.success(message ?? "成功");
    } else {
      throw new Error(message ?? "失败");
    }
  } catch (error) {
    return Promise.reject(error);
  }
};

// 新增数据来源-弹窗
const dataSourceDialogVisible = ref(false);
const addDataSourceDialogShow = () => {
  dataSourceDialogVisible.value = true;
};
const dataSourceDialogHide = () => {
  sourceFormRef.value?.resetFields();
  dataSourceDialogVisible.value = false;
};
// 新增数据来源-表单
const sourceFormRef = ref<FormInstance | null>(null);
const sourceForm = reactive({
  dataSourceName: null,
  protocolID: null,
  connectConfig: null,
});
const dataSourceSubmitHandler = () => {
  dataSourceDialogHide();
};
</script>
<style lang="scss" scoped>
.app-containers {
  height: calc(100vh - 180px);
}

.icon {
  width: 14px;
  height: 14px;
  background: #2d67e3;
  border-radius: 2px;
  display: inline-block;
  vertical-align: middle;
  margin-right: 10px;
  position: relative;
  top: -2px;
}
.status0,
.status2 {
  margin-right: 28px;
  position: relative;
  top: 5px;
}
.status1 {
  position: relative;
  top: 5px;
  .icon {
    background-color: #afb4bf;
  }
}
.status2 {
  .icon {
    background-color: #eb2f3b;
  }
}

.service-form:deep {
  display: flex;
  flex-wrap: wrap;
  padding-left: 20px;
  > .el-row {
    flex-wrap: wrap;
    > .el-col .el-form-item {
      margin-bottom: 20px;
      .el-form-item__label {
        padding-right: 16px;
      }
      .el-input,
      .el-select {
        width: 100%;
      }
      .el-input__inner,
      .el-textarea__inner {
        padding-left: 8px;
      }
      .el-date-editor {
        .el-input__prefix,
        .el-input__suffix {
          right: 5px;
          left: unset;
          font-size: 16px;
          color: #101116;
          .el-input__suffix-inner {
            font-size: 16px;
          }
        }
        &.value-not-null:hover .el-input__prefix {
          display: none;
        }
      }
    }
  }
  label,
  span,
  button,
  input,
  optgroup,
  select,
  textarea {
    font-family: Helvetica, Microsoft YaHei;
    font-size: 14px;
    font-weight: 400;
  }
  label {
    color: #303133;
  }
  input {
    color: #101116;
    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      appearance: none;
      -webkit-appearance: none !important;
      &[type="number"] {
        appearance: textfield;
        -moz-appearance: textfield !important;
      }
    }
    .el-radio {
      font-weight: 400;
    }
  }
}
</style>
