<template>
  <div class="node-info-dialog">
    <Dialog
      v-model="nodeTableVisible"
      :loading="loadingInterface"
      diaTitle="阶段信息"
      :width="'50%'"
      :height="500"
      @close="closeNodeListFun"
      show-footer
    >
      <BaseTable ref="baseTableRef" tableName="NODE_LIST_LEVEL2" hidePagination showIndex :head="headData" :actionsWidth="tableActionsLength['2-2']">
        <template #leftOptions>
          <el-button
            icon="plus"
            @click="openNodeDialogFun('add')"
            type="primary"
          >
            {{ $t('项目列表.新增') }}
          </el-button>
        </template>
        <template #tableActions="{ row }">
          <div class="gl-table-actions">
            <el-link type="primary" @click="openNodeDialogFun('edit',row)">编辑</el-link>
            <el-popconfirm title="确认删除？" @confirm="disposeDeleteListFun(row)">
              <template #reference>
                <el-link type="danger">删除</el-link>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </BaseTable>
      <template #footer>
        <div>
          <el-button @click="closeNodeListFun">取消</el-button>
          <el-button @click="changeStepFun('pre')" v-if="props.dialogType === 'create'">上一步</el-button>
          <el-button @click="changeStepFun('next')" v-if="props.dialogType === 'create'">下一步</el-button>
          <el-button type="primary" @click="addOrEditNode">完成</el-button>
        </div>
      </template>
    </Dialog>
    <Dialog
      v-model="nodeFormVisible"
      :diaTitle="nodeFormDiaType === 'add'?'新增阶段':'编辑阶段'"
      :width="500"
      :height="500"
      show-footer
    >
      <TableForm ref="tableFormRef" tableName="NODE_LIST_LEVEL2" />
      <!-- <el-form :model="nodeForm" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="nodeForm.nodeName" />
        </el-form-item>
        <el-form-item label="计划开始时间">
          <el-date-picker
            :disabled-date=" (time: string) => disabledDateFun(time,'beginTime')"
            v-model="nodeForm.beginTime"
            type="datetime"
            placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="计划结束时间">
          <el-date-picker
            v-model="nodeForm.endTime"
            :disabled-date=" (time: string) => disabledDateFun(time,'endTime')"
            type="datetime"
            placeholder="选择日期"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="nodeForm.description" />
        </el-form-item>
      </el-form>-->
      <template #footer>
        <div>
          <el-button @click="nodeFormVisible = false">取消</el-button>
          <el-button type="primary" @click="addOrEditOneNodeFun">确认</el-button>
        </div>
      </template>
    </Dialog>
  </div>
</template>
<script lang='ts' setup>
import { addNodeApi, deleteNodeApi, editNodeApi, getChildrenNodeListApi } from '@/api/project/node';
import Dialog from '@/components/common/dialog/index.vue';
import BaseTable from '@/components/common/table/baseTable.vue';
import { getTagKeyMap, NODE_TYPE } from '@/utils/enum/node';
import { ElMessage } from 'element-plus';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { CommonStore } from '@/stores/common';
// import dayjs from 'dayjs';
import { getTagMapList } from '@/utils/task';
import { tableActionsLength } from '@/utils/common';
import TableForm from '@/components/common/table/tableForm.vue';

const props = defineProps<{
  showNodeInfoDialog: boolean;
  dialogType: string;
  nodeLevel1Uuid?: string;
  projectBeginTime?: string;
  projectEndTime?: string;

}>();
const emits = defineEmits(['update:showNodeInfoDialog', 'nextPageFun', 'prePageFun', 'completeFun']);
const nodeTableVisible = computed(() => {
  return props.showNodeInfoDialog;
});
const nodeTableList = ref<any[]>([]);
const nodeFormVisible = ref(false);

const loadingInterface = ref(false);

