<template>
  <MainPanel>
    <template v-slot:header>
      <Header title="现场绘图 | 制表" :on-back="onBack" type="return">
        <ui-button type="primary" @click="saveHandler" width="96px"> 完成 </ui-button>
      </Header>
    </template>

    <div class="tab-layout" v-if="roadPhoto" :class="{ downMode }">
      <div class="content" ref="layoutRef">
        <table>
          <tr>
            <td class="value title" colspan="6" height="46">
              <span v-if="downMode">{{ roadPhoto.title }}</span>
              <ui-input
                v-else
                type="text"
                @input="input"
                v-model="roadPhoto.title"
                @blur="history.push"
              />
            </td>
          </tr>
          <tr>
            <td class="label" width="218" height="40">到达事故现场时间</td>
            <td class="value">
              <span v-if="downMode">{{ history.value.arrivalTime }}</span>
              <ui-input
                v-else
                type="text"
                @input="input"
                v-model="history.value.arrivalTime"
                @blur="history.push"
              />
            </td>
            <td class="label" width="100">天气</td>
            <td class="value" width="116">
              <span v-if="downMode">{{ history.value.weather }}</span>
              <ui-input
                v-else
                type="text"
                @input="input"
                v-model="history.value.weather"
                @blur="history.push"
              />
            </td>
            <td class="label" width="100">路面性质</td>
            <td class="value" width="150">
              <span v-if="downMode">{{ history.value.conditions }}</span>
              <ui-input
                v-else
                type="text"
                @input="input"
                v-model="history.value.conditions"
                @blur="history.push"
              />
            </td>
          </tr>
          <tr>
            <td class="label" height="40">事故发生地点</td>
            <td class="value" colspan="5">
              <span v-if="downMode">{{ history.value.location }}</span>
              <ui-input
                v-else
                type="text"
                @input="input"
                v-model="history.value.location"
                @blur="history.push"
              />
            </td>
          </tr>
          <tr>
            <td class="image" colspan="6" height="569">
              <div class="photo-layout">
                <ui-icon type="reset" class="reset" @click="resetHandler" />
                <img
                  :src="useStaticUrl(roadPhoto.url).value"
                  @blur="history.push"
                  class="photo"
                  :style="{ transform: photoCSSMatrix }"
                  ref="photoRef"
                />
                <img
                  src="/static/compass.png"
                  class="compass"
                  :style="{ transform: compassCSSMatrix }"
                  ref="compassRef"
                />
                <!-- <p class="compass-info">比例1 : {{ proportion }}</p> -->
              </div>
            </td>
          </tr>
          <tr>
            <td class="value textarea-layout" colspan="6" height="62">
              <span v-if="downMode">{{ history.value.illustrate }}</span>
              <ui-input
                class="textarea"
                v-else
                type="textarea"
                @input="input"
                v-model="history.value.illustrate"
                @blur="history.push"
                :maxlength="120"
              />
            </td>
          </tr>
          <tr>
            <td class="value date" colspan="6" height="44">
              绘图时间：{{ formatDate(new Date(), "yyyy年MM月dd日hh时mm分") }}
            </td>
          </tr>
        </table>
        <div class="signatures">
          <p class="signature">勘察员：</p>
          <p class="signature">绘图员：</p>
          <p class="signature">当事人签字：</p>
          <p class="signature">见证人签字：</p>
        </div>
      </div>
    </div>
  </MainPanel>
</template>

<script setup lang="ts">
import { router, writeRouteName } from "@/router";
import { formatDate } from "@/utils";
import { computed, nextTick, onDeactivated, ref, watchEffect } from "vue";
import { useHistory } from "@/hook/useHistory";
import { roadPhotos, RoadPhoto, getDefaultTable } from "@/store/roadPhotos";
import { useStaticUrl } from "@/hook/useStaticUrl";
import html2canvas from "html2canvas";
import UiButton from "@/components/base/components/button/index.vue";
import UiInput from "@/components/base/components/input/index.vue";
import { HandMode, useHand } from "@/hook/useHand";
import Header from "@/components/photos/header.vue";
import MainPanel from "@/components/main-panel/index.vue";
import { downloadImage, uploadImage } from "@/store/sync";
import { Mode } from "@/views/graphic/menus";
import Message from "@/components/base/components/message/message.vue";
import matruces from "@/utils/matruces";
import { genUseLoading } from "@/hook";

