<template>
  <div class="airportInfo 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="serviceDialogHide"
      >
        <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 dataSourceList"
                      :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 dataSourceList"
                    :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.protocolName"
              placeholder="请选择活动区域"
            >
              <el-option
                v-for="protocol in protocolList"
                :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 { Query } from '@/api/dataIntegration'
import {
  CommonTableColumn,
  CommonQueryResult,
  SelectOptionQueryResult,
} from '~/common'

interface DataSource {
  dataSourceID: string | number
  dataSourceName: string
}
interface Protocol {
  protocolID: string | number
  protocolName: string
}

// 表格
const tableColumns = ref<CommonTableColumn[]>([])
const tableData = ref<any[]>([])
const page = ref(0)
const noMore = ref(false)
const rowTitle = ref('')
onMounted(() => {
  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
    }
    tableColumns.value = columnSet.map(column => ({
      key: column.columnName,
      label: column.columnLabel,
      ...column,
    }))
    tableData.value.push(...listValues)
  } catch (error: any) {
    page.value--
    ElMessage.error(error.message)
  }
}
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: object,
  param: number
) => {
  switch (param) {
    case 1:
      break
    case 2:
      break
    case 3:
      break
    case 4:
      break
    default:
      break
  }
}

// 新增/删除服务-弹窗
const serviceDialogVisible = ref(false) // 弹窗开关
const serviceDialogType = ref('del') // 弹窗类型是否删除
const serviceDialogWidth = computed(() =>
  serviceDialogType.value === 'del' ? '600px' : '878px'
)
const delName = ref('') // 删除对象名
const msgTitle = '新增服务管理' // 新增弹窗-标题
const addServiceDialogShow = () => {
  getSelectOptions(DATACONTENT_ID.dataSourceOptions)
  serviceDialogType.value = 'add'
  serviceDialogVisible.value = true
}
const delSubmitHandler = () => {}
const delDialogHide = () => {}
const serviceDialogHide = () => {
  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 dataSourceList = ref<DataSource[]>([])
const serviceSubmitHandler = () => {
  serviceDialogHide()
}

// 新增数据来源-弹窗
const dataSourceDialogVisible = ref(false)
const addDataSourceDialogShow = () => {
  getSelectOptions(DATACONTENT_ID.protocolOptions)
  dataSourceDialogVisible.value = true
}
const dataSourceDialogHide = () => {
  sourceFormRef.value?.resetFields()
  dataSourceDialogVisible.value = false
}
// 新增数据来源-表单
const sourceFormRef = ref<FormInstance | null>(null)
const sourceForm = reactive({
  dataSourceName: '',
  protocolName: '',
  connectConfig: '',
})
const protocolList = ref<Protocol[]>([])
const dataSourceSubmitHandler = () => {
  dataSourceDialogHide()
}

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(item => ({
      [item.setlabel]: item.k,
      [item.setvalue]: item.v,
    }))
    switch (id) {
      case DATACONTENT_ID.dataSourceOptions:
        dataSourceList.value = options as DataSource[]
        break
      case DATACONTENT_ID.protocolOptions:
        protocolList.value = options as Protocol[]
        break
      default:
        break
    }
  } catch (error: any) {
    ElMessage.error(error.message)
  }
}
</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>
