<script lang="ts" setup>
import { Tag,Badge, Switch } from 'ant-design-vue'
import { onMounted, ref } from 'vue'

import HistoryModal from '../../exa/config/HistoryModal.vue'
import {columns, getSearchFormSchema} from './instant.data'
import CreateModal from './CreateModal.vue'
import UpdateModal from './UpdateModal.vue'

import { BasicTable, TableAction, useTable } from '@/components/Table'
import { getInstantCount, getInstantPage, updateInstant,deleteInstant } from '@/api/alert/run/instant'
import { getExaNow } from '@/api/alert/exa'
import { useI18n } from '@/hooks/web/useI18n'
import { router } from '@/router'
import { useMessage } from '@/hooks/web/useMessage'
import { IconEnum } from '@/enums/appEnum'
import { useModal } from '@/components/Modal'

defineOptions({ name: 'Instant' })
const { createMessage } = useMessage()
const { t } = useI18n()

const [registerHistoryModal, { openModal: openHistoryModal }] = useModal()
const [registerCreateModal, { openModal: openCreateModal }] = useModal()
const [registerUpdateModal, { openModal: openUpdateModal }] = useModal()
const searchSchema = ref<FormSchema[]>(getSearchFormSchema(true)) // 不显示算法

const [registerTable, { getForm, reload, getDataSource, updateTableDataRecord }] = useTable({
  title: '实例列表',
  api: getInstantPage,
  rowKey: 'mpId',
  immediate: true,
  columns,
  formConfig: {
    labelWidth: 80,
    schemas: searchSchema.value,
    showResetButton: false,
    actionColOptions: {
      span: 3,
      style: {
        marginLeft: '5px',
      },
    },

  },
  useSearchForm: true,
  showTableSetting: true,
  showIndexColumn: false,
  actionColumn: {
    width: 240,
    title: t('common.action'),
    dataIndex: 'action',
    fixed: 'right',
  },
})

function handleDetail(record) {
  console.log(record)
  router.push(`/run/instant/detail?mpId=${record.mpId}`)
}

async function updateStatus(record) {
  await updateInstant(record)
  createMessage.success(t('common.saveSuccessText'))
  console.log(record)
  reload()
}
const isShow = ref<boolean>(false)

function handleCreate() {
  openCreateModal(true, { isUpdate: false })
  isShow.value = true
}

function handleEdit(record: Recordable) {
  openUpdateModal(true, { record, isUpdate: true })
}
async function handleDelete(record: Recordable) {
  await deleteInstant(record.mpId)
  createMessage.success(t('common.delSuccessText'))
  reload()
}

const itemName = ref<string>()
const legendName = ref<string[]>()
function handleHistory(record: Recordable) {
  itemName.value = (JSON.parse(record.instantInfo)).model_state
  legendName.value = []
  legendName.value.push(`${record.mpName}-${itemName.value}`)
  openHistoryModal(true, { record })
}
interface countObj {
  normal: number
  outside: number
  failure: number
  update: number
  stop: number
}
const countData = ref<countObj>()
onMounted(async () => {
  countData.value = await getInstantCount()
  console.log(countData.value)
  const { setFieldsValue } = getForm()
  await setFieldsValue({ system: null })
  getNow()
})
async function getTableData(type) {
  const { getFieldsValue, setFieldsValue } = getForm()
  await setFieldsValue({ runningLog: null, running: null, isUpdate: null })
  if (type === 'normal') {
    await setFieldsValue({ runningLog: '运行正常' })
    console.log(getFieldsValue())
  }
  else if (type === 'outside') {
    await setFieldsValue({ runningLog: '模式外运行' })
  }
  else if (type === 'stop') {
    await setFieldsValue({ runningLog: '模型已停运' })
  }
  else if (type === 'failure') {
    await setFieldsValue({ running: 0 })
  }
  else if (type === 'isUpdate') {
    await setFieldsValue({ isUpdate: 1 })
  }
  else {
    await setFieldsValue({ runningLog: null, running: null, isUpdate: null })
  }
  reload()
}
async function getNow() {
  const params = getDataSource()
  params.forEach((item: any) => {
    const pointCode = (JSON.parse(item.instantInfo)).model_state
    // 对数组中的每个元素执行异步操作
    getExaNow(pointCode).then((result) => {
      updateTableDataRecord(item.id, Object.assign(item, { pointSte: result }))
    })
      .catch((error) => {
        console.error('Error:', error)
        updateTableDataRecord(item.id, Object.assign(item, { pointSte: pointCode }))
      })
  })
}

