<template>
  <div>
    <el-dialog
      title="待办事项"
      v-model="dialogVisible"
      fullscreen
      :show-close="false"
    >
      <template #header>
        <el-card border>
          <template #header>
            <div class="flex items-center justify-between">
              <h3>待办事项</h3>
              <div class="text-right">
                <el-button type="danger" plain @click="dialogVisible = false"
                  >关闭</el-button
                >
              </div>
            </div>
          </template>
          <div>
            <div>
              <el-row :gutter="40">
                <el-col :span="6">
                  <div>
                    <ComponentProfileCard :id="currentArchiveId" />
                    <div class="pt-5" />
                    <!-- <Auth value="headlthManage:todoList:edit">
                      <div
                        class="flex items-center justify-between py-3 px-4 border-0 border-b border-solid border-gray-100 cursor-pointer text-sm hover:bg-gray-50"
                        :class="{
                          'bg-gray-50 text-blue-500': curMenu === 'NewTodoItems'
                        }"
                        @click="handleChangeCurMenu('NewTodoItems')"
                      >
                        <span>新增待办事项</span>
                        <ArrowRight class="w-4" />
                      </div>
                    </Auth> -->
                    <div v-for="(menu, menuIdx) in menus" :key="menuIdx">
                      <div
                        class="flex items-center justify-between py-3 px-4 border-0 border-b border-solid border-gray-100 cursor-pointer text-sm hover:bg-gray-50"
                        :class="{
                          'bg-gray-50 text-blue-500': curMenu === menu.key
                        }"
                        v-if="menuIdx == 2 || hasAuth(menu.auth)"
                        @click="handleChangeCurMenu(menu.key)"
                      >
                        <span>{{ menu.label }} </span>
                        <ArrowRight class="w-4" />
                      </div>
                    </div>
                    <div class="pt-3">
                      <el-text tag="b">选择指定月份或日期处理待办</el-text>
                      <div
                        class="border border-solid border-gray-100 pt-3 mt-3"
                      >
                        <div class="flex justify-between">
                          <el-date-picker
                            v-model="state.date"
                            type="month"
                            placeholder="选择月份"
                            value-format="YYYY-MM"
                            format="YYYY年MM月"
                            @change="handleMonth"
                            class="ml-2"
                          />
                          <div class="pr-2">
                            <el-button
                              type="primary"
                              link
                              @click="handleBackToday"
                              >返回今天</el-button
                            >
                          </div>
                        </div>

                        <el-calendar
                          v-model="state.calendarValue"
                          ref="calendarRef"
                        >
                          <template #date-cell="{ data }">
                            <div
                              class="h-full flex flex-col items-center justify-center"
                              @click="onLiclick(data.day)"
                            >
                              <div class="relative">
                                <div class="text-sm">
                                  {{ data.day.split("-").slice(2).join("-") }}
                                </div>
                                <template
                                  v-if="state.itemDateList[data.day]?.length"
                                >
                                  <div
                                    class="w-2 h-2 absolute rounded top-2"
                                    :class="
                                      itemStatusList[
                                        formatDot(state.itemDateList[data.day])
                                      ].color
                                    "
                                    style="left: 5px"
                                  />
                                  <div class="w-12 text-gray-400 text-xs">
                                    <div
                                      v-if="
                                        state.itemDateList[data.day]?.length
                                      "
                                    >
                                      {{
                                        state.itemDateList[data.day]?.length
                                      }}项
                                    </div>
                                  </div>
                                </template>
                              </div>
                            </div>
                          </template>
                        </el-calendar>
                      </div>
                      <div class="pt-3">
                        <el-text tag="b" class="text-base">说明</el-text>
                        <div class="flex items-center pt-2">
                          <div
                            class="bg-red-600 w-2.5 h-2.5 rounded-full inline-block mr-2"
                          />
                          <span class="text-sm"
                            >表示当天用户有待办事项需完成</span
                          >
                        </div>
                        <div class="flex items-center mb-3 mt-3">
                          <div
                            class="bg-green-600 w-2.5 h-2.5 rounded-full inline-block mr-2"
                          />
                          <span class="text-sm"
                            >表示当天用户所有待办事项已完成</span
                          >
                        </div>
                        <div class="flex items-center">
                          <div
                            class="bg-blue-600 w-2.5 h-2.5 rounded-full inline-block mr-2"
                          />
                          <span class="text-sm"
                            >表示当天用户还有部分待办事项需完成</span
                          >
                        </div>
                      </div>
                    </div>
                  </div>
                </el-col>
                <el-col
                  :span="18"
                  class="border-0 border-l-8 border-gray-100 relative"
                >
                  <template v-if="curMenu == 'NewTodoItems'">
                    <el-form label-width="120px" label-position="left">
                      <el-form-item label="选择事项类别:" required>
                        <el-radio-group v-model="state.itemType">
                          <el-radio
                            v-for="(item, index) in itemTypeList"
                            :key="index"
                            :label="item.value"
                          >
                            {{ item.key }}
                          </el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-form>
                    <div class="">
                      <el-scrollbar height="calc(100vh - 260px)">
                        <component :is="cmps[state.itemType]" ref="cmpsRef" />
                      </el-scrollbar>
                    </div>
                  </template>
                  <template v-else-if="curMenu === 'TodoManagement'">
                    <BacklogConfigList
                      ref="BacklogConfigListRef"
                      @success="getList"
                    />
                  </template>
                  <template v-else>
                    <el-scrollbar height="calc(100vh - 160px)">
                      <template v-if="state.todoDurationList.length">
                        <KeepAlive include="CurrentMonthTodoItems">
                          <component
                            :is="currentMonthTodoItems"
                            :list="state.todoDurationList"
                            :currentDate="state.currentDate"
                            :uncompleted="
                              formatDot(
                                state.itemDateList[state.currentDate]
                              ) != 1
                            "
                            @success="
                              () => {
                                emits('success');
                                getList();
                              }
                            "
                          />
                        </KeepAlive>
                      </template>
                      <template v-else>
                        <el-empty
                          :description="`${state.date}月暂无待办事项`"
                        />
                      </template>
                    </el-scrollbar>
                  </template>
                  <div
                    class="absolute left-0 bottom-0 w-full text-right border border-gray-100 py-4 px-2"
                    v-if="curMenu == 'NewTodoItems'"
                  >
                    <el-button type="primary" @click="onSave('add')"
                      >保存事项</el-button
                    >
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>
      </template>
    </el-dialog>
    <ComponentDialogBacklogCheckbox
      v-model:show="state.visibleBacklogHandle"
      :date="state.time"
      :type="props.type"
      @success="
        () => {
          emits('success');
          getList();
        }
      "
    />
    <!-- <el-dialog
      title="确定要添加这个事项吗？"
      v-model="visibleConfirm"
      width="20%"
    >
      <div class="px-5">
        <div class="flex justify-between mb-4">
          <el-button type="danger" @click="onSave('add')"
            >确定并继续添加待办事项</el-button
          >
          <el-button type="primary" @click="onSave('view')"
            >确定并查看待办事项</el-button
          >
        </div>
        <el-button type="" class="w-full" @click="visibleConfirm = false"
          >取消</el-button
        >
      </div>
    </el-dialog> -->
  </div>