// const nodeForm = reactive({
//   id: '',
//   uuid: '',
//   nodeName: '',
//   beginTime: '',
//   endTime: '',
//   description: '',
//   nodeType: NODE_TYPE.PHASE,
//   type: '', // add 编辑 edit
//   pid: '',
// });

const addOrEditNode = async() => {
  loadingInterface.value = true;
  if (props.dialogType === 'create') {
    // emits('completeFun', 'nodePage');
    await addNodeDisposeFun(nodeTableList.value);
  } else {
    await editNodeDisposeFun();
  }
  if (deleteIdList.value.length > 0) {
    await deleteNodeFun();
  }
  loadingInterface.value = false;
  closeNodeListFun();
  emits('completeFun', 'phasePage');
};

const addNodeDisposeFun = async(addList:any[]) => {
  const tagKeyMap = getTagKeyMap();
  if (props.nodeLevel1Uuid) {
    addList = addList.map(item => {
      item.pid = props.nodeLevel1Uuid;
      return {
        ...item,
        [tagKeyMap.get(NODE_TYPE.PROJECT)]: props.nodeLevel1Uuid,
        [tagKeyMap.get(NODE_TYPE.PHASE)]: null,
      };
    });
  }
  const res:any = await addNodeApi({ addNodeList: addList, tagMap: getTagMapList() });
  if (res && res.code === 200) {
    ElMessage.success('新增节点成功');
  } else {
    ElMessage.error('新增节点失败');
  }
};
const editNodeDisposeFun = async() => {
  const editList = [];
  const addList = [];
  for (let index = 0; index < nodeTableList.value.length; index++) {
    if (nodeTableList.value[index].type === 'add') {
      addList.push(nodeTableList.value[index]);
    }
    else if (nodeTableList.value[index].type === 'edit') {
      editList.push(nodeTableList.value[index]);
    }
  };
  if (addList.length > 0) {
    await addNodeDisposeFun(addList);
  }
  if (editList.length > 0) {
    await editNodeFun(editList);
  }

};
const editNodeFun = async(editList:any[]) => {
  const res:any = await editNodeApi({ editNodeList: editList });
  if (res && res.code === 200) {
    ElMessage.success('编辑节点成功');
  } else {
    ElMessage.error('编辑节点失败');
  }
};
// NODE_LIST_LEVEL2
const headData = ref<any[]>([
  { title: '名称', key: 'nodeName', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
  { title: '计划开始时间', key: 'beginTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
  { title: '计划结束时间', key: 'endTime', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
  { title: '备注', key: 'description', isShow: true, inputMode: 'input', type: 1, inForm: false, required: true },
]);

const baseTableRef = ref<InstanceType<typeof BaseTable> | null>(null);

// 节点弹窗类型
const nodeFormDiaType = ref('add'); // add 编辑 edit

const openNodeDialogFun = (type: string, row?: any) => {
  nodeFormVisible.value = true;
  nodeFormDiaType.value = type;
  console.log('row', row);
  nextTick(() => {
    if (type === 'add') {
      tableFormRef.value.resetFun();
    // Object.assign(nodeForm, {
    //   nodeName: '',
    //   beginTime: '',
    //   endTime: '',
    //   description: '',
    // });
    } else if (type === 'edit') {
    // Object.assign(nodeForm, row);
      tableFormRef.value.setFormDataFun({ ...row });
    }
  });
};

const closeNodeFormFun = () => {
  nodeFormVisible.value = false;
};

const closeNodeListFun = () => {
  console.log('关闭弹窗');
  emits('update:showNodeInfoDialog', false);
};

const tableFormRef = ref();

const addOrEditOneNodeFun = async() => {
  if (await tableFormRef.value.validateFun()) {
    const fromData = tableFormRef.value.getFormDataFun();
    if (validSameName(fromData)) return;
    if (nodeFormDiaType.value === 'add') {
      fromData.type = 'add';
      fromData.nodeType = NODE_TYPE.PHASE;
      fromData.uuid = 'fakeUuid' + uuidv4();
      if (props.nodeLevel1Uuid) {
        fromData.pid = props.nodeLevel1Uuid;
      }
      console.log('新增阶段', fromData);
      nodeTableList.value.push({ ...fromData });
    } else {
      if (fromData.type !== 'add') {
        fromData.type = 'edit';
      }
      nodeTableList.value = nodeTableList.value.map(item => {
        if (item.id === fromData.id) {
          return { ...fromData };
        }
        return item;
      });
      console.log('编辑阶段', fromData, nodeTableList.value);
    }
    baseTableRef.value?.setDataFun(nodeTableList.value);
    closeNodeFormFun();
  }
};

const validSameName = (fromData: { nodeName: string; id: any; }) => {
  if (nodeTableList.value.some(item => {
    return item.nodeName === fromData.nodeName && item.id !== fromData.id;
  })) {
    ElMessage.error('阶段名称有重复！');
    return true;
  }
  return false;
};

const deleteIdList = ref<Array<string>>([]);

const disposeDeleteListFun = ({ type, uuid }: { type: string; uuid: string; }) => {
  if (type !== 'add') {
    deleteIdList.value.push(uuid);
  }
  nodeTableList.value = nodeTableList.value.filter(item => item.uuid !== uuid);
  baseTableRef.value?.setDataFun(nodeTableList.value);
};

const deleteNodeFun = async() => {
  // 调用删除接口
  const res:any = await deleteNodeApi({ deleteNodeIdList: deleteIdList.value });
  if (res && res.code === 200) {
    ElMessage.success('删除节点成功');
    nodeListApi();
  } else {
    ElMessage.error(res.msg || '删除节点失败');
  }
};

const changeStepFun = (step:string) => {
  if (step === 'next') {
    emits('nextPageFun', 'nodePage');
  }
  if (step === 'pre') {
    emits('prePageFun', 'nodePage');
  }
};

const nodeListApi = async() => {
  nodeTableList.value = [];
  const res:any = await getChildrenNodeListApi({ current: 1, size: 999, nodeId: props.nodeLevel1Uuid, nodeType: NODE_TYPE.PHASE });
  if (res && res.code === 200) {
    nodeTableList.value = res.data;
  } else {
    nodeTableList.value = [];
  }
  baseTableRef.value?.setDataFun(nodeTableList.value);

};

// const disabledDateFun = (time:string, type:string) => {
//   if (type === 'beginTime') {
//     return dayjs(time).isBefore(dayjs(props.projectBeginTime));
//   } else {
//     return dayjs(props.projectEndTime).isBefore(dayjs(time));
//   }
// };

const commonStore = CommonStore();

const getDictPhaseList = () => {
  const nodeLevel2ListDic: any = commonStore.getDictData('NODE_LEVEL2_ENUM');
  nodeTableList.value = nodeLevel2ListDic.A.map((item: { label: string; }) => {
    return {
      id: 'fakeUuid' + uuidv4(),
      nodeName: item.label,
      beginTime: props.projectBeginTime,
      endTime: props.projectEndTime,
      nodeType: NODE_TYPE.PHASE,
      uuid: 'fakeUuid' + uuidv4(),
      description: '',
    };
  });
};

watch(() => props.showNodeInfoDialog, (newVal) => {
  if (newVal) {
    nextTick(() => {
      if (props.dialogType === 'create') {
        if (nodeTableList.value.length === 0) {
          console.log('props', props);
          getDictPhaseList();
          // console.log('nodeLevel2ListDic', nodeLevel2ListDic.A);
          baseTableRef.value?.setDataFun(nodeTableList.value);
        }
        console.log('baseTableRef', baseTableRef, nodeTableList.value);
      }
    });
  }
},
{
  immediate: true,
});
onMounted(() => {
  if (props.nodeLevel1Uuid) {
    nodeListApi();
  }
  // if(props.dialogType === 'edit') {

  // }
});
defineExpose({
  nodeTableList,
  addNodeDisposeFun,
});
</script>
<style lang="scss" scoped>
</style>
