<template>
  <Dialog :title="title" v-model="show" :width="formType == 'create' ? '750px' : '1100px'">
    <div class="flex items-baseline">
      <el-form
        :model="form"
        ref="formRef"
        :disabled="['do', 'detail'].includes(formType)"
        :rules="rules"
        label-width="80px"
        class="flex-1"
      >
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入待办标题" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="内容" prop="content">
              <Editor
                v-model:modelValue="form.content"
                height="400px"
                :disabled="formType == 'do'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="优先级" prop="priority">
              <el-select v-model="form.priority" placeholder="选择优先级" filterable>
                <el-option
                  v-for="item in props.priorityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="完成状态" prop="completeStatus">
              <el-select v-model="form.completeStatus" placeholder="选择完成状态" filterable>
                <el-option
                  v-for="item in props.statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="截止日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="选择日期时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item label="执行人" prop="userList">
              <el-select
                v-model="form.userList"
                placeholder="选择执行人，可多选"
                multiple
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in employeeOptions"
                  :key="item.id"
                  :disabled="item.status == 1"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="8" :offset="0">
            <el-form-item prop="notifyType">
              <template #label>
                <el-tooltip
                  content="新增待办时会立刻发送消息通知执行人，若后续无需再次提醒，频率可选择“不提醒”"
                  placement="top"
                  effect="dark"
                >
                  <Icon icon="ep:info-filled" :size="12" />
                </el-tooltip>
                <span>提醒频率</span>
              </template>
              <el-select v-model="form.notifyType" placeholder="选择提醒频率">
                <el-option label="不提醒" value="1" />
                <el-option label="单次提醒" value="2" />
                <el-option label="循环提醒" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0" v-if="form.notifyType != 1">
            <el-form-item label="提醒时间" prop="remindTime" class="wait-form">
              <el-input
                v-if="form.notifyType == 2"
                v-model="form.notifyBeforeTime"
                placeholder="输入小时数"
                min="0"
                type="number"
              >
                <template #prepend>
                  <span>提前</span>
                </template>
                <template #append> 小时 </template>
              </el-input>
              <el-input
                v-else-if="form.notifyType == 3"
                v-model="form.intervalTime"
                placeholder="输入小时数"
                min="0"
                type="number"
              >
                <template #prepend>
                  <span>每</span>
                </template>
                <template #append> 小时 </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0" v-if="form.notifyType == 3">
            <el-form-item label="首次提醒" prop="firstNotifyTime">
              <el-time-picker
                v-model="form.firstNotifyTime"
                format="HH:mm"
                value-format="HH:mm"
                style="width: 100%"
                :picker-options="enableTimeRange"
                placeholder="选择时间点"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="formType != 'create'" class="w-350px ml-10px h-full">
        <div class="mb-10px" v-if="formType == 'do'">
          <Editor
            v-model:modelValue="form.followUpContent"
            height="150px"
            :toolbarConfig="toolbarConfig"
          />
          <el-button class="absolute" style="right: 20px; top: 195px" type="primary" @click="addDo">
            更新进度
          </el-button>
        </div>
        <div class="overflow-y-auto pl-15px" style="height: calc(100% - 50px)">
          <el-timeline class="ml-10px">
            <el-timeline-item
              v-for="item in followList"
              :key="item.followId"
              placement="bottom"
              :timestamp="formatDate(item.createTime, 'YYYY-MM-DD HH:mm:ss')"
              color="#30d1fc"
            >
              <div class="font-bold" style="font-size: 16px">{{ item.followUserName }}</div>
              <div v-dompurify-html="item.content"></div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>

    <template #footer v-if="formType != 'do'">
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button type="primary" :disabled="formLoading" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogWait">
import {
  createWait,
  updateWait,
  getWaitDetail,
  getFollowWaitPage,
  followWait
} from '@/api/okr/wait'
import { getEmployeeSimpleList } from '@/api/pers/employee'
import { formatDate } from '@/utils/formatTime'

const props = defineProps({
  priorityOptions: {
    type: Array,
    default: () => [
      { label: '高', value: '1' },
      { label: '中', value: '2' },
      { label: '低', value: '3' }
    ]
  },
  statusOptions: {
    type: Array,
    default: () => [
      { label: '未完成', value: '1', tagType: 'warning' },
      { label: '已关闭', value: '2', tagType: 'success' }
    ]
  }
})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const toolbarConfig = {
  toolbarKeys: []
}

const enableTimeRange = {
  selectableRange: '07:00 - 22:00'
}

const show = ref(false)
const title = ref('')
const formType = ref('create')

const form = ref({})
const formLoading = ref(false)
const rules = ref({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  endDate: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
  userList: [{ required: true, message: '请选择执行人', trigger: 'change' }]
})

const followList = ref([])

function open(type, id) {
  show.value = true
  title.value = { create: '新增待办', update: '修改待办', do: '更新待办进度', detail: '待办详情' }[
    type
  ]
  formType.value = type
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      // 表单数据
      getWaitDetail(id).then((info) => {
        form.value = {
          ...info,
          endDate: formatDate(info.endDate, 'YYYY-MM-DD'),
          userList: info.userIdList
        }
      })
      getFollowList(id)
    } finally {
      formLoading.value = false
    }
  }
  getOptions()
}

function getFollowList(id) {
  // 跟进数据
  getFollowWaitPage({
    workId: id
  }).then((data) => {
    followList.value = data
  })
}

function getOptions() {
  getEmployeeSimpleList().then((data) => {
    employeeOptions.value = data
  })
}

function resetForm() {
  form.value = {
    title: undefined,
    content: undefined,
    priority: '1',
    completeStatus: '1',
    endDate: undefined,
    userList: [],
    notifyType: '3',
    remindTime: 12,
    firstNotifyTime: '09:00'
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const formRef = ref()

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value === 'create') {
      await createWait(form.value)
      message.success(t('common.createSuccess'))
    } else {
      await updateWait(form.value)
      message.success(t('common.updateSuccess'))
    }
    show.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const employeeOptions = ref([])

function addDo() {
  followWait({
    workId: form.value.workId,
    content: form.value.followUpContent
  }).then(() => {
    message.success('跟进成功')
    getFollowList(form.value.workId)
  })
}
</script>

<style lang="scss" scoped>
.wait-form {
  :deep(.el-input-group__prepend) {
    padding: 0 10px;
  }
  :deep(.el-input-group__append) {
    padding: 0 10px;
  }
  :deep(.el-input__inner) {
    text-align: center;
  }
}
</style>
