<template>
  <Dialog custom-show type="sm" title="任务下达" height="630px" @confirm="confirmRegister" @close="closeDialog">
    <div class="dialog-content">
      <div class="dialog-body">
        <el-form ref="taskFormRef" :model="form" :rules="rules">
          <el-form-item label="任务内容：" label-width="80px" prop="task_description">
            <el-input v-model="form.task_description" class="custom-input2" clearable placeholder="请输入相关任务描述" />
          </el-form-item>
          <el-form-item label="任务类型：" label-width="80px" prop="task_type">
            <el-select
              v-model="form.task_type"
              placeholder="选择任务类型"
              class="custom-select"
              size="large"
              popper-class="custom-select-popper"
              :teleported="false"
              clearable
              filterable
            >
              <el-option v-for="type in opt_task_type" :key="type.value" :label="type.text" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行单位：" label-width="80px" prop="unit_name">
            <el-select
              v-model="form.unit_name"
              placeholder="选择执行单位"
              class="custom-select"
              size="large"
              popper-class="custom-select-popper"
              :teleported="false"
              clearable
              filterable
              @change="handleUnitChange"
            >
              <el-option v-for="unit in filteredUnits" :key="unit.unitId" :label="unit.unit_name" :value="unit.unit_name" />
            </el-select>
          </el-form-item>
          <el-form-item label="执行人：" label-width="80px" prop="executor">
            <el-select
              v-model="form.executor"
              placeholder="请选择执行人"
              class="custom-select"
              size="large"
              popper-class="custom-select-popper"
              :teleported="false"
              clearable
              filterable
            >
              <el-option v-for="user in executorList" :key="user.userId" :label="user.nickName" :value="user.nickName" />
            </el-select>
          </el-form-item>
          <el-form-item label="登记人：" label-width="80px" prop="registrar">
            <el-input v-model="form.registrar" class="custom-input2" type="text" readonly />
          </el-form-item>
          <el-form-item label="联系电话：" label-width="80px" prop="contact_phone">
            <el-input v-model="form.contact_phone" class="custom-input2" placeholder="发布人的联系电话" />
          </el-form-item>
          <el-form-item label="完成时限：" label-width="80px" prop="expire_time">
            <el-date-picker
              v-model="form.expire_time"
              type="date"
              value-format="YYYY-MM-DD"
              class="common-date-picker"
              popper-class="common-date-popper"
              placeholder="选择完成时限"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="上传图片：" label-width="80px" prop="imgList">
            <FileUpload v-model="form.imgList" :file-type="['jpg', 'jpeg', 'png']" :limit="9" :file-size="5" class="upload-box" />
          </el-form-item>
          <el-form-item label="上传文件：" label-width="80px" prop="fileList">
            <FileUpload v-model="form.fileList" :file-type="['mp4', 'avi', 'wmv']" :limit="6" :file-size="1024" class="upload-box" />
          </el-form-item>
        </el-form>
      </div>
    </div>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { addTask, getUnits, getUser, getUserList } from '@/api/emergencyCommandMap/JointDuty';
const proxy = getCurrentInstance()?.proxy;

const opt_task_type = [
  { text: '事件处置', value: '0' },
  { text: '防范措施', value: '1' },
  { text: '险情处理', value: '2' },
  { text: '督办任务', value: '3' }
];
// 表单初始数据
const initFormData = {
  task_description: '',
  task_type: '',
  unit_name: '',
  registrar: '',
  executor: '',
  contact_phone: '',
  expire_time: '',
  event_code: '',
  imgList: [],
  fileList: []
};

const data = reactive({
  form: { ...initFormData },
  rules: {
    task_description: [{ required: true, message: '任务描述不能为空', trigger: 'blur' }],
    task_type: [{ required: true, message: '任务类型不能为空', trigger: 'blur' }],
    unit_name: [{ required: true, message: '执行单位不能为空', trigger: 'blur' }],
    registrar: [{ required: true, message: '登记人不能为空', trigger: 'blur' }],
    executor: [{ required: true, message: '执行人不能为空', trigger: 'blur' }],
    contact_phone: [{ required: true, message: '联系电话不能为空', trigger: 'blur' }],
    expire_time: [{ required: true, message: '完成时限不能为空', trigger: 'blur' }]
  }
});
const taskFormRef = ref();
const filteredUnits = ref([]);
const executorList = ref([]);
const { form, rules } = toRefs(data);
const props = defineProps<{
  eventId?: string;
}>();

// 获取当前登录用户信息
const fetchUser = async () => {
  try {
    const response = await getUser({});
    if (response.code === 200) {
      form.value.registrar = response.data.user.nickName;
      form.value.contact_phone = response.data.user.phonenumber;
    } else {
      console.error('获取用户信息失败:', response.msg);
    }
  } catch (error) {
    console.error('请求用户信息失败:', error);
  }
};

const fetchUnits = async () => {
  try {
    const response = await getUserList({});
    if (response.code === 200) {
      const units = new Map();
      response.rows.forEach((unit) => {
        if (!units.has(unit.deptName)) {
          units.set(unit.deptName, {
            unitId: unit.deptId,
            unit_name: unit.deptName
          });
        }
      });
      filteredUnits.value = Array.from(units.values());
    } else {
      console.error('获取单位数据失败:', response.msg);
    }
  } catch (error) {
    console.error('请求单位数据失败:', error);
  }
};

const fetchUsers = async (deptId) => {
  try {
    const response = await getUserList({ deptId });
    if (response.code === 200 && response.rows && Array.isArray(response.rows)) {
      executorList.value = response.rows.map((user) => ({
        userId: user.userId,
        nickName: user.nickName
      }));
    } else {
      console.error('获取用户列表失败:', response);
    }
  } catch (error) {
    console.error('请求用户列表失败:', error);
  }
};

const handleUnitChange = async (newUnitName) => {
  const selectedUnit = filteredUnits.value.find((unit) => unit.unit_name === newUnitName);
  if (selectedUnit) {
    await fetchUsers(selectedUnit.unitId);
  }
};

const emit = defineEmits(['update:show']);

const closeDialog = () => {
  emit('update:show', false);
};

const confirmRegister = () => {
  taskFormRef.value?.validate((valid) => {
    if (valid) {
      form.value.event_code = props.eventId;
      addTask(form.value).then((response) => {
        if (response.code === 200) {
          proxy?.$modal.msgSuccess('任务登记成功');
          closeDialog();
        } else {
          console.error('任务登记失败:', response.msg);
        }
      });
    }
  });
};

onMounted(() => {
  fetchUser();
  fetchUnits();
  fetchUsers();
});
</script>

<style lang="scss" scoped>
.dialog-content {
  :deep(.el-form) {
    .el-form-item__label {
      color: #fff !important;
      font-weight: bold !important;
      margin-right: 5px !important;
    }
  }
  .upload-box {
    :deep(.el-upload__tip) {
      color: #ffffff !important;
    }
  }
}
</style>