const roadPhoto = computed<RoadPhoto>(() => {
  let route, params, data;
  if (
    (route = router.currentRoute.value).name === writeRouteName.tabulation &&
    (params = route.params).id &&
    (data = roadPhotos.value.find((data) => data.id === params.id))
  ) {
    return data;
  } else {
    // router.back();
  }
});
const history = computed(
  () => roadPhoto.value && useHistory(getDefaultTable(roadPhoto.value))
);

const input = () => (history.value.state.hasRedo = false);

const compassRef = ref<HTMLImageElement>();
const { cssMatrix: compassCSSMatrix, matrix: compassMatrix } = useHand(
  compassRef,
  HandMode.Angle,
  () => {
    history.value.value.compassAngle = compassMatrix.value;
    history.value.push();
  },
  history.value.value.compassAngle
);
const photoRef = ref<HTMLImageElement>();
const { cssMatrix: photoCSSMatrix, matrix: photoMatrix } = useHand(
  photoRef,
  HandMode.MoveAndScale,
  () => {
    history.value.value.imageTransform = photoMatrix.value;
    history.value.push();
  },
  history.value.value.imageTransform
);

const resetHandler = () => {
  photoMatrix.value = matruces.translateMatrix(0, 0, 0);
  history.value.value.imageTransform = photoMatrix.value;
  history.value.push();
};

onDeactivated(() => (photoLoaded.value = false));
const proportion = ref(1);
const photoLoaded = ref(false);
watchEffect(() => {
  if (!roadPhoto.value || !photoRef.value) {
    return;
  }
  if (!photoLoaded.value) {
    photoRef.value.onload = () => (photoLoaded.value = true);
    return;
  }
  const scale = roadPhoto.value.data.scale / window.devicePixelRatio || 1;
  const martrixScale = photoMatrix.value[0];
  const photoWidth = photoRef.value.naturalWidth;
  const prop = ((photoWidth / photoRef.value.offsetWidth) * scale) / martrixScale;
  proportion.value = Math.ceil(1 / prop);
});

const onBack = () => {
  router.back();
  // router.replace({
  //   name: writeRouteName.graphic,
  //   params: { mode: Mode.Road, id: roadPhoto.value.id, action: "update" },
  // });
};

const downMode = ref(false);
// const downMode = ref(true);
const layoutRef = ref<HTMLDivElement>();
const getLayoutImage = async () => {
  downMode.value = true;
  await nextTick();
  const canvas = await html2canvas(layoutRef.value);
  Message.success({ msg: "已保存至相册", time: 2000 });
  downMode.value = false;
  const blob = await new Promise<Blob>((resolve) =>
    canvas.toBlob(resolve, "image/jpeg", 0.95)
  );
  await downloadImage(blob, roadPhoto.value.id + ".jpg");
  return await uploadImage(blob);
};

const saveHandler = genUseLoading(async () => {
  let index = 1;
  let prex = "未命名";
  while (true) {
    if (roadPhotos.value.some((road) => road.title === `${prex}${index}`)) {
      index++;
    } else {
      break;
    }
  }

  roadPhoto.value.title = roadPhoto.value.title.trim() || `${prex}${index}`;
  // const repeatIndex = roadPhotos.value.findIndex(
  //   (road) => road !== roadPhoto.value && road.title === roadPhoto.value.title
  // );
  // if (~repeatIndex && !(await useConfirm("检测到您有相同文件名的文件，确定要覆盖吗？"))) {
  //   return;
  // }
  // if (~repeatIndex) {
  //   roadPhotos.value.splice(repeatIndex, 1);
  // }

  roadPhoto.value.table = {
    ...history.value.value,
    url: await getLayoutImage(),
  };
  router.replace({ name: writeRouteName.roads, params: { type: "table" } });
});
</script>

