<script setup lang="ts" name="InstanceDetails">
import StatusTag from '@/views/workbench/StatusTag'
import ActivityTimeline from '@/views/workbench/activityTimeline/index.vue'
import FormParser from '@/components/FormParser'
import type { FormInfo } from '@/api/modules/flow/define'
import { buildRecords, type FlowActivity, records } from '@/api/modules/flow/activity'
import { showConfirmDialog, showFailToast, showSuccessToast } from 'vant'
import {
  cancel,
  type FlowInstance,
  getForm,
  getInstance,
  ProcessStatus
} from '@/api/modules/flow/instance'
import { useCachedViewStore } from '@/stores/modules/cachedView'

const router = useRouter()
const cachedViewStore = useCachedViewStore()
const route = router.currentRoute
const formInfo = ref<FormInfo>({
  formName: '',
  instanceId: '',
  taskId: '',
  flowDefine: {
    id: '',
    defineId: '',
    key: '',
    name: '',
    version: 0,
    groupId: '',
    icon: {
      name: '',
      color: '',
      bgColor: ''
    },
    process: {
      id: '',
      pid: '',
      name: '',
      type: 'start',
      next: undefined
    },
    form: {
      labelPosition: 'right',
      labelWidth: 100,
      gutter: 15,
      disabled: false,
      fields: [],
      rules: [],
      dataSource: []
    },
    deploymentId: '',
    description: '',
    suspend: 0
  },
  status: 0,
  startUserId: '',
  startTime: '',
  endTime: '',
  operations: {
    complete: false,
    refuse: false,
    back: false,
    transfer: false,
    delegate: false,
    addMulti: false,
    minusMulti: false
  }
})
const formData = ref<Recordable>({})
const formKey = ref(0)
const instanceLoading = ref(true)
const activities = ref<FlowActivity[]>([])
const timelineActivities = ref<FlowActivity[]>([])
const activityKey = ref(0)
const activitiesLoading = ref(true)
const instance = ref<FlowInstance>()

const onBack = () => {
  router.back()
}
const isCancel = () => {
  if (instance.value) {
    if (instance.value.status !== ProcessStatus.RUNNING) {
      return false
    }
    const { cancelDays, startTime } = instance.value
    if (cancelDays === 0) {
      return false
    }
    const start = new Date(startTime)
    start.setDate(start.getDate() + cancelDays)
    return start.getTime() > new Date().getTime()
  }
  return false
}
onMounted(() => {
  const { id } = route.value.query
  if (!id) {
    showFailToast('流程id不能为空')
    router.back()
  }
  getInstance(id as string).then((res) => {
    if (res.success) {
      instance.value = res.data
    }
  })
  getForm(id as string).then((res) => {
    if (res.success) {
      formInfo.value = res.data
      formKey.value = Date.now()
      instanceLoading.value = false
    }
  })
  // 获取流程活动
  activitiesLoading.value = true
  records(id as string).then((res) => {
    if (res.success) {
      activities.value = res.data
      timelineActivities.value = buildRecords(res.data)
      activityKey.value = Date.now()
      activitiesLoading.value = false
    }
  })
})
const handleAgain = () => {
  cachedViewStore.delCachedView('StartProcess')
  router.push({
    name: 'StartProcess',
    query: {
      id: formInfo.value.flowDefine.defineId,
      instanceId: formInfo.value.instanceId
    }
  })
}
const handleCancel = () => {
  showConfirmDialog({
    title: '提示',
    message: '您确认要撤回该流程吗？'
  }).then(() => {
    if (formInfo.value.instanceId) {
      cancel([formInfo.value.instanceId]).then((res) => {
        if (res.success) {
          showSuccessToast('撤回成功')
          router.back()
        }
      })
    }
  })
}
</script>

<template>
  <van-nav-bar placeholder clickable fixed left-arrow title="流程详情" @click-left="onBack" />
  <van-cell-group inset mt-2>
    <van-cell>
      <template #title>
        <van-skeleton title :row="1" :loading="instanceLoading">
          {{ formInfo.formName }}
          <StatusTag :status="formInfo.status" />
        </van-skeleton>
      </template>
      <template #label>
        <van-skeleton title avatar :row="2" :loading="instanceLoading">
          <div flex-items-center gap2>
            <UserName :username="formInfo.startUserId" />
            提交于 {{ formInfo.startTime }}
          </div>
        </van-skeleton>
      </template>
    </van-cell>
  </van-cell-group>
  <van-cell-group inset mt-2>
    <van-skeleton title :row="4" :loading="instanceLoading">
      <form-parser
        ref="formParserRef"
        :key="formKey"
        :form-data="formData"
        :form-conf="formInfo.flowDefine.form"
      />
    </van-skeleton>
  </van-cell-group>
  <van-cell-group inset mt-2 mb-15>
    <div class="flow-activity-timeline">
      <van-skeleton title :row="6" :loading="activitiesLoading">
        <ActivityTimeline :activities="timelineActivities"></ActivityTimeline>
      </van-skeleton>
    </div>
  </van-cell-group>
  <van-action-bar>
    <van-action-bar-icon icon="revoke" text="撤回" @click="handleCancel" v-show="isCancel()" />
    <van-action-bar-icon icon-class="i-ph-repeat" text="再次发起" @click="handleAgain" />
  </van-action-bar>
</template>

<style scoped lang="less">
.flow-activity-timeline {
  padding: 20px 20px;
}
</style>
