<template>
  <el-dialog :model-value="visible" :title="data._id ? `编辑项目分类` : `新增项目分类`" :width="width" @close="close">
    <el-scrollbar ref="scrollbarRef" wrap-style="max-height: calc(85vh - 200px)">
      <el-form p-15 label-position="top">
        <el-form-item>
          <template #label>
            <span v-if="data._id">分类名称</span>
            <span v-else-if="data.parentId" font-14>在【{{ data.parentName }}】下方新增项目分类</span>
            <span v-else font-14>添加一级项目分类</span>
          </template>
          <el-input v-model="label" :maxlength="10" :placeholder="data.label || `请输入项目分类名称`" />
        </el-form-item>
        <el-form-item v-if="data.level && data.level === 1" label="关联科室">
          <div
            class="mt-10px p-10px flex items-center w-full border border-gray-200 min-h-32px cursor-pointer rounded hover:border-gray-300"
            @click="showDeptPicker()">
            <div v-if="selectDepts.length == 0" class="flex-shrink-0 text-gray-400 text-14px">请选择</div>
            <div class="flex-grow flex flex-wrap -mb-5px">
              <div
                class="flex items-center rounded border border-gray-200 px-10px py-6px mr-5px mb-5px group bg-gray-50"
                v-for="(dept, i) in selectDepts" :key="i" @click.stop="">
                <div color-normal class="text-13px">{{ dept.deptName }}</div>
                <el-icon class="ml-5px text-gray-500 hover:text-red-500" :size="14" @click.stop="removeDept(i)">
                  <CloseBold />
                </el-icon>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <template #footer>
      <div text-center>
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="save()">保存</el-button>
      </div>
    </template>
  </el-dialog>
  <dept-picker-modal ref="deptPickerRef" :mult="false" :value="deptIds" :visible="deptVisible" :width="deptPickerWidth"
    @change="deptChange" @close="closeDeptPicker" />
</template>
<script setup>
import { computed, nextTick, ref, watch } from 'vue';
import { ElMessage } from "element-plus";
import { addProjectCate, updateProjectCate } from "@/api/project-manage";
import useModal from "@/hooks/useModal";
import deptPickerModal from "@/components/dept-picker-modal/dept-picker-modal.vue";

const emits = defineEmits(['close', 'change'])
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  },
  width: {
    type: Number,
    default: 500
  }
})
const label = ref('');
const selectDepts = ref([]);
const deptPickerRef = ref();
const deptIds = computed(() => selectDepts.value.map((i) => i._id));
const { close: closeDeptPicker, show: showDeptPicker, visible: deptVisible, width: deptPickerWidth } = useModal(640);

function deptChange(val) {
  selectDepts.value = val;
  closeDeptPicker();
}

function removeDept(i) {
  selectDepts.value.splice(i, 1);
}

function close() {
  emits('close')
}

async function save() {
  if (typeof label.value !== "string" || label.value.trim() === "") {
    ElMessage.info("分类名称不能为空");
    return;
  }
  const fn = ['add', 'addChild'].includes(props.data._type) ? addProjectCate : updateProjectCate;
  const params = { label: label.value.trim() };
  if (props.data._type === 'addChild') {
    params.parentId = props.data.parentId;
  } else if (props.data._type === 'edit') {
    params.id = props.data._id;
  }
  if (props.data.level === 1) {
    params.deptId = deptIds.value[0] || ''
  }
  const { success, message } = await fn(params);
  if (success) {
    ElMessage.success(message);
    close();
    emits('change')
  } else {
    ElMessage.error(message);
  }

}

watch(() => props.visible, async n => {
  if (!n) return;
  label.value = props.data.label || '';
  await nextTick()
  if (typeof props.data.deptId === 'string' && props.data.deptId.trim() && props.data.level == 1 && deptPickerRef.value) {
    selectDepts.value = await deptPickerRef.value.getDeptsByIds([props.data.deptId])
  } else {
    selectDepts.value = [];
  }
})
</script>
<style lang="scss" scoped></style>
