<template>
  <div class="comp-content comp-task-pool" v-loading="loading" >
    <TreeCaseTable
      ref="loadcaseTableRef"
      :tableName="tableName"
      :showCheckbox="showCheckBox"
      :data="disposeTreeData(data)"
      :actionsWidth="95"
      @checkbox-change="checkboxChangeFun"
      :actionList="actionList"
      v-bind="$attrs"
    >
      <template #leftOptions>
        <div v-if="!readonly">
          <el-button :icon="Plus" @click="addRowFun(NODE_TYPE.CATEGORY)" :disabled="addNodeDisabled[NODE_TYPE.CATEGORY]" >{{ $t('工况库.分类') }}</el-button>
          <el-button :icon="Plus" @click="addRowFun(NODE_TYPE.TASK)" :disabled="addNodeDisabled[NODE_TYPE.TASK]">{{ $t('工况库.工况') }}</el-button>
          <el-button :icon="Plus" @click="addRowFun(NODE_TYPE.PERFORMANCE)" :disabled="addNodeDisabled[NODE_TYPE.PERFORMANCE]" >{{ $t('工况库.指标') }}</el-button>
        </div>
        <slot name="otherLeftOptions"></slot>
      </template>
      <!-- <template #eMemberList="{row}">
        {{ disposeMemberList(row,'eMemberList') }}
      </template> -->
      <!-- <template #pMemberList="{row}">
        {{ disposeMemberList(row,'pMemberList') }}
      </template> -->
      <!-- <template #tableActions="{ row }" v-if="hasOperationColumn" >
        <div class="gl-table-actions" v-if="!readonly">
          <el-link type="primary" @click="editRowFun(row)">编辑</el-link>
          <el-popconfirm
            title="是否删除"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="deleteTableRowFun(row)"
          >
            <template #reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
        </div>
        <slot name="otherTableActions" :row="row"></slot>
      </template> -->
    </TreeCaseTable>
    <!-- <Dialog v-model="modalVisible" destroy-on-close :diaTitle="modalTitle" show-footer :height=" formData.nodeType===NODE_TYPE.TASK? 700 : 'auto'">
      <template #default>
        <el-form ref="modalFormRef" :model="formData" label-width="auto">
          <template v-for="item in formItemList" :key="item.field">
            <el-form-item
              :label="item.title + ':'"
              :prop="item.field"
              :rules="
                (!item.formConfig?.excludeRequiredType ||
                  !item.formConfig?.excludeRequiredType.includes(formData.type)) &&
                  item.formConfig?.rules
                  ? item.formConfig.rules
                  : []
              "
            >
              <template v-if="item.formConfig?.type === 'textInput'">
                <el-input
                  v-model="formData[item.field]"
                  :placeholder="`${$t('工况库.请输入')}${item.title}`"
                ></el-input>
              </template>
              <template v-if="item.formConfig?.type === 'numberInput'">
                <el-input
                  v-model="formData[item.field]"
                  :placeholder="`${$t('工况库.请输入')}${item.title}`"
                  type="number"
                  :precision="2"
                  :step="0.1"
                  @focus="formData[`old_${item.field}`] = formData[item.field]"
                  @blur="(e:any)=>valueModelInput(e,formData, item)"
                ></el-input>
              </template>
              <template v-if="item.formConfig?.type === 'dateSelect'">
                <el-date-picker
                  v-model="formData[item.field]"
                  type="datetime"
                  :placeholder="`${$t('工况库.请选择')}${item.title}`"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="full-width"
                  :clearable="false"
                  :editable="false"
                  :disabled-date="(time:any)=>item.params?.disabledDate(time,formData,item)"
                />
              </template>
              <template v-if="item.formConfig?.type === 'select'">
                <el-select
                  v-model="formData[item.field]"
                  :placeholder="`${$t('工况库.请选择')}${item.title}`"
                  class="full-width"
                  @change="selectChange(formData, item)"
                  :disabled="isFunction(item.formConfig?.disabled) ? item.formConfig?.disabled(formData, operationType) : item.formConfig?.disabled"
                  :multiple="item.formConfig?.multiple"
                  :value-key="item.formConfig?.valueKey"
                >
                  <el-option
                    v-for="(item_2) in getSelectOptionsFun(item, formData)"
                    :key="item_2.value"
                    :label="item_2.label"
                    :value="item_2.value"
                  />
                </el-select>
              </template>
              <template v-if="item.formConfig?.type === 'upload_img'">
                <div class="upload">
                  <UploadImg v-model="formData[item.field]" />
                </div>
              </template>
              <template v-if="item.formConfig?.type === 'cascader'">
                <el-cascader
                  v-if="!item.params?.isLazyLoad"
                  clearable
                  class="full-width"
                  v-model="formData[item.field]"
                  :options="item.formConfig?.options"
                  :props="{
                    label: 'name',
                    value: 'folderName',
                    emitPath: false,
                  }"
                  filterable
                  :show-all-levels="false"
                >
                  <template #default="{ data }">
                    <el-icon v-if="data.dataType === 1"><Folder /></el-icon>
                    <el-icon v-else><Document /></el-icon>
                    <span class="cascader-label">{{ data.originalName }}</span>
                  </template>
                </el-cascader>
                <el-cascader
                  v-else
                  clearable
                  class="full-width"
                  v-model="formData[item.field]"
                  :props="item.params?.props"
                  filterable
                  :show-all-levels="false"
                >
                  <template #default="{ data }">
                    <el-icon v-if="data.dataType === 1"><Folder /></el-icon>
                    <el-icon v-else><Document /></el-icon>
                    <span class="cascader-label">{{ data.originalName }}</span>
                  </template>
                </el-cascader>
              </template>
            </el-form-item>
          </template>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="confirmForm">确定</el-button>
      </template>
    </Dialog> -->
    <nodeDetailDialog
      v-model="modalVisible"
      :modalTableNameList="props.modalTableNameList"
      :operationType="operationType"
      :nodeType="modalNodeType"
      :detail="modalDetail"
      :belongProject="belongProject"
      @confirm="onNodeDetailConfirmFun"
    />
    <!-- <userSelectTable
      v-if="showManageTable"
      v-model:memberVisible="showManageTable"
      :checkedUserList="selectManagerInfo.memberList"
      @update:updateMemberList="updateTaskUser"
    /> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import TreeCaseTable from '@/components/common/treeCaseTable/treeTable.vue';
