<template>
  <BaseTable
    ref="baseTableRef"
    showIndex
    showCheckbox
    :tableName="TABLE_NAME.WORKSPACE_TIME"
    :params="tableParams"
    :api="getDedicatedTimeApi"
    @checkboxChange="checkboxChangeFun"
    @checkboxAll="checkboxAllFun"
    @tableDataLoad="dataChangeFun"
  >
    <template #leftOptions>
      <el-button
        type="primary"
        icon="edit"
        :disabled="selectedRows.length === 0"
        @click="openBatchEditDialogFun"
      >
        {{ $t('工位时间维护.批量修改') }}
      </el-button>
      <el-form :inline="true">
        <el-form-item :label="$t('工位时间维护.阶段') + '：'" class="phase-content">
          <el-select
            v-model="phaseUuid"
            class="phase-select"
            :placeholder="$t('工位时间维护.请选择阶段')"
            @change="phaseChangeFun"
          >
            <el-option
              v-for="item in phaseListOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
    <template #fullName="{ row }"> {{ row.projectCode }}-{{ row.nodeCode }} </template>

    <template #structureRefinementCompletionTime="{ row }">
      <el-date-picker
        v-model="row.structureRefinementCompletionTime"
        type="datetime"
        format="YYYY-MM-DD HH:mm:ss"
        valueFormat="YYYY-MM-DD HH:mm:ss"
        :placeholder="$t('通用.请选择时间')"
        @change="updateSingleWorkspaceTimeFun(row, 'structureRefinementCompletionTime')"
      />
    </template>

    <template #stationUpgradeTime="{ row }">
      <el-date-picker
        v-model="row.stationUpgradeTime"
        type="datetime"
        format="YYYY-MM-DD HH:mm:ss"
        valueFormat="YYYY-MM-DD HH:mm:ss"
        :placeholder="$t('通用.请选择时间')"
        @change="updateSingleWorkspaceTimeFun(row, 'stationUpgradeTime')"
      />
    </template>

    <template #listReleaseTime="{ row }">
      <el-date-picker
        v-model="row.listReleaseTime"
        type="datetime"
        format="YYYY-MM-DD HH:mm:ss"
        valueFormat="YYYY-MM-DD HH:mm:ss"
        :placeholder="$t('通用.请选择时间')"
        @change="updateSingleWorkspaceTimeFun(row, 'listReleaseTime')"
      />
    </template>
  </BaseTable>

  <BatchUpdateWorkspaceTime
    v-model:visible="showBatchEditDialog"
    :selectedRows="selectedRows"
    :currentPhase="currentPhase"
    @confirm="batchEditConfirmFun"
  />
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import BaseTable from '@/components/common/table/baseTable.vue';
import {
  getDedicatedTimeApi,
  getChildrenNodeListApi,
  batchUpdateWorkspaceExtraApi,
} from '@/api/project/node';
import { NODE_TYPE } from '@/utils/enum/node';
import { TABLE_NAME } from '@/utils/enum/tableName';
import { ElMessage } from 'element-plus';
import BatchUpdateWorkspaceTime from './components/batchUpdateWorkspaceTime.vue';

const { t } = useI18n();

interface Props {
  projectUuid: string;
}

const props = withDefaults(defineProps<Props>(), {
  projectUuid: '',
});

const baseTableRef = ref();

const phaseUuid = ref('');
const phaseListOptions = ref<any[]>([]);

const getPhaseListFun = async () => {
  if (!props.projectUuid) {
    return;
  }
  const res: any = await getChildrenNodeListApi({
    current: 1,
    size: 999,
    nodeType: NODE_TYPE.PHASE,
    nodeId: props.projectUuid,
  });
  if (res && res.code === 200) {
    phaseListOptions.value = res.data.map((item: { nodeName: string; uuid: string }) => ({
      label: item.nodeName,
      value: item.uuid,
    }));
    if (phaseListOptions.value.length && !phaseUuid.value) {
      phaseUuid.value = phaseListOptions.value[0].value;
    }
  } else {
    phaseListOptions.value = [];
  }
};

const phaseChangeFun = () => {
  selectedRows.value = [];
};

const tableParams = computed(() => ({
  projectUuid: props.projectUuid,
  nodeUuid: phaseUuid.value,
}));

const showBatchEditDialog = ref(false);
const selectedRows = ref<any[]>([]);

const currentPhase = computed(() => {
  return phaseListOptions.value.find((item) => item.value === phaseUuid.value);
});

const checkboxChangeFun = () => {
  const rows = baseTableRef.value?.tableRef?.getCheckboxRecords?.() || [];
  selectedRows.value = rows;
};

const checkboxAllFun = () => {
  const rows = baseTableRef.value?.tableRef?.getCheckboxRecords?.() || [];
  selectedRows.value = rows;
};

const openBatchEditDialogFun = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning(t('工位时间维护.请先选择要修改的工位'));
    return;
  }
  showBatchEditDialog.value = true;
};

const batchEditConfirmFun = () => {
  selectedRows.value = [];
  baseTableRef.value?.resetFun();
};

const dataChangeFun = () => {
  const tableData = baseTableRef.value?.tableData || [];
  tableData.forEach((row: any) => {
    if (row._timeFieldsProcessed) {
      return;
    }

    if (row.extras && Array.isArray(row.extras)) {
      row.extras.forEach((extra: any) => {
        if (extra.propertyName === 'structureRefinementCompletionTime') {
          row.structureRefinementCompletionTime = extra.propertyValue;
        } else if (extra.propertyName === 'stationUpgradeTime') {
          row.stationUpgradeTime = extra.propertyValue;
        } else if (extra.propertyName === 'listReleaseTime') {
          row.listReleaseTime = extra.propertyValue;
        }
      });
      row._timeFieldsProcessed = true;
    }
  });
};

const updateSingleWorkspaceTimeFun = async (row: any, propertyName: string) => {
  const propertyValue = row[propertyName] || '';

  const isDesignPhase = currentPhase.value?.label?.includes('设计') || false;
  const syncToTask = isDesignPhase;

  try {
    const res: any = await batchUpdateWorkspaceExtraApi({
      workspaceExtras: [
        {
          workspaceUuid: row.uuid,
          extras: [
            {
              propertyName,
              propertyValue,
            },
          ],
        },
      ],
      syncToTask,
    });

    if (res && res.code === 200) {
      ElMessage.success(t('通用.操作成功'));
      baseTableRef.value?.resetFun();
    }
  } catch (error) {
    console.error('更新失败', error);
    baseTableRef.value?.resetFun();
  }
};

onMounted(() => {
  getPhaseListFun();
});
</script>

<style scoped>
.phase-content {
  margin-bottom: 0;
  margin-left: 12px;
}
.phase-select {
  width: 180px;
}
</style>
