<template>
  <div class="">
    <vModal
      v-model:visible="visibleWorkModal"
      :title="modalTitle"
      :mask="true"
      :ok-loading="loading"
      :mask-closable="false"
      @modal-handle-ok="modelHandleOk"
      @modal-handle-cancel="modelHandleCancel"
    >
      <div style="padding: 5px 15px">
        <a-form
          ref="workFormRef"
          :model="formData"
          :auto-label-width="true"
          label-align="right"
        >
          <DynamicForm
            :form-data="formData"
            :schema="schema"
            :work-id="workId"
          ></DynamicForm>
        </a-form>
      </div>
    </vModal>
  </div>
</template>

<script lang="ts" setup>
import { ref, h, reactive } from 'vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { Modal, Message } from '@arco-design/web-vue'
import vModal from '@/components/modal/index.vue'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { WorkDetailResParams } from '@/types/work'
import DynamicForm from '@/components/dynamicForm/index.vue'
import {
  getWorkDetail,
  getWorkUndoneCount,
  submitWork
} from '@/api/project/work'
import { getDefaultFormState } from '@/components/form'
import { useRouter } from 'vue-router'
import { ProjectDetailTabTitleList } from '@/enums/api'

import { useUndoneCount } from '@/hooks/useUndoneCount'

const loading = ref<boolean>(false)
const router = useRouter()
const schema = ref()
const formData = ref({})
const workFormRef = ref<FormInstance>()
const visibleWorkModal = ref(false) // 是否显示对话框
const modalTitle = ref() // 对话框标题
const workId = ref()
const { emitter } = useEmitt()
const detail = reactive<{ work?: WorkDetailResParams }>({
  work: undefined
}) // 客户详情
// const detail =  r
/**
 * 隐藏model 对话框，重置表单
 */
const modelHandleCancel = () => {
  return workFormRef.value!.resetFields() // 初始化表单值
}

/**
 * 显示级别modal
 * @param type modal 类型
 * @param item
 */
const showWorkModal = async (id: string) => {
  const workDetail = await getWorkDetail(id)
  detail.work = workDetail
  if (workDetail.status === 2 && workDetail.process_type === 1) {
    return
  }
  let type = 0 // 弹出确认框
  if (workDetail.process_type === 1 && workDetail.form) {
    type = 1
  }
  if (workDetail.process_type === 2) {
    type = 2
  }
  workId.value = workDetail.id
  if (type === 0) {
    showConfirmModal(workDetail)
  }
  if (type === 1) {
    modalTitle.value = workDetail.form?.title
    schema.value = workDetail.form?.schema || {}
    formData.value = getDefaultFormState(schema.value, {}, schema.value, true)
    visibleWorkModal.value = true
  }
  if (type === 2) {
    showToBeReadModal(workDetail)
  }
}

const showToBeReadModal = async (detail: WorkDetailResParams) => {
  const title = {
    setup() {
      return () => h('strong', detail.name)
    }
  }
  const ModalContent = {
    setup() {
      return () => h('div', { innerHTML: detail.desc })
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    mask: true,
    maskClosable: false,
    okText: '关闭',
    draggable: true,
    escToClose: true,
    width: 500,
    simple: true,
    hideCancel: true,
    onOk: async () => {
      if (detail.status === 2) {
        return
      }
      try {
        await submitWork({ id: detail.id! })
        Message.success('操作成功')
        setTimeout(() => {
          emitter.emit('get_project_list')
          emitter.emit('get_project_log')
          emitter.emit('get_task_log')
          emitter.emit('get_work_list')
          emitter.emit('get_project_detail', true)
          resetWorkUndoneCount()
        }, 1500)
      } catch (e) {
        loading.value = false
      }
    }
  })
}

/**
 * 当不需要提交表单，且为待办时，生成确认框。
 * @param detail
 */
const showConfirmModal = async (detail: WorkDetailResParams) => {
  const title = {
    setup() {
      return () => h('strong', detail.name)
    }
  }
  const ModalContent = {
    setup() {
      return () =>
        h('span', { style: 'margin: 10px;' }, [
          h('span', `确认`),
          h('strong', `${detail.name}`),
          h('span', ` 吗？`)
        ])
    }
  }
  Modal.warning({
    title: () => h(title),
    content: () => h(ModalContent),
    alignCenter: true,
    titleAlign: 'start',
    mask: true,
    maskClosable: false,
    draggable: true,
    escToClose: true,
    width: 380,
    simple: true,
    hideCancel: false,
    onOk: async () => {
      try {
        await submitWork({ id: detail.id! })
        emitter.emit('get_project_list')
        emitter.emit('get_project_log')
        emitter.emit('get_task_log')
        Message.success('操作成功')
        setTimeout(() => {
          emitter.emit('get_task_list')
          emitter.emit('get_task_detail')
          emitter.emit('get_project_detail', true)
          resetWorkUndoneCount()
        }, 1500)
      } catch (_e) {
        loading.value = false
      }
    }
  })
}

const resetWorkUndoneCount = async () => {
  const { undone_count: count } = await getWorkUndoneCount()
  const { setCount } = useUndoneCount()
  setCount(count)
}

/**
 * 点击确认按钮时，cb(false)时不会继续后续操作
 * @param cb 回调函数，
 */
const modelHandleOk = async (cb: (closed: boolean) => void) => {
  const isValid = await workFormRef.value?.validate()
  if (isValid) {
    return cb(false)
  }
  try {
    await submitWork({ id: workId.value!, form_data: formData.value })
    emitter.emit('get_project_list')
    emitter.emit('get_project_log')
    emitter.emit('get_task_log')
    setTimeout(() => {
      emitter.emit('get_project_detail', true)
      emitter.emit('get_task_detail')
      Message.success('操作成功')
      if (detail.work?.params?.reverse_target) {
        emitter.emit(
          'switch-draft-page',
          detail.work?.params?.reverse_target?.draft
        )
        router.push({
          name: ProjectDetailTabTitleList.find(item =>
            item.redirectId?.includes(
              detail.work?.params?.reverse_target?.target
            )
          )?.routerName,
          params: { prjId: detail.work?.prj_id }
        })
      }
      emitter.emit('get_task_list')
      resetWorkUndoneCount()
    }, 1500)
    return cb(true)
  } catch (e) {
    loading.value = false
    return cb(false)
  }
}

defineExpose({ showWorkModal }) // 暴露子组件的方法或者数据
</script>

<script lang="ts">
export default {
  name: 'ProjectWork'
}
</script>