import { getTagKeyMap, NODE_TYPE } from '@/utils/enum/node';
import { canAddChild } from '@/utils/node';
import nodeDetailDialog from './nodeDetailDialog.vue';
import { TASK_CALCULATE_STATUS, TASK_PROCESS_STATUS } from '@/utils/enum/task';
import { disposeTagKey } from '@/views/task/projectDetail/components/project';
import { ElMessage } from 'element-plus';
import { generateFakeId } from '@/utils/node';
import i18n from '@/utils/i18n';
import { TABLE_NAME } from '@/utils/enum/tableName';

const loadcaseTableRef = ref();

const formItemList = ref<any>([]);
const modalVisible = ref<boolean>(false);
const formData = ref<any>({});
const addNodeDisabled = ref<any>({});

interface Props {
  data: any;
  tableName: string;
  loading?: boolean;
  modalTableNameList?: string[];
  leftVisible?: boolean;
  leftButtonVisible?: boolean;
  hasOperationColumn?: boolean;
  readonly?: boolean;
  rememberProjectPhaseId?: string;
  projectInfo?: any;
  excludeOperation?: any;
  needPermission?: boolean; // 需要判断权限
  projectManagerIds?: any; // 项目管理员
  creatorId?: any; // 项目创建人
  projectUuid?: string; // 项目uuid
  phaseUuid?: string; // 阶段uuid
  exportBtnVisible?: boolean; // 阶段uuid
  showCheckBox?: boolean;
  belongProject?: boolean;
  specialActionList?: any;
}