<style lang="scss" scoped>
.tab-layout {
  position: absolute;
  top: calc(var(--header-top) + var(--editor-head-height));
  bottom: 0;
  overflow-y: auto;
  left: 0;
  right: 0;

  font-family: sr, st;
  color: #000;
  font-size: 20px;
}

.content {
  width: 100%;
  padding: 20px 20px 60px;
  margin: 0 auto;
}

.image {
  position: relative;
  .photo-layout {
    position: absolute;
    left: 0px;
    right: 0px;
    bottom: 0px;
    top: 0px;
    overflow: hidden;
    display: flex;
    justify-content: center;

    .photo {
      max-width: 100%;
      max-height: 100%;
      align-items: center;
    }
    .compass {
      top: 20px;
    }
    .compass,
    .compass-info {
      position: absolute;
      right: 20px;
      width: 128px;
      height: 128px;
      top: 20px;
    }
    .compass-info {
      text-align: center;
      color: #000;
      font-size: 16px;
      margin-top: 128px;
      pointer-events: none;
      white-space: nowrap;
    }
  }
}

.content table {
  width: calc(100% - 2px);
  // height: 800px;
  border-collapse: collapse;

  tr:not(:first-child) {
    &:nth-child(2) td {
      border-top: 2px solid #000;
    }

    td:first-child {
      border-left: 2px solid #000;
    }
    td {
      border-right: 2px solid #000;
      border-bottom: 2px solid #000;
    }
  }

  .label {
    text-align: center;
  }

  .value {
    height: 43px;
    background-color: #d4e8ff;
  }

  .title {
    padding-bottom: 7px;
    position: relative;

    &:after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 8px;
      background-color: #fff;
    }
  }

  .date {
    text-align: right;
    padding-right: 44px;
  }

  .reset {
    position: absolute;
    left: 24px;
    top: 24px;
    z-index: 99;
    width: 32px;
    height: 32px;
    background: #ffffff;
    color: #000;
    box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.5);
    border-radius: 55px 55px 55px 55px;
    opacity: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #000;
  }
}

.downMode {
  .reset {
    display: none !important;
  }
  .title {
    span {
      height: 52px !important;
      font-size: 46px !important;
      font-weight: 400;
      color: #000000;
      line-height: 52px;
      letter-spacing: 10px;
    }
  }

  .content {
    width: 1485px;
    height: 1050px;
    padding: 125px 100px 75px 100px;
    // padding: 30px 28px 26px;
    overflow: hidden;
  }
  .content table .textarea-layout {
    height: 60px;
    span {
      padding: 5px 0px;
      display: block;
      height: 100%;
    }
  }
  .content table {
    .value {
      background: none;
    }

    tr:not(:first-child) {
      td {
        border-right: 1px solid #000;
        border-bottom: 1px solid #000;
      }

      &:nth-child(2) td {
        border-top: 2px solid #000;
      }

      td:first-child {
        border-left: 2px solid #000;
      }
      td:last-child {
        border-right: 2px solid #000;
      }

      &:last-child td {
        border-bottom: 2px solid #000;
      }
    }
  }
}

.signatures {
  margin-top: 10px;
  display: flex;
  font-size: 16px;

  .signature {
    flex: 1;
  }
}
</style>

<style lang="scss">
.value {
  box-sizing: border-box;
  // padding: 8px 10px;
  padding: 0 10px;
  input,
  .ui-input {
    width: 100%;
    height: 32px !important;
    outline: none !important;
    color: #000 !important;
    border: 1px #000 dotted !important;
    font-size: 16px !important;
    line-height: 32px !important;
    vertical-align: middle !important;
  }
}

.title {
  span {
    display: block;
    font-size: 32px !important;
    height: 48px !important;
    font-weight: 400;
    text-align: center;
    line-height: 48px !important;
  }
  input,
  .ui-input {
    font-size: 32px !important;
    height: 48px !important;
    font-weight: bold;
    text-align: center;
    line-height: 48px !important;
  }
}
.textarea {
  textarea {
    color: #000 !important;
    font-size: 16px !important;
    line-height: 1.2em;
  }
}

.textarea-layout {
  .textarea {
    height: 100% !important;
  }
  .retouch {
    justify-content: flex-end !important;
    .len {
      color: #000 !important;
    }
  }
}
</style>
