<template>
  <el-drawer
    v-model="visible"
    resizable
    :close-on-click-modal="false"
    title="维度配置"
    @close="closeFun"
  >
    <el-tabs
      v-model="currentEditableTab"
      type="card"
      editable
      @edit="editTabsFun"
      @tab-change="tabChangeFun"
    >
      <el-tab-pane
        v-for="item in editableTabs"
        :key="item.name"
        :label="item.title"
        :name="item.name"
      >
        <div class="select-content">
          <div class="select-content-head">
            <el-space>
              <el-button type="primary" @click="addSelectLevelFun">添加层级</el-button>
              <el-button type="primary" @click="saveSelectLevelFun">保存</el-button>
            </el-space>
          </div>
          <div class="select-content-body">
            <el-form
              :ref="(el: any) => (selectLevelFormRef[item.name] = el)"
              :model="selectLevelFormData"
            >
              <el-form-item
                v-for="(item, index) in selectLevelFormData.selectLevelList"
                :key="item.id"
                :label="item.name"
                :prop="'selectLevelList.' + index + '.value'"
                :rules="{
                  required: true,
                  message: '请选择',
                  trigger: 'change',
                }"
              >
                <div class="select-level-box">
                  <el-select class="select-level" v-model="item.value" clearable>
                    <el-option
                      v-for="(item_1, index_1) in options"
                      :key="index_1"
                      v-bind="item_1"
                      :disabled="getOptionDisabledFun(item_1)"
                    ></el-option>
                  </el-select>
                  <el-icon
                    class="delete-icon"
                    @click="deleteSelectLevelFun(index)"
                  ><Delete/></el-icon>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <AddConfigurationDia
      v-model="addDiaVisible"
      @close="closeAddFun"
      @confirm="addConfigurationFun"
    />
  </el-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { saveTemplateWithHierarchiesApi, getTemplateWithHierarchiesApi, deleteTemplateWithHierarchiesApi, getAllTemplateApi } from '@/api/data/dimensionTemplate';
import { ElMessage, ElMessageBox } from 'element-plus';
import AddConfigurationDia from './addConfigurationDia.vue';
import type { TabPaneName } from 'element-plus';
import { NODE_TYPE } from '@/utils/enum/node';

interface SelectLevelItem {
  name: string;
  id: number;
  value?: any;
}

interface TabItem {
  title: string;
  name: string;
}

interface Props {
  modelValue: boolean;
  dimensionId: number;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  dimensionId: 1,
});

watch(() => props.modelValue, (val: boolean) => {
  visible.value = val;
  if (val) {
    getAllTemplateFun();
  }
});

const emit = defineEmits(['update:modelValue', 'confirm']);
const visible = ref<boolean>(false);
const currentEditableTab = ref<any>(null);
const selectLevelFormData = ref<any>({
  selectLevelList: [],
});
const editableTabs = ref<TabItem[]>([]);
const selectLevelFormRef = ref<any>({});
const addDiaVisible = ref<boolean>(false);
const treeKey = ref<any>(+new Date());
const options = ref<any>([
  {
    label: '项目',
    value: NODE_TYPE.PROJECT,
  },
  {
    label: '阶段',
    value: NODE_TYPE.PHASE,
  },
  {
    label: '机台',
    value: 'machine',
  },
  {
    label: '工位',
    value: 'workspace',
  },
  {
    label: '学科',
    value: 'discipline',
  },
  {
    label: '任务',
    value: NODE_TYPE.TASK,
  },
  {
    label: '指标',
    value: NODE_TYPE.PERFORMANCE,
  },
]);

const getAllTemplateFun = () => {
  getAllTemplateApi({}).then((res: any) => {
    if (res.code === 200) {
      editableTabs.value = res.data.allDimensionTemplates?.map((item: any) => {
        return {
          title: item.templateName,
          name: item.id,
        };
      });
      if (editableTabs.value.length > 0) {
        treeKey.value = +new Date();
      }
    }
  });
};

const tabChangeFun = () => {
  selectLevelFormData.value.selectLevelList = [];
  getTemplateWithHierarchiesFun();
};

