<template>
  <view class="py-20rpx">
    <view class="bg-white px32rpx py28rpx flex items-center">
      <view class="text-[rgba(0,0,0,0.3)]">课程名称：</view>
      <view class="flex-1 flex items-center">
        <wd-input
          type="text"
          placeholder="请输入课程名称"
          no-border
          v-model:model-value="courseItem.name"
          readonly
        />
      </view>
    </view>
    <view class="mt20rpx bg-white px32rpx py30rpx" v-if="data">
      <view class="flex items-center justify-between">
        <view class="flex items-center">
          <view class="bg-#0074FF w8rpx h28rpx rounded-6rpx"></view>
          <view class="font-semibold text-32rpx ml12rpx"> 补课课表 </view>
        </view>
        <view class="flex items-center">
          <commonbtn bg-color="#0074FF" @click="handleAddClass">
            增加课时
          </commonbtn>
          <view class="ml20rpx flex items-center" @click="handleAllUp">
            <view class="text-[rgba(0,0,0,0.3)] mr20rpx"
              >{{ isAll ? "全部收起" : "全部展开" }}
            </view>
            <wd-icon
              name="arrow-up"
              size="22px"
              color="rgba(0,0,0,0.3)"
              v-if="isAll"
            ></wd-icon>
            <wd-icon
              name="arrow-down"
              size="22px"
              color="rgba(0,0,0,0.3)"
              v-else
            ></wd-icon>
          </view>
        </view>
      </view>
      <view
        class="mt30rpx bg-#F6F6F6 rounded-32rpx px24rpx py28rpx"
        v-for="(item, idx) in makeupClassList"
        :key="idx"
      >
        <view class="flex items-center justify-between">
          <view
            class="bg-#0074FF text-28rpx rounded-full text-white px14rpx box-border py4rpx"
          >
            {{ idx + 1 }}</view
          >
          <view class="flex items-center">
            <view
              @click="handleDelete(idx)"
              class="text-#FB5B5B font-semibold text-28rpx"
              v-if="idx > 0"
              >删除</view
            >
            <view
              class="ml24rpx flex items-center"
              @click="handleItemDown(idx)"
            >
              <view class="text-[rgba(0,0,0,0.3)] mr20rpx">{{
                isActiveItem.includes(idx) ? "收起" : "展开"
              }}</view>
              <wd-icon
                name="arrow-up"
                size="22px"
                color="rgba(0,0,0,0.3)"
                v-if="isActiveItem.includes(idx)"
              ></wd-icon>
              <wd-icon
                name="arrow-down"
                size="22px"
                color="rgba(0,0,0,0.3)"
                v-else
              ></wd-icon>
            </view>
          </view>
        </view>
        <view v-show="isActiveItem.includes(idx)">
          <view class="mt20rpx">
            <view class="font-semibold"
              ><text class="text-#FB5B5B font-semibold">*</text> 开始时间</view
            >
            <view class="mt20rpx b-white rounded-16rpx overflow-hidden">
              <wd-datetime-picker
                placeholder="请选择开始时间"
                v-model:model-value="item.startTime"
                :minDate="dayjs().valueOf()"
              />
            </view>
          </view>
          <view class="mt20rpx">
            <view class="font-semibold"
              ><text class="text-#FB5B5B font-semibold">*</text> 结束时间</view
            >
            <view class="mt20rpx b-white rounded-16rpx overflow-hidden">
              <wd-datetime-picker
                placeholder="请选择结束时间"
                v-model:model-value="item.endTime"
                :minDate="dayjs().valueOf()"
              />
            </view>
          </view>
          <view class="mt20rpx">
            <view class="font-semibold"
              ><text class="text-#FB5B5B font-semibold">*</text> 课时名称</view
            >
            <view
              class="mt20rpx bg-white rounded-16rpx box-border overflow-hidden px24rpx py18rpx"
            >
              <wd-input
                type="text"
                placeholder="请输入课时名称"
                no-border
                v-model="item.name"
              />
            </view>
          </view>
        </view>
        <view class="mt3" v-show="!isActiveItem.includes(idx)">
          <wd-text
            :lines="1"
            size="28rpx"
            color="#000000"
            bold
            :text="`${dayjs(item.startTime).format('YYYY-MM-DD HH:mm')} ${dayjs(item.endTime).format('YYYY-MM-DD HH:mm')}  ${item.name}`"
          ></wd-text>
        </view>
      </view>
      <view class="h150rpx"></view>
    </view>
  </view>
  <fixdbtn block size="large" @click="save">保存</fixdbtn>
