<template>
  <div class="p-2">
    <PageHeader></PageHeader>
    <div class="EditBody">
      <div class="title">
        <div>基本信息</div>
      </div>
      <div class="bodybox">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" label-position="right">
          <el-form-item label="巡检计划名称" prop="planName">
            <el-input v-model="form.planName" placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="任务时间">
            <div class="flex flex-wrap">
              <div
                class="week-items"
                @click="checkoutWeekFun(item)"
                :class="{
                  active: checkoutWeek.includes(item)
                }"
                v-for="(item, index) in 7"
                :key="index"
              >
                <div class="iconbox">
                  <el-icon v-show="checkoutWeek.includes(item)"><Check /></el-icon>
                </div>
                <span class="ml-5px">{{ numToWeek(item) }}</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="任务时间段">
            <!-- <el-select v-model="form.taskTime" placeholder="选择任务时间段" style="width: 100%">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select> -->
            <div v-for="(_, index) in taskTime" :key="index" style="display: flex; align-items: center; margin-top: 10px">
              <el-time-picker
                v-model="taskTime[index]"
                is-range
                range-separator="到"
                start-placeholder="开始时间"
                format="HH:mm"
                value-format="HH:mm:00"
                end-placeholder="结束时间"
                style="width: 100%"
              />
              <!-- <el-button v-if="taskTime.length > 1" icon="Minus" circle style="margin-left: 10px" @click="removeTaskTime(index)"></el-button>
              <el-button
                v-if="taskTime.length === index + 1 && taskTime.length <= 8"
                icon="Plus"
                circle
                style="margin-left: 10px"
                @click="addTaskTime"
              ></el-button> -->
            </div>
          </el-form-item>

          <el-form-item label="提醒时间">
            <el-select v-model="form.remindTime" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in com_inspection_remind_tiime" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划路线">
            <el-select @change="handleChangeMap" v-model="form.routeIds" placeholder="请选择" style="width: 100%">
              <el-option v-for="item in playlist" :key="item.value" :label="item.routeName" :value="item.id" />
            </el-select>
            <GD ref="GDef" :disabled="true"></GD>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="outback">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { listRoute } from '@/api/system/InspectionRoute';
import PageHeader from '@/components/Pageheader/index.vue';
import { numToWeek } from '@/utils/time';
import { ref } from 'vue';
import { addPlan, getPlan, updatePlan } from '@/api/system/InspectionPlan';
import { Check } from '@element-plus/icons-vue';
import GD from '@/components/Map/GD.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { com_inspection_remind_tiime } = toRefs<any>(proxy?.useDict('com_inspection_remind_tiime'));

const route = useRoute();
const router = useRouter();

const form = ref({
  id: null,
  planName: '', // 巡检计划名称
  inspectorIds: '', // 巡检人员
  taskTime: '', // 任务时间段
  executeDay: '', // 执行周期具体的周几
  remindTime: '', // 提醒时间
  routeIds: '', // 计划路线id
  inspectSetting: 0 // 巡检设置
});
const rules = ref({
  planName: [{ required: true, message: '请输入巡检计划名称', trigger: 'blur' }],
  inspectorIds: [{ required: true, message: '请选择巡检人员', trigger: 'blur' }],
  routeIds: [{ required: true, message: '请选择路线', trigger: 'blur' }]
});
// 初始化 taskTime，确保至少有一个时间段
const taskTime = ref<[string, string][]>([['', '']]);

// 选择周几
const checkoutWeek = ref([]);
function checkoutWeekFun(val: number) {
  if (!checkoutWeek.value.includes(val)) {
    checkoutWeek.value.push(val);
    form.value.executeDay = checkoutWeek.value.join(',');
  } else {
    checkoutWeek.value = checkoutWeek.value.filter((item) => item !== val);
  }
}

// 提醒时间

// 巡检计划id
const editid = ref(null);

