<template>
  <div>
    <div class="mx-2 my-4 wrap" :style="{ maxWidth: isEdit ? 'calc(100vw - 19.6vw)' : '' }">
      <div class="flex">
        <h1>排床</h1>
        <div>
          <a-button @click="handleEdit">编辑</a-button>
        </div>
      </div>
      <div class="my-4 filter">
        <div>
          <XTForm :form-data="formData" @change="callFilter" />
        </div>
      </div>
      <div class="detail">
        <div class="aside">
          <div class="aside-item aside-item--tit">床位</div>
          <div class="mb-2 aside-item" v-for="b in bed" :key="b.bed">
            <div class="aside-item_bed">{{ b.bed }}</div>
            <div class="aside-item_robot">
              <i class="iconfont icon-xt-dual-pump_default" v-if="b.double" />
              <span>{{ b.robot }}</span>
            </div>
          </div>
        </div>
        <div class="content" ref="scrollEl">
          <div>
            <div
              ref="headEl"
              :class="[
                'mb-2 content-head',
                Number(refY) > 100 ? 'content-head--fixed' : '',
                isEdit && Number(refY) > 100 ? 'content-head--edit' : '',
              ]"
            >
              <div
                class="head-item animate__animated animate__slideInLeft"
                v-for="h in head"
                :key="h.monthDay"
              >
                <div :class="['head-item_time', h.current ? 'head-item_time--current' : '']">
                  <span class="head-item_time-week">{{ h.week }}</span>
                  <span class="head-item_time-day">({{ h.monthDay }})</span>
                </div>
                <div class="head-item_sailings">
                  <div
                    :class="[
                      'head-item_sailings-item',
                      filter.sailings ? 'head-item_sailings-item--only' : '',
                    ]"
                    v-for="c in h.count"
                    :key="c"
                  >
                    {{ c }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div :class="['content-body', Number(refY) > 100 ? 'content-body--fixed' : '']">
            <div class="flex mb-2" v-for="(c, cIdx) in cnt" :key="c.id">
              <div class="flex items-center" v-if="c.bed == bed[cIdx].bed">
                <div class="body-list" v-for="(sa, idx) in c.sailings" :key="idx">
                  <div
                    v-for="person in sa"
                    :key="person.key"
                    :class="[
                      'animate__animated animate__slideInLeft',
                      'body-list_item',
                      person.show ? '' : 'body-list_item--hidden',
                      filter.sailings && person.show ? 'body-list_item--only' : '',
                      setClass(person),
                    ]"
                    @click="handlePerson(person)"
                    @dblclick="handleDbPerson(person)"
                  >
                    <!-- <div>testt</div> -->
                    <div>{{ person.name }} </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="edit animate__animated animate__slideInRight" v-if="isEdit">
      <!-- {{ refX }} {{ refY }}
      {{ headX }}
      {{ Number(refX) > 100 }} -->
      <div class="edit-tit"> 本周排床编辑 </div>
      <div class="edit-cnt">
        <div class="edit-cnt_tit">未排床</div>
        <div class="edit-cnt_detail">
          <div
            v-for="item in bedNot"
            :key="item.id"
            :class="['edit-item', item.id == notBedId ? 'edit-item--not' : '']"
            @click="handleNotBed(item)"
          >
            <div> {{ item.name }}</div>
            <div class="edit-item_count"> {{ item.count }}次</div>
          </div>
        </div>
      </div>
      <div class="edit-cnt">
        <div class="edit-cnt_tit">已排床</div>
        <div class="mb-2">
          <Select
            show-search
            allow-clear
            class="w-full"
            @search="searchBed"
            @change="changeBed"
            placelholder="搜索需要排班的患者"
            :options="bedNot"
            v-model:value="searchBedField"
          >
            <template #suffixIcon>
              <i class="iconfont icon-xt-search ant-select-suffix" />
            </template>
          </Select>
        </div>
        <div class="edit-cnt_detail">
          <div
            v-for="item in bedHas"
            :key="item.id"
            :class="['edit-item', item.id == hasBedId ? 'edit-item--has' : '']"
            @click="handleHasBed(item)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="flex items-center edit-foot">
        <a-button class="edit-foot_btn" type="default" @click="handleReset">取消</a-button>
        <a-button class="edit-foot_btn" disabled type="primary" @click="handleSubmit"
          >保存</a-button
        >
      </div>
      <!-- <a-button @click="scrollX += 10"> Scroll right 10px </a-button> -->
      <!-- <a-button @click="scrollY += 10"> Scroll down 10px </a-button> -->
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, onMounted, watch } from 'vue';
  import dayjs from 'dayjs';
  import { defaultHead, defaultBed, defaultData } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { XTForm } from '/@/components/XTForm';
  import _ from 'lodash-es';
  import { useMenuSetting } from '/@/hooks/setting/useMenuSetting';
  // import { useScroll } from '/@/hooks/event/useScroll';
  import { useScroll, useThrottleFn } from '@vueuse/core';
  import { Select } from 'ant-design-vue';

  const { getCollapsed, toggleCollapsed } = useMenuSetting();
  onMounted(() => {
    if (getCollapsed) {
      toggleCollapsed();
    }
    // 滚动到指定位置
    scrollTo(0, 1);
    // const scrollId = document.querySelector('.content');
    // console.log('🚀 ~ file: index.vue:133 ~ onMounted ~ scrollId:', scrollId);
    // scrollId.addEventListener('scroll', function (e) {
    //   console.log('e', e.target);
    // });
  });
  // console.log('🚀 ~ file: index.vue:51 ~ defaultHead:', defaultHead());
  // console.log('🚀 ~ file: index.vue:51 ~ defaultBed:', defaultBed());
  // console.log('🚀 ~ file: index.vue:51 ~ defaultData:', defaultData());
  // console.log('🚀 ~ file: index.vue:51 ~ dayjs:', dayjs().day());
  // console.log('🚀 ~ file: index.vue:51 ~ dayjs:', defaultHead());
  // console.log('🚀 ~ file: index.vue:51 ~ dayjs:', dayjs().day(1).format('MM-DD'));
  const { createMessage } = useMessage();
  const head = ref(defaultHead());
  console.log('🚀 ~ file: index.vue:181 ~ head:', head.value);
  const bed = defaultBed();
  console.log('🚀 ~ file: index.vue:181 ~ bed:', bed);

  const cnt = ref(defaultData());
  console.log('🚀 ~ file: index.vue:186 ~ cnt.value:', cnt.value);
  const notBedId = ref('');
  const hasBedId = ref('');
  const filter = ref({}) as any;
  const isEdit = ref(false);
  const searchBedField = ref('');
  const customWeekStartEndFormat = value =>
    `${dayjs(value).startOf('week').format('YYYY-MM-DD')} ~ ${dayjs(value)
      .endOf('week')
      .format('YYYY-MM-DD')}`;
  const disabledDate = (current: any) => {
    // Can not select days before today and today
    return current && current > dayjs().endOf('month');
  };
  // scroll
  const scrollEl = ref(null);
  const headEl = ref(null);
  const { x: scrollX } = useScroll(scrollEl, { behavior: 'smooth' });
  const { y: scrollY } = useScroll(document.body, { behavior: 'smooth' });
  const { x: headX } = useScroll(headEl, { behavior: 'smooth' });
  const refY = computed({
    get() {
      return scrollY.value.toFixed(1);
    },
    set(val) {
      scrollY.value = parseFloat(val);
    },
  });
  // 滚动到指定位置
  function scrollTo(x, y) {
    console.log('🚀 ~ file: index.vue:177 ~ scrollTo ~ x:', x);
    // scrollX.value = (x - 1) * 54 * 3;
    scrollX.value = x > 3 ? 300 : 0;
    if (isEdit.value && scrollY.value > 100) {
      headX.value = x > 3 ? 300 : 0;
    }
    if (y == null) return;
    scrollY.value = (y - 1) * 54 + (y - 2) * 10 + (y > 10 ? 90 : 110);
  }
  // 监听编辑状态下的页面竖向滚动
  watch(
    () => scrollY.value,
    () => {
      scrollThrott();
    },
  );
  // 节流操作
  const scrollThrott = useThrottleFn(() => {
    if (isEdit.value && scrollY.value > 100) {
      headX.value = scrollX.value > 100 ? 107 : 0;
    }
  }, 500);

  // const refX = computed(() => {
  //   console.log('x', scrollX.value);
  //   return scrollX.value.toFixed(1);
  // });

  // const { x, y } = useScroll(document.body);

  // scroll
  const bedNot = [
    {
      id: 'n1',
      name: '王雪（女｜38）',
      label: '王雪（女｜38）',
      count: 1,
    },
    {
      id: 'n2',
      name: '测试456456',
      label: '测试456456',
      count: 1,
    },
    {
      id: 'n3',
      name: '测试456456',
      label: '测试123123',
      count: 1,
    },
    {
      id: 'n4',
      name: '测试456456',
      label: '测试456456',
      count: 3,
    },
    {
      id: 'n5',
      name: '测试456456',
      label: '测试123123',
      count: 1,
    },
    {
      id: 'n6',
      name: '测试456456',
      label: '测试456456',
      count: 2,
    },
    {
      id: 'n123123',
      name: '测试456456',
      label: '测试123123',
      count: 1,
    },
    {
      id: 'n456456',
      name: '测试456456',
      label: '测试456456',
    },
  ];
  const bedHas = [
    {
      id: 'h123123',
      name: '测试123123',
    },
    {
      id: 'h456456',
      name: '测试456456',
    },
  ];
  // formdata
  const formData = [
    {
      name: 'date',
      componentType: 'DatePicker',
      placeholder: '请输入',
      format: customWeekStartEndFormat,
      disabledDate: disabledDate,
      valueFormat: 'YYYY-MM-DD',
      picker: 'week',
      width: 300,
    },
    {
      name: 'sailings',
      componentType: 'Select',
      placeholder: '请选择',
      width: 120,
      defaultValue: 0,
      // label: '班次',
      dicts: [
        { label: '全部班次', value: 0 },
        { label: '第一班', value: 1 },
        { label: '第二班', value: 2 },
        { label: '第三班', value: 3 },
      ],
    },
  ];

  function handleNotBed(data) {
    notBedId.value = data.id;
    hasBedId.value = null;
    setCnt();
  }
  function handleHasBed(data) {
    hasBedId.value = data.id;
    notBedId.value = null;
    setCnt();
  }
  function callFilter(data) {
    console.log('🚀 ~ file: index.vue:173 ~ callFilter ~ data:', data);
    if (data.sailings || data.sailings == 0) {
      console.log('修改班次', data.sailings);
      filter.value.sailings = data.sailings;
      setCnt(1);
      head.value = head.value.map(ele => {
        const count = ['第一班', '第二班', '第三班'];
        ele.count = data.sailings == 0 ? count : _.slice(count, data.sailings - 1, data.sailings);
        return ele;
      });
      console.log(
        '🚀 ~ file: index.vue:97 ~ handleNotBed ~ cnt.value :',
        cnt.value[0]['sailings'][0],
      );
    }
    if (data.date) {
      filter.value.date = customWeekStartEndFormat(data.date).split('~');
      console.log('🚀 ~ file: index.vue:214 ~ callFilter ~ filter.value.date:', filter.value.date);
    }
  }
  // 设置数据
  function setCnt(type?: number) {
    console.log('🚀 ~ file: index.vue:391 ~ setCnt ~ cnt.value:', cnt.value);
    cnt.value = cnt.value.map(ele => {
      ele.sailings = ele.sailings.map(cele => {
        return cele.map((sele, idx) => {
          if (type == 1) {
            if (filter.value.sailings == 0) {
              sele.show = true;
              return sele;
            }
            if (filter.value.sailings != 0 && filter.value.sailings - 1 == idx) {
              sele.show = true;
              return sele;
            } else {
              sele.show = false;
              return sele;
            }
          } else {
            sele.edit = true;
            if (sele.old) {
              sele.disabled = true;
            } else {
              sele.disabled = sele.name && !sele.empty ? true : false;
            }
            return sele;
          }
        });
      });
      return ele;
    });
  }
  // 设置 class
  function setClass(data) {
    if (data.disabled) {
      return 'body-list_item--disabled';
    } else if (data.empty && data.selected && data.edit) {
      return 'body-list_item--selected';
    } else if (data.empty && data.actived && data.edit) {
      return 'body-list_item--actived';
    } else if (!data.disabled && data.empty && data.edit) {
      return 'body-list_item--select';
    } else if (data.old) {
      return 'body-list_item--old';
    } else if (data.empty && data.actived) {
      return 'body-list_item--actived';
    } else if (!data.name && data.empty) {
      return 'body-list_item--empty';
    }
  }
  // 双击查看详情
  function handleDbPerson(data) {
    console.log('🚀 ~ file: index.vue:136 ~ data:', data);
    createMessage.info(
      `查看详情: 床位: ${data.x}, 时间: ${data.y}, 班次: ${data.z + 1}, ${
        data.empty ? '空床' : data.name
      }${notBedId.value ? ', 未排床: ' + notBedId.value : ''}`,
    );
    console.log('cnt.value', cnt.value);
  }
  // 单击选中
  function handlePerson(data) {
    console.log('🚀 ~ file: index.vue:336 ~ handlePerson ~ data:', data);
    if (data.disabled) return;
    if (notBedId.value) {
      cnt.value[data.x]['sailings'][data.y - 1][data.z]['selected'] = true;
    }
    if (hasBedId.value) {
      cnt.value[data.x]['sailings'][data.y - 1][data.z]['actived'] = true;
    }
    scrollTo(data.y, null);
    createMessage.info(
      `床位: ${data.x}, 时间: ${data.y}, 班次: ${data.z + 1}, ${data.empty ? '空床' : data.name}${
        notBedId.value ? ', 未排床: ' + notBedId.value : ''
      }`,
    );
  }
  // 取消
  function handleReset() {
    notBedId.value = null;
    hasBedId.value = null;
    cnt.value = defaultData();
    handleEdit();
  }
  // 提交
  function handleSubmit() {
    createMessage.success('提交成功');
  }
  // 编辑状态
  function handleEdit() {
    isEdit.value = !isEdit.value;
    if (!getCollapsed.value || !isEdit.value) {
      toggleCollapsed();
    }
  }
  function searchBed(val) {
    console.log('🚀 ~ file: index.vue:443 ~ searchBed ~ val:', val);
  }
  function changeBed(val) {
    console.log('🚀 ~ file: index.vue:443 ~ changeBed ~ val:', val);
  }
