<template>
  <Dialog title="批量修改跟进人" v-model="show" width="400px">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="auto">
      <el-form-item label="修改线索数">
        {{ form.clueIdList.length }}
      </el-form-item>
      <el-form-item label="原跟进人" prop="originFollowUserId">
        <el-select v-model="form.originFollowUserId" placeholder="原跟进人" filterable>
          <el-option
            v-for="item in props.userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="新跟进人" prop="newFollowUserId">
        <el-select v-model="form.newFollowUserId" placeholder="新跟进人" filterable>
          <el-option
            v-for="item in props.userOptions"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span>
        <el-button @click="show = false">取 消</el-button>
        <el-button :disabled="formLoading" type="primary" @click="handleSave">保 存</el-button>
      </span>
    </template>
  </Dialog>
</template>

<script setup name="DialogBatchChangeFollow">
import { batchUpdateFollowUser } from '@/api/clue'

const message = useMessage() // 消息弹窗
const props = defineProps({
  userOptions: {
    type: Array
  }
})

const show = ref(false)
const form = ref({
  clueIdList: [],
  originFollowUserId: undefined,
  newFollowUserId: undefined
})

const rules = ref({
  originFollowUserId: { required: true, message: '原跟进人不可为空', trigger: 'change' }
  // newFollowUserId: { required: true, message: '新跟进人不可为空', trigger: 'change' }
})

function open(clueIdList) {
  resetForm(clueIdList)
  show.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

function resetForm(clueIdList) {
  form.value = {
    clueIdList,
    originFollowUserId: undefined,
    newFollowUserId: undefined
  }
}

const formLoading = ref(false)
const emit = defineEmits(['success'])
const formRef = ref()
async function handleSave() {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    await batchUpdateFollowUser(form.value)
    message.success('修改成功！')
    show.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (err) {
    console.log(err)
  } finally {
    formLoading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