const props = withDefaults(defineProps<Props>(), {
  data: [],
  tableName: '',
  loading: false,
  modalTableNameList: () => ([TABLE_NAME.TASK_POOL_CATEGORY, TABLE_NAME.TASK_POOL_TASK, TABLE_NAME.TASK_POOL_PERFORMANCE]),
  leftVisible: true,
  leftButtonVisible: true,
  hasOperationColumn: true,
  readonly: false,
  rememberProjectPhaseId: '',
  projectInfo: null,
  excludeOperation: [],
  needPermission: false,
  projectManagerIds: [],
  creatorId: '',
  projectUuid: '',
  phaseUuid: '',
  exportBtnVisible: false,
  showCheckBox: true,
  belongProject: false, // 属于项目还是工况库
  specialActionList: [],
});
const tagKeyMap = getTagKeyMap();
const disposeTreeData = (treeData: any[]) => {
  const recursionTreeData = (list:any[], pTagKeyList:any[] ) => {
    for (let index = 0; index < list.length; index++) {
      disposeTagKey(list[index], pTagKeyList, tagKeyMap);
      if (list[index].children && list[index].children.length > 0) {
        recursionTreeData(list[index].children, list[index].tagKeyList);
      }
    }
  };
  recursionTreeData(treeData, []);
  console.log('treeData', treeData);
  return treeData;
};

onMounted(() => {
  checkboxChangeFun();
});

// -----  nodeDetailDialog 相关 -----
enum OPERATION_TYPE {
  ADD = 'add',
  EDIT = 'edit',
}
const operationType = ref<OPERATION_TYPE>(OPERATION_TYPE.ADD);
const modalNodeType = ref<string>('');
const modalDetail = ref<any>(null);
const addRowFun = (nodeType?: any) => {
  operationType.value = OPERATION_TYPE.ADD;
  modalNodeType.value = nodeType;
  modalDetail.value = null;
  modalVisible.value = true;
};
const editRowFun = (row: any) => {
  operationType.value = OPERATION_TYPE.EDIT;
  modalNodeType.value = row.nodeType;
  modalDetail.value = { ...row, planTime: [row.beginTime, row.endTime], eMemberListArr: row.eMemberList, pMemberListArr: row.pMemberList };
  modalVisible.value = true;
};

// 关闭编辑新增弹窗
const cancelForm = () => {
  formItemList.value = [];
  formData.value = {};
  modalVisible.value = false;
};
const isSameNameLevel = (row: any, visibleData: any) => {
  console.log('visibleData', visibleData);
  const sameLevelList = visibleData.filter((item: any) => {
    return item.parentId === row.parentId && item.fakeId !== row.fakeId;
  });
  const isExistSameName = sameLevelList.some((item: any) => {
    return item.nodeName === row.nodeName;
  });
  return isExistSameName;
};

