<template>
  <div class="dialog">
    <div class="title gradient-text">启动预案</div>
    <div class="close-icon" @click="onClose"></div>
    <!-- 响应等级选择和操作按钮 -->
    <div class="section-box">
      <div class="title2">响应等级</div>
      <el-select v-model="selectedLevel" placeholder="请选择响应等级" class="custom-select" style="width: 1200px;margin-left: 30px">
        <el-option v-for="level in responseLevels" :key="level.value" :label="level.name" :value="level.value"></el-option>
      </el-select>
      <div class="btn" @click="onStartPlan">启动预案</div>
      <div class="btn" @click="onTaskDelivery">预案任务下发</div>
    </div>
    <div class="title-box">{{ planTitle }}</div>
    <div class="plan-content">
      <!-- 预案内容的标签页 -->
      <div class="tabs">
        <div v-for="(item, index) in tabs" :key="index" :class="index === activeTab ? 'tab tabActive' : 'tab'" @click="handleClickTab(index)">{{ item.label }}</div>
      </div>
      <div class="tab-content">
        <div class="tabs2">
          <div
            v-for="(item, index) in tabs[activeTab]?.children"
            :key="index"
            :class="index === activeTab2 ? 'tab tab-active2' : 'tab'"
            @click="handleClickTab2(index)"
          >
            <div class="text">{{ item.label }}</div>
          </div>
        </div>
        <div class="tab-content2">
          {{
            tabs[activeTab] && tabs[activeTab].children && tabs[activeTab].children[activeTab2] ? tabs[activeTab].children[activeTab2].content : ''
          }}
        </div>
      </div>
    </div>
    <TaskDelivery v-model="taskDeliveryState.show" :title="taskDeliveryState.title" :planId="planData.plan_id" :eventId="props.eventId" />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import TaskDelivery from './TaskDelivery.vue';
import { matchingPlan, launchPlan } from '@/api/duty/eventing';
// 内部状态
const planTitle = ref(''); // 预案名称
const selectedLevel = ref(''); // 默认响应等级为空
// 定义组件接收的属性类型
interface Props {
  show: boolean;
  eventId: string;
  title: string;
}
// 初始化组件属性
const props = defineProps<Props>();

const responseLevels = [
  // 响应等级选项
  { value: '1', name: '特重大（I级）' },
  { value: '2', name: '重大（II级）' },
  { value: '3', name: '较大（III级）' },
  { value: '4', name: '一般（IV级）' }
];
const planData = reactive({
    purpose: '',
    basis: '',
    scope: '',
    principles: '',
    plan_id: ''
});

let plan_id = '';
const tabs = ref([
  {
    label: '总则',
    children: [
      { label: '编制目的', content: '编制目的内容' },
      { label: '编制依据', content: '编制依据内容' },
      { label: '适用范围', content: '适用范围内容' },
      { label: '工作原则', content: '工作原则内容' }
    ]
  },
  { label: '组织体系', children: [] },
  { label: '运行机制', children: [] },
  { label: '应急保障', children: [] },
  { label: '附则', children: [] },
  { label: '附件', children: [] }
]);
const activeTab = ref(0); // 当前激活的标签页
const activeTab2 = ref(0); // 当前激活的标签页

const handleClickTab = (key) => {
  activeTab.value = key;
};
const handleClickTab2 = (key) => {
  activeTab2.value = key;
};

// 定义事件发射器
const emit = defineEmits(['update:show']);

// 对话框关闭时执行的操作
const onClose = () => {
  emit('update:show', false);
};

// 处理启动预案的函数
const onStartPlan = async () => {
  // 检查是否选择了响应等级
  if (!selectedLevel.value) {
    ElMessage.error('请先选择响应等级！');
    return;
  }

  // 收集数据
  const data = {
    response_level: selectedLevel.value,
    eventId: props.eventId,
    plan_id: planData.plan_id // 确保 planData 中包含正确的 plan_id
  };

  try {
    // 调用后端API启动预案
    const response = await launchPlan(data);
    if (response && response.code === 200) {
      ElMessage.success('预案启动成功！');
    } else if (response && response.code !== 200) {
      ElMessage.error(`预案启动失败，后端返回错误码：${response.code}`);
    }
  } catch (error) {
    console.error('启动预案时发生的错误:', error);
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error(error.response.data.message);
    } else if (error.response && error.response.status) {
      ElMessage.error(`启动预案时发生错误，HTTP 状态码：${error.response.status}`);
    } else {
      ElMessage.error('启动预案时发生未知错误，请稍后再试。');
    }
  }
};
// 处理标签页点击事件
const onTabClick = (tab: any, event: Event) => {
  // 实现标签页点击的逻辑
};

// 控制 taskDelivery 弹窗的显示状态
const taskDeliveryState = reactive({
  show: ref(false),
  title: '' as string
});

// 处理预案任务下发内容的函数
const onTaskDelivery = () => {
  taskDeliveryState.title = '预案任务下发';
  taskDeliveryState.show = true;
};

