<template>
  <view class="example">
    <uni-forms ref="formRef" :modelValue="formData" validateTrigger="submit" label-width="110px" label-position="top">
      <DynamicForm :form-data="formData" :schema="schema" :work-id="workId"></DynamicForm>
      <view style="margin-bottom: 10px;display: flex;">
        <custom-button width="100%" type="filled" color="#f2f3f5" @click="cancelProccessWork()" style="flex:1;margin-right: 5px;;"><text
            style="color: #606266;">取消</text></custom-button>
        <custom-button width="100%" type="filled" color="#007aff" @click="handlerProccessWork()"
          style="flex:1">确认</custom-button>
      </view>
    </uni-forms>
  </view>
</template>

<script lang="ts" setup>
import { getWorkDetail, submitWork } from '@/api/project-center/work';
import { WorkDetailResParams } from '@/types/work';
import { getDefaultFormState } from '@/utils/schema';
import DynamicForm from '@/components/dynamic-form/index.vue';
import { useEmitt } from '@/logics/mitt/useEmitt';

const formRef = ref()
const schema = ref({})
const formData = ref({})
const workId = ref()
const { emitter } = useEmitt()

const detail = reactive<{ work?: WorkDetailResParams }>({
  work: undefined
}) // 详情

const getDetail = async (id: string) => {
  workId.value = id;
  const workDetail = await getWorkDetail(id)
  schema.value = workDetail.form?.schema || {}
  formData.value = getDefaultFormState(schema.value, {}, schema.value, true)
  uni.setNavigationBarTitle({
    title: workDetail.form?.title!
  })
  detail.work = workDetail
}

const handlerProccessWork = async () => {
  const isValid = await formRef.value?.validate()
  if (!isValid) {
    return
  }
  await submitWork({ id: workId.value!, form_data: formData.value })
  uni.showToast({
      icon: 'success',
      title: '操作成功'
    })
  emitter.emit('get_project_list')
  emitter.emit('get_project_log')
  emitter.emit('get_task_log')
  emitter.emit('get_work_list')
  setTimeout(() => {
    emitter.emit('get_project_detail')
    emitter.emit('get_task_detail')
    if (detail.work?.params?.reverse_target) {
      emitter.emit(
        'switch_draft_page',
        detail.work?.params?.reverse_target?.draft
      )
    }
    emitter.emit('get_task_list')
    uni.navigateBack()
  }, 1500)
}

const cancelProccessWork = ()=>{
  return uni.navigateBack()
}
onLoad((option) => {
  getDetail(option?.id!)
});

onMounted(() => {
  // getDetail()
})
</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'apply-shared', //解除样式隔离
  }
}
</script>
<style scoped>
.example {
  padding: 15px;
  background-color: #fff;
}

:deep(.uni-forms-item__label) {
  width: auto !important;
}

:deep(.is-text-box) {
  display: none !important
}
</style>