const getVxeRef = () => {
  return loadcaseTableRef.value?.TreeTableRef?.treeTableRef;
};
const onNodeDetailConfirmFun = (formData: any) => {
  const { visibleData } = getVxeRef()?.getTableData();
  const checkRowData = getVxeRef()?.getCheckboxRecords(true);
  console.log('formData', formData);
  if (operationType.value === 'add') {
    const addRow = {
      parentId: checkRowData[0]?.fakeId,
      fakeId: generateFakeId(),
      discipline: checkRowData[0]?.discipline,
      ...formData,
      depth: checkRowData[0]?.depth + 1,
      // eMemberList: getMemberListByIds(formData.eMemberList)
    };

    if (addRow.nodeType === NODE_TYPE.TASK) {
      addRow.exeStatus = TASK_PROCESS_STATUS.NO_STARTED;
      addRow.achieveStatus = TASK_CALCULATE_STATUS.NO_CALCULATE;
      addRow.eMemberList = addRow.eMemberListArr;
      addRow.pMemberList = addRow.pMemberListArr;
    }
    console.log('addRow', addRow);
    // 给新增节点赋值tagKeyMapList
    // const tagKeyList = disposeTagKey(addRow, checkRowData[0]?.tagKeyList || [], tagKeyMapList.value);
    // if (addRow?.nodeType === NodeTaskType.ROUNDS || addRow.type === TaskType.PERFORMANCE) {
    //   addRow.parentBeginTime = null;
    //   addRow.parentEndTime = null;
    // }
    // if (addRow.type === TaskType.PERFORMANCE) {
    //   addRow.beginTime = null;
    //   addRow.endTime = null;
    // }
    if (isSameNameLevel(addRow, visibleData)) {
      return ElMessage.warning('当前层级已有同名，请修改名称');
    }
    const insertPosition: any = -1;
    if (checkRowData[0]?.children?.length > 0) {
      // const lastBranchIndex = findLastIndex(checkRowData[0].children, (item: any) => {
      //   return item.type === addRow.type;
      // });
      // if (lastBranchIndex === -1 && addRow.type === TaskType.NODE) {
      //   insertPosition = null;
      // } else if (lastBranchIndex !== -1) {
      //   const insertPositionRow = checkRowData[0]?.children[lastBranchIndex];
      //   insertPosition = findNextRow(insertPositionRow, false) || -1;
      // }
    }
    // 新增顶层节点时要赋值顶层uuid
    if (checkRowData.length === 0) {
      // 有阶段就取阶段的uuid
      addRow.pid = props.phaseUuid || props.projectUuid;
    } else {
      addRow.pid = checkRowData[0].uuid;
    }
    nextTick(async () => {
      await getVxeRef()?.insertAt(addRow, insertPosition);
      await getVxeRef()?.setTreeExpand(checkRowData[0], true);
      // emits('updateCallback', 'add');
    });
  } else {
    if (isSameNameLevel(formData, visibleData)) {
      return ElMessage.warning('当前层级已有同名，请修改名称');
    }
    const row = visibleData.find((item: any) => item.fakeId === formData.fakeId);
    const rowInfo = {
      ...formData,
      eMemberList: formData.eMemberListArr,
      pMemberList: formData.pMemberListArr,
    };
    getVxeRef().setRow(row, rowInfo);
    const { fullData } = getVxeRef().getTableData();
    const updateNodeInTree = (list: any[]): boolean => {
      for (const item of list) {
        if (item.fakeId === rowInfo.fakeId) {
          Object.assign(item, rowInfo);
          return true;
        }
        if (item.children && item.children.length > 0) {
          const found = updateNodeInTree(item.children);
          if (found) return true;
        }
      }
      return false;
    };
    updateNodeInTree(fullData || []);
    // emits('updateCallback', 'update');
  }
  getVxeRef()?.clearCheckboxRow();
  cancelForm();
  checkboxChangeFun();

};// 保存form
const deleteTableRowFun = async(row: any) => {
  const delArr:any = [];
  const getAllChild = (arr:any[]) => {
    if (arr.length > 0) {
      arr.forEach((item:any) => {
        delArr.push(item);
        if (item.children && item.children.length > 0) {
          getAllChild(item.children);
        }
      });
    }
  };
  getAllChild([row]);
  await loadcaseTableRef.value?.removeFun(delArr);
  // nextTick(() => {
  //   emits('updateCallback', 'delete');
  // });
};
const actionList = computed(() => {
  if (!props.hasOperationColumn) {
    return [];
  }
  if (props.specialActionList.length > 0) {
    return props.specialActionList;
  }
  const baseActions = [
    {
      title: i18n?.global?.t('通用.编辑'),
      type: 'primary',
      click: (row: any) => {
        editRowFun(row);
      },
      hide: () => {
        return props.readonly;
      },
    },
    {
      title: i18n?.global?.t('通用.删除'),
      type: 'danger',
      needConfirm: true,
      confirmTip: i18n?.global?.t('通用.确认删除吗'),
      click: (row: any) => {
        deleteTableRowFun(row);
      },
      hide: () => {
        return props.readonly;
      },
    },
  ];
  return baseActions;
});
const checkboxChangeFun = () => {
  const checkRowData = loadcaseTableRef.value?.getCheckboxRecordsFun(true) || [];
  canAddChildFun(checkRowData, NODE_TYPE.CATEGORY);
  canAddChildFun(checkRowData, NODE_TYPE.TASK);
  canAddChildFun(checkRowData, NODE_TYPE.PERFORMANCE);
};
const canAddChildFun = (checkRowData: any, nodeType: string) => {
  if (!nodeType) {
    return true;
  }
  let canAdd = true;
  if (checkRowData.length === 0) {
    canAdd = canAddChild({ nodeType: NODE_TYPE.ROOT }, nodeType);
  } else if (checkRowData.length === 1) {
    canAdd = canAddChild(checkRowData[0], nodeType);
  } else {
    canAdd = false;
  }
  addNodeDisabled.value[nodeType] = !canAdd;
};

defineExpose({
  loadcaseTableRef,
});
</script>

<style lang="scss" scoped>
.comp-task-pool {
  width: 100%;
  height: calc(100% - 40px);
}
</style>
