<template>
  <div class="system-busViolationLevel-add">
    <el-dialog v-model="isShowDialog" width="550px" :close-on-click-modal="false" :destroy-on-close="true">
      <template #header>
        <div v-drag="['.system-busViolationLevel-add .el-dialog', '.system-busViolationLevel-add .el-dialog__header']">添加违章等级</div>
      </template>
      <el-form ref="formRef" size="large" :model="formData" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="违章等级" prop="violationLevel">
              <el-input v-model="formData.violationLevel" placeholder="请输入违章等级" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="颜色" prop="color">
              <el-color-picker v-model="formData.color" show-alpha />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="风险等级" prop="riskType">
              <el-select v-model="formData.riskType" placeholder="请选择风险等级">
                <el-option v-for="dict in risxList" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" :offset="0" prop="dept">
            <el-form-item label="部门">
              <el-cascader
                :options="postListAll"
                v-model="formData.dept"
                clearable
                filterable
                :show-all-levels="false"
                placeholder="请选择部门"
                :props="{ expandTrigger: 'hover', checkStrictly: true, value: 'id', emitPath: false, multiple: true }"
                @change="changeDept"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="岗位" prop="postIdList">
              <el-select v-model="formData.postIdList" placeholder="请选择岗位" multiple :disabled="!formData.dept">
                <el-option
                  v-for="dict in formData.postWorkList"
                  :key="dict.postId"
                  :label="dict.deptName + '/' + dict.postName"
                  :value="dict.postId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="违章类型" prop="violationType">
              <el-select v-model="formData.violationType" placeholder="请选择违章类型" multiple>
                <el-option v-for="dict in tourTypeOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="onSubmit">确 定</el-button>
          <el-button @click="onCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { addViolationLevel } from '@/api/safety/violationLevel';
import { useUserStoreHook } from '@/store/modules/user';
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);

// Props
const props = defineProps<{
  tourTypeOptions: any[];
  risxList: any[];
  postListAll: any[];
}>();

const emit = defineEmits(['busViolationLevelList']);
const { proxy } = getCurrentInstance()!;

const formRef = ref<any>(null);
const menuRef = ref();

const isShowDialog = ref(false);
const loading = ref(false);

const formData = reactive({
  id: undefined,
  violationLevel: undefined,
  dept: undefined,
  color: undefined,
  violationType: undefined as any,
  wxOrPc: undefined,
  createBy: undefined,
  updateBy: undefined,
  createdAt: undefined,
  updatedAt: undefined,
  deletedAt: undefined,
  projectId: currentProject.value?.id,
  riskType: '',
  postWorkList: [] as any[],
  postIdList: [] as any[]
});

const rules = {
  id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
  violationLevel: [
    {
      required: true,
      validator: (_rule: any, value: string) => /^[A-Z]*$/g.test(value),
      message: '请输入A-Z的字母',
      trigger: 'change'
    }
  ],
  postIdList: [{ required: true, message: '岗位不能为空', trigger: 'blur' }]
};

// 打开弹窗
const openDialog = () => {
  resetForm();
  isShowDialog.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  isShowDialog.value = false;
};

// 取消操作
const onCancel = () => {
  closeDialog();
};

// 表单重置
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    violationLevel: undefined,
    color: undefined,
    violationType: undefined,
    dept: undefined,
    wxOrPc: undefined,
    createBy: undefined,
    updateBy: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    deletedAt: undefined,
    projectId: currentProject.value?.id,
    riskType: '',
    postWorkList: [] as any[],
    postIdList: []
  });
};

// 提交操作
const onSubmit = () => {
  if (!formRef.value) return;

  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;

      const param = JSON.parse(JSON.stringify(formData));
      if (param.violationType?.length) {
        param.violationType = param.violationType.join(',');
      }

      addViolationLevel(param)
        .then(() => {
          ElMessage.success('添加成功');
          closeDialog();
          emit('busViolationLevelList');
        })
        .finally(() => {
          loading.value = false;
        });
    }
  });
};

const changeDept = (val: any) => {
  formData.postWorkList = getPostVoListByIds(props.postListAll, val);
  formData.postIdList = [];
  console.log(formData.postWorkList, val);
};

function getPostVoListByIds(tree: any[], idList: (string | number)[]): any[] {
  const idSet = new Set(idList.map(String)); // 用于快速匹配 ID（统一为字符串比较）
  const result: any[] = [];

  function dfs(nodes: any[]) {
    for (const node of nodes) {
      if (idSet.has(String(node.id))) {
        result.push(...(node.postVoList || []));
      }

      if (node.children && node.children.length > 0) {
        dfs(node.children);
      }
    }
  }

  dfs(tree);
  return result;
}

defineExpose({
  openDialog,
  closeDialog
});
</script>

<style lang="scss">
.system-busViolationLevel-add {
  .el-col {
    margin-top: 20px;
  }
  .el-select .el-input__wrapper {
    width: 400px;
  }
  .el-select__tags {
    white-space: nowrap;
    text-overflow: ellipsis;
    flex-wrap: nowrap;
    overflow: hidden;
    margin-left: 1px;
  }
}
</style>
