<template>
  <BasicLayout>
    <view class="p-15">
      <!-- 请假信息卡片 -->
      <view class="info-card">
        <view class="card-header">
          <text class="applicant-name">教师{{ qjData.jsName }}的请假申请</text>
        </view>
        <view class="card-content">
          <view class="info-row">
            <text class="label">请假类型:</text>
            <text class="value">{{ qjData.qjlx }}</text>
          </view>
          <view class="info-row">
            <text class="label">请假时间:</text>
            <text class="value">{{ qjData.qjkstime }} 至 {{ qjData.qjjstime }}</text>
          </view>
          <view class="info-row">
            <text class="label">请假时长:</text>
            <text class="value">{{ qjData.qjsc }}</text>
          </view>
          <view class="info-row">
            <text class="label">请假事由:</text>
            <text class="value">{{ qjData.qjsy }}</text>
          </view>
        </view>
      </view>

      <!-- 代课安排 -->
      <view class="dk-arrange-card">
        <view class="card-header">
          <text class="card-title">代课安排</text>
        </view>
        <view class="card-content">
          <view class="dk-list">
            <view 
              v-for="(dk, index) in dkList" 
              :key="index" 
              class="dk-item"
            >
              <view class="dk-header">
                <text class="dk-title">代课{{ index + 1 }}</text>
                <u-button 
                  text="删除" 
                  size="mini" 
                  type="error" 
                  @click="removeDk(index)"
                />
              </view>
              <view class="dk-content">
                <view class="info-row">
                  <text class="label">代课教师:</text>
                  <text class="value">{{ dk.jsName }}</text>
                </view>
                <view class="info-row">
                  <text class="label">代课时间:</text>
                  <text class="value">{{ dk.dktime }}</text>
                </view>
                <view class="info-row">
                  <text class="label">课程名称:</text>
                  <text class="value">{{ dk.kcmc }}</text>
                </view>
                <view class="info-row">
                  <text class="label">班级:</text>
                  <text class="value">{{ dk.bjmc }}</text>
                </view>
              </view>
            </view>
          </view>
          
          <view class="add-dk-section">
            <u-button 
              text="添加代课安排" 
              type="primary" 
              @click="showDkSelector"
              class="add-btn"
            />
          </view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="submit-section">
        <u-button 
          text="提交协调结果" 
          type="primary" 
          @click="handleSubmit"
          class="submit-btn"
        />
      </view>
    </view>

    <!-- 代课教师选择弹窗 -->
    <u-popup
      :show="showSelector"
      mode="bottom"
      height="70%"
      @close="closeSelector"
    >
      <view class="selector-container">
        <view class="selector-header">
          <text class="selector-title">选择代课教师</text>
          <u-button text="确定" type="primary" @click="confirmSelection" />
        </view>
        <view class="selector-content">
          <u-checkbox-group v-model="selectedDkIds">
            <view 
              v-for="dk in availableDkList" 
              :key="dk.id" 
              class="dk-option"
            >
              <u-checkbox 
                :value="dk.id" 
                :label="`${dk.jsName} - ${dk.kcmc} - ${dk.bjmc}`"
              />
            </view>
          </u-checkbox-group>
        </view>
      </view>
    </u-popup>
  </BasicLayout>
</template>

<script setup lang="ts">
import { jsQjJwcXtApi } from "@/api/base/jsQjApi";
import { findQjById, getPkkbByJsRangeTimeApi } from "@/api/base/jsQjApi";
import { useUserStore } from "@/store/modules/user";
import { navigateBack } from "@/utils/uniapp";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";

const { getJs } = useUserStore();

const qjId = ref<string>();
const qjData = ref<any>({});
const dkList = ref<any[]>([]);
const availableDkList = ref<any[]>([]);
const selectedDkIds = ref<string[]>([]);
const showSelector = ref(false);

// 加载请假信息
const loadQjData = async () => {
  try {
    const result = await findQjById({ id: qjId.value });
    if (result.code === 1) {
      qjData.value = result.data;
      // 加载可用的代课安排
      await loadAvailableDkList();
    }
  } catch (error) {
    console.error('获取请假信息失败:', error);
  }
};

// 加载可用的代课安排
const loadAvailableDkList = async () => {
  try {
    const params = {
      jsId: qjData.value.jsId,
      startTime: qjData.value.qjkstime,
      endTime: qjData.value.qjjstime
    };
    const result = await getPkkbByJsRangeTimeApi(params);
    if (result.code === 1) {
      availableDkList.value = result.data || [];
    }
  } catch (error) {
    console.error('获取可用代课安排失败:', error);
  }
};

// 显示代课选择器
const showDkSelector = () => {
  selectedDkIds.value = [];
  showSelector.value = true;
};

// 关闭选择器
const closeSelector = () => {
  showSelector.value = false;
  selectedDkIds.value = [];
};

// 确认选择
const confirmSelection = () => {
  const selectedDks = availableDkList.value.filter(dk => 
    selectedDkIds.value.includes(dk.id)
  );
  
  // 添加到代课列表
  selectedDks.forEach(dk => {
    const dkItem = {
      jsId: dk.jsId,
      jsName: dk.jsName,
      dktime: dk.dktime,
      kcmc: dk.kcmc,
      bjmc: dk.bjmc,
      pkkbId: dk.id
    };
    dkList.value.push(dkItem);
  });
  
  closeSelector();
};

// 删除代课安排
const removeDk = (index: number) => {
  dkList.value.splice(index, 1);
};

// 提交协调结果
const handleSubmit = async () => {
  if (dkList.value.length === 0) {
    uni.showToast({
      title: "请至少添加一个代课安排",
      icon: "none"
    });
    return;
  }
  
  const params = {
    qjId: qjId.value,
    jsId: getJs.id,
    dkList: dkList.value
  };
  
  uni.showLoading({ title: "提交中..." });
  try {
    await jsQjJwcXtApi(params);
    uni.showToast({ title: "协调成功", icon: "success" });
    navigateBack();
  } catch (error) {
    uni.showToast({ title: "协调失败", icon: "error" });
  }
  uni.hideLoading();
};

onLoad((options) => {
  if (options.qjId) {
    qjId.value = options.qjId;
    loadQjData();
  }
});
</script>

<style lang="scss" scoped>
.info-card,
.dk-arrange-card {
  background: white;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-header {
  padding: 15px;
  border-bottom: 1px solid #eee;
  
  .applicant-name,
  .card-title {
    font-size: 16px;
    font-weight: bold;
    color: #333;
  }
}

.card-content {
  padding: 15px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .label {
    width: 80px;
    font-size: 14px;
    color: #666;
    flex-shrink: 0;
  }
  
  .value {
    flex: 1;
    font-size: 14px;
    color: #333;
  }
}

.dk-list {
  .dk-item {
    border: 1px solid #eee;
    border-radius: 6px;
    margin-bottom: 10px;
    
    .dk-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #eee;
      
      .dk-title {
        font-size: 14px;
        font-weight: bold;
        color: #333;
      }
    }
    
    .dk-content {
      padding: 10px;
    }
  }
}

.add-dk-section {
  margin-top: 15px;
  text-align: center;
  
  .add-btn {
    width: 100%;
  }
}

.submit-section {
  margin-top: 20px;
  
  .submit-btn {
    width: 100%;
  }
}

.selector-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .selector-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    border-bottom: 1px solid #eee;
    
    .selector-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  
  .selector-content {
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    
    .dk-option {
      padding: 10px 0;
      border-bottom: 1px solid #f0f0f0;
    }
  }
}
</style>