const getTemplateWithHierarchiesFun = () => {
  getTemplateWithHierarchiesApi({ id: currentEditableTab.value }).then((res: any) => {
    if (res.code === 200) {
      selectLevelFormData.value.selectLevelList = res.data.dimensionTemplateHierarchies?.map(
        (item: any, index: number) => {
          return {
            id: item.id,
            name: index + 1 + '级',
            value: item.displayName,
          };
        }
      );
    }
  });
};

const getOptionDisabledFun = (item_1: any) => {
  return selectLevelFormData.value.selectLevelList.some((item: SelectLevelItem) => {
    return item.value === item_1.value;
  });
};

const addSelectLevelFun = () => {
  selectLevelFormData.value.selectLevelList.push({
    name: selectLevelFormData.value.selectLevelList.length + 1 + '级',
    id: new Date().getTime(),
    value: null,
  });
};

const deleteSelectLevelFun = (index: number) => {
  selectLevelFormData.value.selectLevelList.splice(index, 1);
  selectLevelFormData.value.selectLevelList.forEach((item: SelectLevelItem, index: number) => {
    item.name = index + 1 + '级';
  });
};

const saveSelectLevelFun = () => {
  selectLevelFormRef.value[currentEditableTab.value]?.validate((valid: any) => {
    if (valid) {
      saveTemplateWithHierarchiesApi({
        template: {
          id: currentEditableTab.value,
        },
        hierarchies: selectLevelFormData.value.selectLevelList.map((item: SelectLevelItem) => {
          return {
            displayName: item.value,
          };
        }),
      }).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('保存成功');
          emit('confirm');
        } else {
          ElMessage.error(res.message);
        }
        emit('update:modelValue', false);
      });
    }
  });
};

const editTabsFun = (targetName: TabPaneName | undefined, action: 'remove' | 'add') => {
  if (action === 'add') {
    addDiaVisible.value = true;
  } else if (action === 'remove') {
    ElMessageBox.confirm('是否确认删除该配置？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteTemplateWithHierarchiesApi({ id: Number(targetName) }).then((res: any) => {
        if (res.code === 200) {
          const tabs = editableTabs.value;
          let activeName = currentEditableTab.value;
          if (activeName === targetName) {
            tabs.forEach((tab, index) => {
              if (tab.name === targetName) {
                const nextTab = tabs[index + 1] || tabs[index - 1];
                if (nextTab) {
                  activeName = nextTab.name;
                }
              }
            });
          }
          currentEditableTab.value = activeName;
          editableTabs.value = tabs.filter((tab) => tab.name !== targetName);
          getTemplateWithHierarchiesFun();
          ElMessage.success('删除成功');
        } else {
          ElMessage.error(res.message);
        }
      });
    });
  }
};

const closeAddFun = () => {
  addDiaVisible.value = false;
};

const addConfigurationFun = (addFormData: any) => {
  saveTemplateWithHierarchiesApi({
    template: {
      templateName: addFormData.name,
    },
  }).then((res: any) => {
    if (res.code === 200) {
      const tabName = res.data.dimensionTemplate.id;
      editableTabs.value.push({
        title: addFormData.name,
        name: tabName,
      });
      currentEditableTab.value = tabName;
      selectLevelFormData.value.selectLevelList = [];
    } else {
      ElMessage.error(res.message);
    }
  });
};

const closeFun = () => {
  emit('update:modelValue', false);
};

watch(() => props.dimensionId, (val: number) => {
  currentEditableTab.value = val;
  tabChangeFun();
}, { immediate: true });
</script>

<style lang="scss" scoped>
.select-content {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  .select-content-head {
    width: 100%;
  }
  .select-content-body {
    width: 100%;
    flex: 1;
    padding: var(--padding-normal) 0;
    .select-level-box {
      width: 100%;
      display: flex;
      align-items: center;
      margin-bottom: var(--margin-normal);
      span {
        white-space: nowrap;
        margin-right: var(--margin-normal);
      }
      .select-level {
        width: 100%;
        margin-right: var(--margin-normal);
      }
      .delete-icon {
        color: var(--el-color-danger);
        cursor: pointer;
      }
    }
  }
}
</style>