</template>
<script setup>
import { request } from "@/utils";
import moment from "moment";
import { ArrowRight } from "@element-plus/icons-vue";
import {
  ref,
  computed,
  defineProps,
  defineEmits,
  watch,
  reactive,
  defineAsyncComponent,
  nextTick
} from "vue";
import { hasAuth } from "@/router/utils";

import ComponentDialogBacklogCheckbox from "./DialogBacklogCheckbox.vue";
import ComponentProfileCard from "./ProfileCard.vue";
import BacklogConfigList from "./BacklogConfigList.vue";
// import CurrentMonthTodoItems from "./CurrentMonthTodoItems.vue";

import { useManageProjectStoreHook } from "@/store/modules/manageProject";
import { ElMessage } from "element-plus";

const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: "edit"
  },
  complateTime: {
    type: String,
    default: ""
  }
});
const emits = defineEmits(["update:show", "success", "onClickDay"]);
const dialogVisible = computed({
  get() {
    return props.show;
  },
  set(n) {
    emits("update:show", n);
  }
});
const cmpsRef = ref();

const curMenu = ref("HandleMonthTodo");
const currentMonthTodoItems = defineAsyncComponent(() =>
  import("./CurrentMonthTodoItems.vue")
);
const itemStatusList = [
  {
    key: "待完成",
    value: 0,
    color: "bg-red-500"
  },
  {
    key: "已完成",
    value: 1,
    color: "bg-green-600"
  },
  {
    key: "部分完成",
    value: 2,
    color: "bg-blue-600"
  }
];