</script>

<style lang="less" scoped>
  // .wrap {
  // }

  .detail {
    display: flex;
  }

  .aside {
    &-item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: calc(100vw - 95.5vw);
      height: 54px;
      border-radius: 4px 0 0 4px;

      &--tit {
        text-align: center;
        font-size: 14px;
        font-weight: 400;
        color: #818694;
        margin-bottom: 0;
      }

      &_bed {
        font-size: 14px;
        font-weight: 600;
        color: #000a18;
      }

      &_robot {
        display: flex;
        font-size: 12px;
        font-weight: 400;
        color: #818694;
        align-items: center;

        .iconfont {
          color: #0075ff;
          margin-right: 2px;
        }
      }
    }
  }

  .content {
    display: flex;
    flex-direction: column;
    // max-width: calc(100vw - 430px);
    overflow: scroll;

    &-head {
      display: flex;
      background-color: #f0f2f5;

      &--fixed {
        position: fixed;
        top: 48px;
        z-index: 8;
        padding-bottom: 4px;
      }

      &--edit {
        width: calc(100vw - 488px);
        overflow-x: auto;

        &::-webkit-scrollbar {
          display: none;
        }
      }
    }

    &-body {
      display: flex;
      flex-direction: column;

      &--fixed {
        padding-top: 54px;
      }
    }
  }

  .body {
    &-list {
      display: flex;

      &_item {
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        padding: 0 10px;
        width: calc(100vw - 95.5vw);
        height: 54px;
        text-align: center;
        background: #fff;
        margin-right: 1px;
        cursor: pointer;
        color: #000a18;
        transition: all 0.3s ease-in-out;

        &:last-child {
          margin-right: 10px;
          border-radius: 0 4px 4px 0;
        }

        &:first-child {
          border-radius: 4px 0 0 4px;
        }

        &:hover {
          transform: scale(1.1);
          background: #fff;
          box-shadow: 0 0 20px 0 rgb(0 37 74 / 12%);
          border-radius: 4px;
        }

        &--empty {
          background-color: #eaedf3;

          &:hover {
            background-color: #eaedf3;
          }
        }

        &--only {
          border-radius: 4px;
          width: 246px;
          margin-right: 10px;
        }

        &--old {
          color: #c3cdd8;
        }

        &--selected {
          background-color: rgb(239 255 251 / 100%);
          border: 1px dashed rgb(68 215 182 / 100%);

          &:hover {
            background-color: rgb(239 255 251 / 100%);
          }
        }

        &--actived {
          background-color: rgb(233 246 255 / 100%);
          border: 1px dashed rgb(0 109 255 / 100%);

          &:hover {
            background-color: rgb(233 246 255 / 100%);
          }
        }

        &--disabled {
          color: #c3cdd8;
          background: #eaedf3;
          cursor: not-allowed;

          &:hover {
            transform: scale(1);
            color: #c3cdd8;
            background: #eaedf3;
          }
        }

        &--select {
          background: #fff;
        }

        &--hidden {
          display: none;
        }
      }
    }
  }

  .head {
    &-item {
      margin-right: 10px;

      &:last-child {
        margin-right: 0;
      }

      &_time {
        text-align: center;
        color: #000a18;
        margin-bottom: 6px;

        &-week {
          font-size: 14px;
          font-weight: 600;
          margin-right: 6px;
        }

        &-day {
          font-size: 12px;
          font-weight: 400;
          color: #818694;
        }

        &--current {
          color: #0075ff;

          .head-item_time-day {
            color: #0075ff;
          }
        }
      }

      &_sailings {
        display: flex;

        &-item {
          width: calc(100vw - 95.5vw);
          font-size: 12px;
          font-weight: 400;
          color: #818694;
          text-align: center;
          margin-right: 1px;
          // background-color: #ccc;
          &:last-child {
            margin-right: 0;
          }

          &--only {
            width: 246px;
          }
        }
      }
    }
  }

  .edit {
    position: fixed;
    top: 60px;
    right: 20px;
    min-width: 250px;
    height: calc(100vh - 120px);
    padding: 14px 0;
    background-color: #fff;
    border-radius: 4px;
    z-index: 9;

    &-tit {
      padding: 0 20px 14px;
      font-size: 16px;
      font-weight: 600;
      color: #000a18;
      border-bottom: 1px solid #e1e5ea;
    }

    &-cnt {
      height: calc(100vh - 580px);
      padding: 20px;

      &_detail {
        height: 100%;
        overflow-y: auto;
      }

      &_tit {
        position: relative;
        padding-bottom: 10px;
        padding-left: 6px;
        font-size: 14px;
        font-weight: 600;
        color: #000a18;

        &::after {
          position: absolute;
          top: 6px;
          left: 0;
          content: '';
          width: 2px;
          height: 12px;
          background: #000a18;
          border-radius: 1px;
        }
      }
    }

    &-foot {
      position: absolute;
      bottom: 0;
      width: 100%;
      padding: 14px 20px;
      border-top: 1px solid #e1e5ea;
      display: flex;
      justify-content: space-between;

      &_btn {
        width: 45%;
      }
    }

    &-item {
      min-width: 210px;
      height: 40px;
      line-height: 40px;
      background: #f4f6f9;
      border-radius: 4px;
      margin-bottom: 10px;
      padding: 0 12px;
      cursor: pointer;
      font-size: 14px;
      font-weight: 500;
      color: #000a18;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &_count {
        font-size: 12px;
        font-weight: 400;
        color: #818694;
      }

      &--not {
        background: #effffb;
        border: 1px dashed #44d7b6;
      }

      &--has {
        background: #e9f6ff;
        border: 1px dashed #006dff;
      }
    }
  }
</style>