</template>

<script setup lang="ts">
import dayjs from "dayjs";
import img1 from "@/subPack/static/del.png";
import img2 from "@/subPack/static/success.png";
import type { webMakeClass } from "@/api/globals";
import { createGlobalLoadingMiddleware } from "@/api/core/middleware";
const isAll = ref(true);
const isActiveItem = ref([0]);
const makeupClassList = ref<
  {
    startTime: string | number;
    endTime: string | number;
    name: string;
  }[]
>([{ startTime: "", endTime: "", name: "" }]);
const { courseItem } = storeToRefs(useCourseStore());

const { data, send: getData } = useRequest(
  (id: string, coursesType: number) =>
    Apis.app.queryListByCoursesId({
      params: { coursesType, id },
    }),
  {
    immediate: false,
  },
);

const { send: saveData } = useRequest(
  (fromData: webMakeClass[]) => Apis.app.editPriceRules({ data: fromData }),
  {
    immediate: false,
    middleware: createGlobalLoadingMiddleware({ loadingText: "保存中..." }),
  },
);
watch(
  () => courseItem.value,
  async () => {
    await getData(String(courseItem.value.appCourseId), 1);
    makeupClassList.value = data.value.map((it) => {
      return {
        ...it,
        startTime: dayjs(it.startTime).valueOf(),
        endTime: dayjs(it.endTime).valueOf(),
      };
    });
  },
  {
    immediate: true,
  },
);
function handleAddClass() {
  makeupClassList.value.push({
    startTime: "",
    endTime: "",
    name: "",
  });
  isActiveItem.value.push(makeupClassList.value.length - 1);
}
function handleItemDown(idx: number) {
  if (isActiveItem.value.includes(idx)) {
    isActiveItem.value = isActiveItem.value.filter((item) => item !== idx);
  } else {
    isActiveItem.value.push(idx);
  }
  if (isActiveItem.value.length == makeupClassList.value.length) {
    isAll.value = true;
  }
  if (isActiveItem.value.length == 0) {
    isAll.value = false;
  }
  console.log(isActiveItem.value, "asdasdas");
}
function handleAllUp() {
  if (isActiveItem.value.length == makeupClassList.value.length) {
    isActiveItem.value = [];
  }
  isAll.value = !isAll.value;
  makeupClassList.value.forEach((item, index) => {
    if (isAll.value) {
      isActiveItem.value.push(index);
    } else {
      isActiveItem.value = [];
    }
  });
}
async function save() {
  const form: webMakeClass[] = JSON.parse(
    JSON.stringify(makeupClassList.value),
  );
  if (!areAllItemsAllFieldsFilled(form))
    return uni.showToast({
      title: "请填写完整",
      icon: "error",
      duration: 2000,
    });
  const newObj = form.map((it) => {
    return {
      ...it,
      startTime: dayjs(it.startTime).format("YYYY-MM-DD HH:mm:ss"),
      endTime: dayjs(it.endTime).format("YYYY-MM-DD HH:mm:ss"),
      coursesId: String(courseItem.value.appCourseId),
    };
  });
  await saveData(newObj);
  uni.navigateBack();
}
function handleDelete(idx: number) {
  console.log("点击");

  uni.showModal({
    title: "确认操作",
    content: "是否确认删除这条记录？",
    success: function (res) {
      if (res.confirm) {
        makeupClassList.value.splice(idx, 1);
        getToast(1);
      } else if (res.cancel) {
        console.log("用户点击取消");
      }
    },
  });
}
function getToast(type: number) {
  uni.showToast({
    image: type == 1 ? img1 : img2,
    title: type == 1 ? "删除成功" : "保存成功",
  });
}
</script>

<style scoped></style>

<route lang="json">
{
  "name": "Makeupclass",
  "style": {
    "navigationBarTitleText": "补课课表"
  }
}
</route>