// 初始化
// 路线列表
const playlist = ref([]);
async function init() {
  const res = await listRoute();
  playlist.value = res.rows;
  if (route.query.id) {
    editid.value = route.query.id;
    getPlan(editid.value).then((res) => {
      form.value = {
        id: res.data.id,
        planName: res.data.planName, // 巡检计划名称
        inspectorIds: res.data.inspectorIds, // 巡检人员
        taskTime: res.data.taskTime, // 任务时间段
        executeDay: res.data.executeDay, // 执行周期具体的周几
        remindTime: res.data.remindTime, // 提醒时间
        routeIds: res.data.routeIds, // 计划路线id
        inspectSetting: res.data.inspectSetting // 巡检设置
      };
      checkoutWeek.value = res.data.executeDay
        .split(',')
        .map((item) => Number(item))
        .filter((item) => item);

      // 2. 处理任务时间段的回显
      if (res.data.taskTime) {
        // 假设后端返回格式为 "09:00-11:00; 13:00-15:00"
        // 先按分号分割，再按横杠分割开始和结束时间
        taskTime.value = res.data.taskTime.split(';').map((timeRange: string) => {
          const times = timeRange.trim().split('-');
          // 确保返回的是 [start, end] 格式，如果解析失败则返回空字符串
          return times.length === 2 ? [times[0], times[1]] : ['', ''];
        });
        // 如果解析后为空，至少保留一个空项以便用户添加
        if (taskTime.value.length === 0) {
          taskTime.value = [['', '']];
        }
      } else {
        taskTime.value = [['', '']];
      }

      handleChangeMap(res.data.routeIds);
    });
  }
}

// 返回
function outback() {
  router.back();
}

const GDef = ref(null);

function handleChangeMap(val: string) {
  if (val) {
    GDef.value.clearMapMarker();
    const find = playlist.value.find((item) => item.id === val);
    if (find.points && find.points.length > 0) {
      find.points.forEach((item) => {
        const angular = item.location.split(',').map(Number).filter(Boolean);
        GDef.value.addMarker_more(angular, item.pointNames, item.id);
      });
    }
    // 巡检路线
    if (find.pathPoints) {
      GDef.value.renderSavedPath(find.pathPoints);
    }
  }
}

onMounted(() => {
  init();
});
const formRef = ref();
function submit() {
  // 将二维数组转换为字符串，例如 "09:00-11:00; 13:00-15:00"
  form.value.taskTime = taskTime.value
    .filter((t) => t[0] && t[1]) // 过滤掉未填写的
    .map((t) => `${t[0]}-${t[1]}`)
    .join('; ');

  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (editid.value) {
        updatePlan(form.value).then(() => {
          ElMessage.success('编辑成功');
          outback();
        });
      } else {
        addPlan(form.value).then(() => {
          ElMessage.success('添加成功');
          outback();
        });
      }
    }
  });
}
</script>

<style scoped lang="scss">
.EditBody {
  margin-top: 20px;
  padding: 30px;
  background-color: white;
  .bodybox {
    width: 600px;
    margin: 20px auto 0;
  }
  .inspectorIdsBox {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .inspector_items {
      width: 120px;
      height: 40px;
      line-height: 40px;
      margin: 5px;
      text-align: center;
      border-radius: 5px;
      background-color: #ddeaff;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 0 2px;
      .name {
        overflow: hidden;
        text-overflow: ellipsis;
        text-wrap: nowrap;
      }
      &.add {
        background-color: #ddeaff25;
        border: 1px dashed #ccc;
        cursor: pointer;
        &:hover {
          background-color: rgba(221, 234, 255, 0.199);
          border-color: #44a0ff;
          color: #44a0ff;
        }
      }
      .deleteaction {
        margin-left: 10px;
        cursor: pointer;
        &:hover {
          color: red;
        }
      }
    }
  }
  .week-items {
    width: 90px;
    height: 30px;
    line-height: 30px;
    border-radius: 5px;
    cursor: pointer;
    margin: 10px 5px;
    border: 1px solid #ccc;
    color: #000;
    display: flex;
    align-items: center;
    .iconbox {
      width: 30px;
      height: 30px;
      margin-left: 5px;
      text-align: center;
      line-height: 30px;
    }
    &.active {
      color: rgba(26, 117, 255, 1);
      background-color: rgba(26, 117, 255, 0.15);
      border: none;
    }
  }

  .mapbox {
    margin-top: 20px;
    width: 100%;
    height: 400px;
    border: 1px solid #ccc;
  }
}
</style>
