<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="25%"
    class="x-dialog"
    :destroy-on-close="true"
  >
    <el-form
      class="dialog-data"
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="88px"
    >
      <el-form-item label="选择班组:" prop="deptId">
        <el-cascader
          v-model="form.deptId"
          :options="deptList"
          :props="cascaderProps"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handlerClose()" icon="CloseBold">取消</el-button>
        <el-button type="primary" icon="Select" @click="confirm()"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
const { proxy } = getCurrentInstance();
import { distributeyj } from "@/api/emergency-rescue";
const props = defineProps({
  title: {
    type: String,
    default: "",
  },
  deptList: {
    type: Array,
    default: () => [],
  },
  id: {
    type: Number,
  },
  modelValue: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:modelValue", "confirm"]);
const cascaderProps = {
  value: "deptId",
  label: "deptName",
};
const data = reactive({
  form: {
    deptId: [],
  },

  rules: {
    deptId: [{ required: true, message: "请选择办组人员", trigger: "blur" }],
  },
});
const { form, rules } = toRefs(data);

const visible = ref(props.modelValue);

const handlerClose = () => {
  visible.value = false;
  proxy.resetForm("formRef");
};

const confirm = () => {
  proxy.$refs["formRef"].validate(async (valid) => {
    if (valid) {
      const deptId = form.value.deptId[form.value.deptId.length - 1];
      await distributeyj({
        id: props.id,
        deptId: deptId,
      });
      proxy.$modal.msgSuccess(`${title}成功`);
      emit("confirm");
      handlerClose();
    }
  });
};

// 监听外部 modelValue 变化
watch(
  () => props.modelValue,
  (val) => {
    visible.value = val;
  }
);
watch(visible, (val) => {
  emit("update:modelValue", val);
});
</script>

<style scoped>
.dialog-data {
  width: 100%;
  display: flex;
  align-items: center;
  & > div {
    width: 100%;
  }
}
</style>
