<template>
  <div class="node-detail">
    <Dialog
      v-model="visible"
      show-footer
      show-cancel-button
      show-confirm-button
      :diaTitle="localDiaTitle"
      @show="onShowFun"
      :confirm-closable="false"
      :width="(localDetail?.nodeType === NODE_TYPE.TASK)?800:400"
    >
      <template #default>
        <TableForm
          v-if="visible"
          :colNum="(localDetail?.nodeType === NODE_TYPE.TASK)?2:1"
          ref="tableFormRef"
          :tableName="localTableName"
          @change="onFormChangeFun"
          :rule-data="ruleData"
          :showDisabled="showDisabled"
        >
          <template #form-flowTemplate>
            <flowTemplateSelect v-model="selectedFlowTemplate" />
          </template>
          <template #form-standard>
            <knowledgeSelect v-model="standard"/>
          </template>
        </TableForm>
      </template>
      <template #footer>
        <div>
          <el-button @click="onCancelFun">{{ $t('通用.取消') }}</el-button>
          <el-button type="primary" @click="onConfirmFun">{{ $t('通用.确定') }}</el-button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue';
import Dialog from '@/components/common/dialog/index.vue';
import TableForm from '@/components/common/table/tableForm.vue';
import { getTagKeyMap, NODE_TYPE } from '@/utils/enum/node';
import { getMemberListIds } from '@/utils/task';
import { disposeTagKey } from '@/views/task/projectDetail/components/project';
import { isCategoryType, isCategoryNodeType } from '@/utils/node';
import flowTemplateSelect from './flowTemplateSelect.vue';
import knowledgeSelect from './knowledgeSelect.vue';
import { TABLE_NAME } from '@/utils/enum/tableName';

enum OPERATION_TYPE {
  ADD = 'add',
  EDIT = 'edit',
}
interface Props {
  modelValue: boolean;
  tableName?: string;
  detail?: any;
  operationType: OPERATION_TYPE | string;
  nodeType?: string;
  modalTableNameList?: string[];
  belongProject?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  tableName: '',
  operationType: OPERATION_TYPE.ADD,
  nodeType: '',
  modalTableNameList: () => ([TABLE_NAME.TASK_POOL_CATEGORY, TABLE_NAME.TASK_POOL_TASK, TABLE_NAME.TASK_POOL_PERFORMANCE]),
  detail: null,
  belongProject: false,
});

const emits = defineEmits(['update:modelValue', 'confirm']);
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emits('update:modelValue', val),
});
const tableFormRef = ref<any>();

const localDiaTitle = ref('');
const localDetail = ref<any>(null);
const localOperationType = ref<OPERATION_TYPE|string>(OPERATION_TYPE.ADD);
const localTableName = ref(props.tableName || '');
// 流程模板相关
const selectedFlowTemplate = ref<any>(null);
const standard = ref();
const onShowFun = () => {
  resetFun();
  nextTick(() => {
    if (localDetail.value) {
      tableFormRef.value?.setFormDataFun({ ...localDetail.value, eMemberList: getMemberListIds(localDetail.value.eMemberList), pMemberList: getMemberListIds(localDetail.value.pMemberList) });
      standard.value = localDetail.value.standard;
      if (localDetail.value.flowTemplate) {
        selectedFlowTemplate.value = localDetail.value.flowTemplate;
      }
    }
  });
};
const resetFun = () => {
  tableFormRef.value?.resetFun();
};

const onFormChangeFun = (data:any) => {
  if (data.key === 'eMemberList') {
    data.data.eMemberListArr = data.val;
  }
  if (data.key === 'pMemberList') {
    data.data.pMemberListArr = data.val;
  }
};
const onCancelFun = () => {
  visible.value = false;
};
const onConfirmFun = async () => {
  const valid = await tableFormRef.value?.validateFun();
  if (valid) {
    const formData = tableFormRef.value?.getFormDataFun();
    formData.standard = standard.value;
    if (selectedFlowTemplate.value) {
      formData.flowTemplate = selectedFlowTemplate.value;
    }
    if (localDetail.value?.tagKeyList) {
      const tagKeyList = disposeTagKey(formData, localDetail.value?.tagKeyList || [], getTagKeyMap());
      console.log('tagKeyList', tagKeyList);
    } else {
      formData.tagKeyList = [];
    }
    // 处理时间范围
    if (formData.planTime) {
      formData.beginTime = formData.planTime[0];
      formData.endTime = formData.planTime[1];
    }
    formData.pMemberIds = '';
    if (formData.pMemberList?.length > 0) {
      formData.pMemberIds = formData.pMemberList;
    }
    formData.eMemberIds = '';
    if (formData.eMemberList?.length > 0) {
      formData.eMemberIds = formData.eMemberList;
    }
    emits('confirm', formData);
  }
};

const showDisabled = computed(() => {
  return localOperationType.value === OPERATION_TYPE.EDIT;
});
const prepareFromProps = () => {
  const nodeType = props.nodeType;
  const operation = props.operationType;
  const detail = props.detail;

  let text = operation === OPERATION_TYPE.ADD ? '新增' : '编辑';
  let targetTableName = props.modalTableNameList?.[1] || '';
  switch (nodeType) {
    case NODE_TYPE.CATEGORY:
      text += '分类';
      targetTableName = props.modalTableNameList?.[0] || targetTableName;
      break;
    case NODE_TYPE.TASK:
      if (props.belongProject) {
        text += '任务';
      } else {
        text += '工况';
      }
      targetTableName = props.modalTableNameList?.[1] || targetTableName;
      break;
    case NODE_TYPE.PERFORMANCE:
      text += '指标';
      targetTableName = props.modalTableNameList?.[2] || targetTableName;
      break;
  }
  if (isCategoryNodeType(nodeType)) {
    text += '分类';
    targetTableName = props.modalTableNameList?.[0] || targetTableName;
  }

  localDiaTitle.value = text;
  localOperationType.value = operation;
  localTableName.value = targetTableName;

  if (operation === OPERATION_TYPE.ADD) {
    const initDetail: any = {};
    if (isCategoryType(nodeType)) {
      initDetail.nodeType = null;
    } else {
      initDetail.nodeType = nodeType;
    }
    localDetail.value = initDetail;
  } else {
    localDetail.value = detail ? { ...detail } : null;
  }
};

watch(() => props.modelValue, (val) => {
  if (val) {
    prepareFromProps();
  }
});

const ruleData = ref<any>({
  highValue: [
    {
      message: '指标类型为数值时，目标值应为数字',
      trigger: 'change',
      validator: (val: unknown) => {
        if (val === null || val === undefined || val === '') {
          return true;
        }
        const formData = tableFormRef.value?.getFormDataFun();
        if (formData.nodeType === NODE_TYPE.PERFORMANCE) {
          if (formData.performanceType === '1') {
            const s = String(val ?? '').trim();
            return s !== '' && Number.isFinite(Number(s));
          } else if (formData.performanceType === '2') {
            return true;
          } else {
            return true;
          }
        }
        return true;
      },
    },

  ],
});

</script>
<style lang="scss" scoped>
.upload {
  width: 100%;
}
.node-detail {
  :deep(.full) {
    width: 100%;
  }
}
</style>