function handleWarnConfig(record: Recordable) {
  router.push(`/run/instant/warn/config?mpId=${record.mpId}`)
}
</script>

<template>
  <div>
    <BasicTable @register="registerTable">
      <template #form-advanceBefore>
        <a-button  type="primary" :pre-icon="IconEnum.ADD" @click="handleCreate">
          {{ t('action.create') }}
        </a-button>
      </template>

      <template #detail="{ record }">
        <a class="click-status" @click="handleDetail(record)">
          {{ record.mpName }}
        </a>

        <!-- <SlidersOutlined class="click-status" /> -->
      </template>
      <!-- 统计量点击跳转历史曲线 -->
      <template #history="{ record }">
        <a @click="handleHistory(record)">
          {{(JSON.parse(record.instantInfo)).model_state}}
        </a>
        <!-- <SlidersOutlined class="click-status" /> -->
      </template>
      <template #toolbar>
        <span class="runningStatus" @click="getTableData('all')">
          全部</span>
        <Badge
          :class="countData?.normal === 0 ? 'runningStatus' : 'runningStatus alarm'" color="green" text="正常运行"
          @click="getTableData('normal')"
        />
        <Badge
          :class="countData?.outside === 0 ? 'runningStatus' : 'runningStatus alarm'" color="#0B55A4" text="模式外运行"
          @click="getTableData('outside')"
        />
        <Badge
          :class="countData?.failure === 0 ? 'runningStatus' : 'runningStatus alarm'" color="red" text="运行失败"
          @click="getTableData('failure')"
        />
        <Badge
          :class="countData?.update === 0 ? 'runningStatus' : 'runningStatus alarm'" color="orange" text="版本更新"
          @click="getTableData('isUpdate')"
        />
        <Badge
          :class="countData?.stop === 0 ? 'runningStatus' : 'runningStatus alarm'" color="black" text="模型停运"
          @click="getTableData('stop')"
        />
      </template>
      <template #runStatus="{ record }">
        <Tag v-if="record.runningLog === '模式已停运'" color="default">模式已停运</Tag>
        <Tag v-else-if="record.running === '0'" color="red">运行失败</Tag>
        <Tag v-else-if="record.runningLog === '模式外运行'" color="blue">模式外运行</Tag>
        <Tag v-else-if="record.isUpdate === '1'" color="orange">版本更新</Tag>
        <Tag v-else-if="record.runningLog === '运行正常'" color="green">正常运行</Tag>
      </template>
<!--      <template #runStatus="{ record }">-->
<!--        <div v-if="record.runningLog === '模式已停运'">-->
<!--          <span style="color:black">模式已停运</span>-->
<!--        </div>-->
<!--        <div v-else-if="record.running === '0'">-->
<!--          <span style="color:red">运行失败</span>-->
<!--        </div>-->
<!--        <div v-else-if="record.runningLog === '模式外运行'">-->
<!--          <span style="color:#0B55A4">模式外运行</span>-->
<!--        </div>-->
<!--        <div v-else-if="record.isUpdate === '1'">-->
<!--          <span style="color:orange">版本更新</span>-->
<!--        </div>-->
<!--        <div v-else-if="record.runningLog === '运行正常'">-->
<!--          <span style="color:green">正常运行</span>-->
<!--        </div>-->
<!--      </template>-->
      <template #status="{ record }">
        <Switch
          v-model:checked="record.instantStatus" :checked-value="1" :un-checked-value="0" checked-children="开"
          un-checked-children="关" @change="updateStatus(record)"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              { icon: IconEnum.WARN, label: t('action.warnConfig'),  onClick: handleWarnConfig.bind(null, record) },

              { icon: IconEnum.EDIT, label: t('action.edit'),  onClick: handleEdit.bind(null, record) },
              {
                icon: IconEnum.DELETE,
                danger: true,
                label: t('action.delete'),
                popConfirm: {
                  title: t('common.delMessage'),
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <HistoryModal :item-name="itemName" :legend-name="legendName" @register="registerHistoryModal" />
    <CreateModal  @register="registerCreateModal" @success="reload" />
    <UpdateModal @register="registerUpdateModal" @success="reload" />
  </div>
</template>

<style lang="less" scoped>
:deep(.instant) {
  font-weight: bold;
  color: #0B55A4
}

:deep(.alarm .ant-badge-status-dot) {
  animation: flash 1s linear infinite;
}

@keyframes flash {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.runningStatus {
  cursor: pointer;
}
</style>