// 调用接口获取预案数据
const fetchPlanData = async () => {
  try {
    if (!props.eventId) {
      ElMessage.warning('eventId 为空，无法获取预案数据');
      return;
    }
    const response = await matchingPlan({ eventId: props.eventId });
    if (response && response.code === 200) {
      const data = response.data;
      planTitle.value = `预案名称: ${data.plan_name}`;
      if (data.response_level) {
        const isValidLevel = responseLevels.some((level) => level.value === data.response_level);
        if (isValidLevel) {
          selectedLevel.value = data.response_level;
        } else {
          ElMessage.error('无效的响应等级，请检查数据');
          selectedLevel.value = '';
        }
      } else {
        selectedLevel.value = '';
      }
      planData.purpose = data.purpose || '这是内容...';
      planData.basis = data.basis || '这是内容...';
      planData.scope = data.scope || '这是内容...';
      planData.principles = data.principles || '这是内容...';
      planData.plan_id = data.plan_id; // 确保 planData 中包含 plan_id
    } else {
      ElMessage.error('未能从服务器获取有效的预案数据');
    }
  } catch (error) {
    ElMessage.error('获取预案数据失败');
  }
};

// 在组件挂载时尝试获取预案数据
onMounted(() => {
  if (props.eventId) {
    fetchPlanData();
  }
});

// 监听 eventId 变化
watch(
  () => props.eventId,
  (newEventId) => {
    if (newEventId) {
      fetchPlanData();
    }
  }
);
</script>

<style scoped>
.dialog {
  position: absolute;
  top: 478px;
  left: 50%;
  transform: translateX(-50%);
  width: 2839px;
  height: 1263px;
  background: url('@/assets/images/plan/dialog.png') no-repeat;
  padding-top: 200px;
  color: #fff;
  font-size: 36px;
  .title {
    position: absolute;
    top: 30px;
    left: 55px;
    font-size: 80px;
  }
  .close-icon {
    position: absolute;
    top: 0px;
    right: 0px;
    width: 75px;
    height: 70px;
    background: url('@/assets/images/map/rightMenu/close.png') no-repeat;
    background-size: 100% 100%;
    cursor: pointer;
  }
  .section-box {
    display: flex;
    align-items: center;
    padding: 15px 60px;
    border: 1px solid #16448c;
    .btn {
      width: 440px;
      height: 120px;
      background: url('@/assets/images/plan/btn.png') no-repeat;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .title-box {
    background-image: url('@/assets/images/plan/titleBox.png');
    background-repeat: no-repeat;
    background-size: 354px 28px;
    background-position: bottom left;
    margin: 40px 60px 0;
    font-family: 'YouSheBiaoTiHei';
    font-size: 56px;
    padding-left: 50px;
  }
}

h2 {
  text-align: center;
}
/* 样式 */
.plan-content {
  display: flex;
  flex-direction: column;
  margin: 40px 60px;
}

.button-container {
  display: flex;
  justify-content: flex-end;
}

.content-row {
  margin-top: 20px;
}
.tabs {
  display: flex;
  width: 100%;
  overflow-x: auto;
  .tab {
    width: 350px;
    height: 78px;
    background: url('@/assets/images/plan/tab.png') no-repeat;
    display: flex;
    justify-content: center;
    align-items: flex-end;
    margin-left: 50px;
    font-family: 'YouSheBiaoTiHei';
    font-size: 38px;
    cursor: pointer;
    &:hover {
      background: url('@/assets/images/plan/tabActive.png') no-repeat;
    }
    &:first-child {
      margin-left: 0;
    }
  }
  .tabActive {
    background: url('@/assets/images/plan/tabActive.png') no-repeat;
  }
}
.tab-content {
  display: flex;
  margin-top: 30px;
  .tabs2 {
    .tab {
      width: 399px;
      height: 70px;
      background: url('@/assets/images/plan/tab2.png') no-repeat;
      display: flex;
      align-items: center;
      padding-left: 76px;
      color: #9badc4;
      font-size: 36px;
      font-weight: bold;
      margin-top: 60px;
      position: relative;
      cursor: pointer;
      &::before {
        content: '';
        width: 2px;
        height: 68px;
        background: #2b88bd;
        position: absolute;
        top: -63px;
        left: 42px;
      }
      &:first-child {
        margin-top: 0;
        &::before {
          display: none;
        }
      }
      &:hover {
        width: 439px;
        background: url('@/assets/images/plan/tab2Active.png') no-repeat;
        .text {
          /* 设置字体透明 */
          color: transparent;
          /* 设置线性渐变，从红色渐变到蓝色 */
          background-image: linear-gradient(to bottom, #fff 40%, #5CC4FA 50%, #40A2E7 100%);
          /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
          -webkit-background-clip: text;
          /* 非Webkit内核浏览器需要使用标准前缀 */
          background-clip: text;
          /* 把当前元素设置为行内块，以便能够应用背景 */
          display: inline-block;
        }
      }
    }
    .tab-active2 {
      width: 439px;
      background: url('@/assets/images/plan/tab2Active.png') no-repeat;
      .text {
        /* 设置字体透明 */
        color: transparent;
        /* 设置线性渐变，从红色渐变到蓝色 */
        background-image: linear-gradient(to bottom, #fff 40%, #5CC4FA 50%, #40A2E7 100%);
        /* 使用 -webkit-background-clip 属性将背景剪裁至文本形状 */
        -webkit-background-clip: text;
        /* 非Webkit内核浏览器需要使用标准前缀 */
        background-clip: text;
        /* 把当前元素设置为行内块，以便能够应用背景 */
        display: inline-block;
      }
    }
  }
  .tab-content2 {
    height: 620px;
    overflow-y: auto;
  }
}
</style>