const itemTypeList = ref([
  {
    key: "复查",
    value: 1
  },
  {
    key: "随访",
    value: 2
  },
  {
    key: "日常监测",
    value: 3
  },

  {
    key: "其他",
    value: 0
  }

  // {
  //   key: "检查",
  //   value: 4
  // },

  // {
  //   key: "回访",
  //   value: 5
  // }
]);
const cmps = {
  0: defineAsyncComponent(() => import("./TodoItemOther.vue")), // 其他
  1: defineAsyncComponent(() => import("./TodoItemCheck.vue")), // 复查
  2: defineAsyncComponent(() => import("./TodoItemFollowUp.vue")), // 随访
  3: defineAsyncComponent(() => import("./TodoItemMonitor.vue")), // 监测
  4: defineAsyncComponent(() => import("./TodoItemInspect.vue")), // 检查
  5: defineAsyncComponent(() => import("./TodoItemReturnVisit.vue")) // 回访
};
const calendarRef = ref();
const menus = [
  {
    label: "新增待办事项",
    key: "NewTodoItems",
    auth: "headlthManage:todoList:edit"
  },
  {
    label: "待办事项管理",
    key: "TodoManagement",
    auth: "headlthManage:todoList:edit"
  },
  {
    label: "本月待办处理",
    key: "HandleMonthTodo",
    auth: ""
  }
];
const state = reactive({
  date: moment().format("YYYY-MM"),
  calendarValue: "",
  visibleBacklogHandle: false,
  time: "",
  itemList: {},
  itemDateList: [],
  itemType: 1, // 事项类别
  todoDurationList: [],
  currentDate: moment().format("YYYY-MM-DD")
});
const visibleConfirm = ref(false);
const BacklogConfigListRef = ref();
const currentArchiveId = computed(() => {
  return useManageProjectStoreHook()?.currentArchiveId;
});
watch(
  () => dialogVisible.value,
  n => {
    if (n) {
      initData();
    }
  }
);
const scrollToAnchor = data => {
  // 从完整路径中解析出真正的锚点部分
  const hash = data; // 注意：根据你的URL结构调整索引
  if (hash) {
    const element = document.getElementById(hash);
    if (element) {
      element.scrollIntoView({ behavior: "smooth" });
    }
  }
};

const onLiclick = hash => {
  curMenu.value = "HandleMonthTodo";
  nextTick(() => {
    scrollToAnchor(hash);
  });
  // setTimeout(() => {
  // }, 1000);
  state.currentDate = hash;
};
const formatDot = data => {
  if (!data) return;
  const doneList = data.filter(v => v.done);
  switch (doneList.length) {
    case 0:
      return 0;
    case data.length:
      return 1;
    default:
      return 2;
  }
};
// 计算该月份的天数
const getDaysInMonth = yearMonth => {
  return moment(yearMonth, "YYYY-MM").endOf("month").date();
};

const handleChangeCurMenu = key => {
  curMenu.value = key;
  cmpsRef.value?.onReset();
};
const getList = () => {
  return new Promise(resolve => {
    request
      .get("dataService/schedule/todoList/duration", {
        params: {
          archiveId: currentArchiveId.value,
          startDate: state.date + "-01",
          endDate: `${state.date}-${getDaysInMonth(state.date)}`,
          filter: 1
        }
      })
      .then(resp => {
        const itemObj = {};
        const data = resp.data;
        state.todoDurationList = data;

        data.map(v => {
          itemObj[v.date] = v.schedules;
        });
        state.itemDateList = itemObj;
        resolve();
      });
  });
};
const handleMonth = date => {
  if (!date) return;
  state.calendarValue = date;
  getList();
};
const handleBackToday = async () => {
  calendarRef.value.selectDate("today");
  const time = moment().format("YYYY-MM-DD");
  state.currentDate = time;
  state.date = moment().format("YYYY-MM");
  await getList();
  onLiclick(time);
};
const onSave = () => {
  cmpsRef.value.onSubmit(params => {
    request
      .post("/dataService/schedule", {
        archiveId: currentArchiveId.value,
        type: state.itemType,
        ...params
      })
      .then(resp => {
        ElMessage.success(resp.message);
        cmpsRef.value.onReset();
        visibleConfirm.value = false;
        getList();
        // if (key == "view") {
        //   curMenu.value = "TodoManagement";
        //   BacklogConfigListRef.value.initData();
        // }
        // visibleConfirm.value = false;
      });
  });
};
const formatDateToYearMonth = dateString => {
  return moment(dateString).format("YYYY-MM");
};
const initData = async () => {
  // 如果有值的话 说明是事项处理
  if (props.complateTime) {
    curMenu.value = "HandleMonthTodo";
    state.date = formatDateToYearMonth(props.complateTime);
    state.calendarValue = state.dete;
    await getList();
    setTimeout(() => {
      onLiclick(props.complateTime);
    }, 500);
  } else {
    curMenu.value = "HandleMonthTodo";
    await getList();
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-calendar__button-group {
  display: none;
}
::v-deep .el-calendar-table .el-calendar-day {
  text-align: center;
}
.item-card {
  height: 100%;
}
::v-deep .el-calendar-table .el-calendar-day {
  height: 50px;
  // padding: 10px;
}
::v-deep .el-calendar__body {
  padding: 10px !important;
}
::v-deep .el-calendar__header {
  display: none;
}
::v-deep .el-dialog__header {
  padding: 0px !important;
}
::v-deep .el-dialog__body {
  padding: 0px;
  overflow: hidden;
}
</style>
