<template>
  <div class="flex items-center p-l-small p-r-base common-mark-header">
    <div class="flex items-center" :class="{ 'left-icons-wrap': path !== '/marking/mark' }" style="margin-top: 3px">
      <div v-for="button in usedOperations" :key="button.type" class="btn-item">
        <div
          :ref="(el) => bindRef(button.type, el)"
          class="grid pointer radius-circle operation-button"
          :title="button.title"
          @click="onOperationClick(button)"
        >
          <svg-icon
            :name="attrs['icon-' + button.type] as string || 'mark-' + button.type"
            style="font-size: 18px"
          ></svg-icon>
        </div>
        <p class="icon-title">{{ button.smallTitle || button.title }}</p>
      </div>
    </div>
    <color-picker v-model="frontColor" :virtual-ref="refs['front-color']" virtual-triggering></color-picker>
    <color-picker v-model="backgroundColor" :virtual-ref="refs['background-color']" virtual-triggering></color-picker>

    <div class="flex flex-1 items-center mark-header">
      <slot></slot>
      <div class="data-item">
        <user-info></user-info>
      </div>
      <div class="data-item">
        <div class="icon-item">
          <lock-entry :in-layout="false" />
        </div>
        <div class="icon-item">
          <message
            :reply-user-id="props.replyUserId"
            :paper-path="props.paperPath"
            :secret-number="props.secretNumber"
          ></message>
        </div>
        <!-- <div class="icon-item">
          <user-info></user-info>
        </div> -->
      </div>

      <!-- <div class="grid pointer close-icon" @click="willLogout">
        <el-icon><close /></el-icon>
      </div> -->
    </div>

    <!-- <base-dialog
      v-model="standardVisible"
      class="standard-dialog"
      :can-resize="'can-resize3'"
      title="评分标准"
      modal-class="no-mask"
      center
      :modal="false"
    >
      <div id="my-iframe-mask"></div>
      <iframe
        style="width: 100%; height: 100%; prevent-events: pointer"
        :src="
          standardRes?.url
            ? standardRes?.url + '#view=FitH&scrollbar=0&toolbar=0&statusbar=0&messages=0&navpanes=0'
            : ''
        "
        alt=""
      />
    </base-dialog> -->
    <standard-dialog v-model="standardVisible" :can-resize="'can-resize3'" resize-key="can-resize3"></standard-dialog>
  </div>
</template>

<script setup lang="ts" name="MarkHeader">
import { reactive, ref, computed, useAttrs, watch, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { add, minus } from '@/utils/common'
import useMainStore from '@/store/main'
import useLayoutStore from '@/store/layout'
import SvgIcon from '@/components/common/SvgIcon.vue'
import ColorPicker from '@/components/common/ColorPicker.vue'
import Message from '@/components/shared/message/Message.vue'
import UserInfo from '@/components/shared/UserInfo.vue'
import { ElIcon, ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import { logout } from '@/utils/shared'
import { sessionStorage } from '@/plugins/storage'
// import useFetch from '@/hooks/useFetch'
import BaseDialog from '@/components/element/BaseDialog.vue'
import LockEntry from '../common/LockEntry.vue'
import StandardDialog from '@/components/shared/StandardDialog.vue'
import bus from '@/utils/bus'
type ButtonType =
  | 'back'
  | 'scale-up'
  | 'scale-down'
  | 'center'
  | 'rotate'
  | 'front-color'
  | 'background-color'
  | 'refresh'
  | 'remark'
  | 'problem'
  | 'example'
  | 'standard'
  | 'delete'
  | 'bookmark'

interface HeaderButton {
  title: string
  type: ButtonType
  smallTitle?: string
}

type EventType = Exclude<ButtonType, 'scale-up' | 'scale-down'> | 'scale-change'

const emits = defineEmits<{
  (e: 'click', opt: { type: EventType; value?: number | string | boolean | number[] }): void
  (e: EventType, val: any): void
  (e: 'back'): void
  (e: 'center', val: boolean): void
  (e: 'refresh'): void
  (e: 'remark'): void
  (e: 'problem'): void
  (e: 'example'): void
  (e: 'standard'): void
  (e: 'delete'): void
  (e: 'bookmark'): void
  (e: 'scale-change', val: number): void
  (e: 'rotate', val: number): void
  (e: 'front-color', color: number[]): void
  (e: 'background-color', color: number[]): void
}>()
const standardVisible = ref(false)

const props = defineProps<{
  excludeOperations?: ButtonType[]
  includeOperations?: ButtonType[]
  replyUserId?: number | null
  paperPath?: string | null
  secretNumber?: string | number | null
}>()

const buttons: HeaderButton[] = [
  { title: '返回', type: 'back' },
  { title: '放大', type: 'scale-up' },
  { title: '缩小', type: 'scale-down' },
  { title: '居中', type: 'center' },
  { title: '旋转', type: 'rotate' },
  { title: '前景色', type: 'front-color' },
  { title: '背景色', type: 'background-color' },
  { title: '刷新', type: 'refresh' },
  { title: '回评', type: 'remark' },
  { title: '问题卷', type: 'problem' },
  { title: '查看样卷', type: 'example' },
  { title: '评分标准', type: 'standard' },
  { title: '删除当前专家卷', type: 'delete', smallTitle: '删除' },
  { title: '设置专家卷', type: 'bookmark', smallTitle: '设专家卷' },
]

const refs = reactive<Partial<Record<ButtonType, Element>>>({
  'front-color': void 0,
  'background-color': void 0,
})

const bindRef = (type: ButtonType, el: any) => {
  if (el) {
    refs[type] = el
  }
}

const usedOperations = computed(() => {
  const viewButtons = props?.includeOperations
    ? buttons.filter((b) => props?.includeOperations?.some((t) => b.type === t))
    : buttons
  return viewButtons.filter((button) => !props.excludeOperations?.some((type) => button.type === type))
})

const attrs = useAttrs()

const mainStore = useMainStore()

const { path, fullPath } = useRoute()

const userMarkConfig = computed(() => {
  return mainStore.userMarkConfig?.[fullPath]
})

/** center */
const center = ref<boolean>(false)

/** ratio */
const ratio = ref<number>(1)

/** rotate */
const rotate = ref<number>(0)

/** front-color */
const frontColor = ref<string>('')

/** background-color */
const backgroundColor = ref<string>('')

const saveMarkSet = () => {
  if (fullPath && !!sessionStorage.get('LOGIN_RESULT')) {
    mainStore.setUserMarkConfig({
      [fullPath]: {
        center: center.value,
        ratio: ratio.value,
        rotate: rotate.value,
        frontColor: frontColor.value,
        backgroundColor: backgroundColor.value,
      },
    })
  }
}

watch(center, () => emitEvent('center', center.value))

watch(ratio, () => emitEvent('scale-change', ratio.value))

watch(rotate, () => emitEvent('rotate', rotate.value))

watch(frontColor, () => {
  emitEvent('front-color', frontColor.value)
  saveMarkSet()
})

watch(backgroundColor, () => {
  emitEvent('background-color', backgroundColor.value)
  saveMarkSet()
})

const validVal = (val: number, max: number, min: number) => {
  return Math.min(max, Math.max(val, min))
}

const onOperationClick = (button: HeaderButton) => {
  if (['front-color', 'background-color'].includes(button.type)) {
    return
  }
  switch (button.type) {
    case 'scale-up':
      ratio.value = validVal(add(ratio.value, 0.1), 2, 0.5)
      saveMarkSet()
      break
    case 'scale-down':
      ratio.value = validVal(minus(ratio.value, 0.1), 2, 0.5)
      saveMarkSet()
      break
    case 'rotate':
      rotate.value = (rotate.value + 90) % 360
      saveMarkSet()
      break
    case 'center':
      center.value = !center.value
      saveMarkSet()
      break
    default:
      emitEvent(button.type)
      // saveMarkSet()
      break
  }
}
function busEventHandler() {
  bus.on('scale-up', () => {
    ratio.value = validVal(add(ratio.value, 0.1), 2, 0.5)
    saveMarkSet()
  })
  bus.on('scale-down', () => {
    ratio.value = validVal(minus(ratio.value, 0.1), 2, 0.5)
    saveMarkSet()
  })
  bus.on('init-scale', () => {
    ratio.value = 1
    saveMarkSet()
  })
}
busEventHandler()

const emitEvent = (type: EventType, val?: string | number | boolean | number[]) => {
  if (type === 'standard') {
    standardVisible.value = true
    return
  }
  if (type === 'refresh') {
    if (!mainStore.online) {
      ElMessage.error('您的网络已断开，请检查网络')
      return
    }
  }
  if (attrs['on' + type.replace(/^\S/, (s) => s.toUpperCase())]) {
    emits(type, val as any)
  }
  emits('click', { type: type, value: val })
}

type MarkConfig = {
  center: boolean
  ratio: number
  rotate: number
  frontColor: string
  backgroundColor: string
}

const setCurrentConfig = (config: MarkConfig) => {
  center.value = config.center ?? center.value
  ratio.value = config.ratio ?? ratio.value
  rotate.value = config.rotate ?? rotate.value
  frontColor.value = config.frontColor ?? frontColor.value
  backgroundColor.value = config.backgroundColor ?? backgroundColor.value
}

watch(
  userMarkConfig,
  () => {
    if (userMarkConfig.value) {
      setCurrentConfig(userMarkConfig.value)
    }
  },
  { immediate: true }
)
const willLogout = async () => {
  if (fullPath && !!sessionStorage.get('LOGIN_RESULT')) {
    await mainStore.setUserMarkConfig({
      [fullPath]: {
        center: center.value,
        ratio: ratio.value,
        rotate: rotate.value,
        frontColor: frontColor.value,
        backgroundColor: backgroundColor.value,
      },
    })
    logout()
  } else {
    logout()
  }
}
// onUnmounted(() => {
//   if (fullPath && !!sessionStorage.get('LOGIN_RESULT')) {
//     mainStore.setUserMarkConfig({
//       [fullPath]: {
//         center: center.value,
//         ratio: ratio.value,
//         rotate: rotate.value,
//         frontColor: frontColor.value,
//         backgroundColor: backgroundColor.value,
//       },
//     })
//   }
// })
const layoutStore = useLayoutStore()
onMounted(() => {
  layoutStore.toggleMarkerHeaderLoaded(true)
})
onUnmounted(() => {
  layoutStore.toggleMarkerHeaderLoaded(false)
})
</script>

<style scoped lang="scss">
.common-mark-header {
  height: $MainLayoutHeaderHeight;
  background-color: $MainLayoutHeaderBg;
  :deep(.message-icon) {
    .msg-box {
      .tip {
        color: #999;
      }
    }
  }
  .left-icons-wrap {
    position: relative;
    padding-right: 15px;
    margin-right: 10px;
    &:after {
      content: '';
      position: absolute;
      right: 0;
      height: 100%;
      width: 1px;
      background: #464646;
    }
  }
  .btn-item {
    width: 62px;
    text-align: center;
  }
  .icon-title {
    font-size: 14px;
    transform: scale(0.9);
    color: #8a8a8a;
    margin-top: 5px;
  }
  .operation-button {
    width: 40px;
    height: 40px;
    place-items: center;
    color: $RegularFontColor;
    background-color: rgba(255, 255, 255, 0.1);
    color: #fff;
    margin-left: auto;
    margin-right: auto;
    &:hover {
      background: $color--primary;
      color: $color--white;
    }
  }
  .mark-header {
    margin-left: auto;
    // color: $RegularFontColor;
    height: 100%;
    // color: #999;
    color: #8a8a8a;
    font-size: $SmallFont;
    // font-weight: bold;
    padding: 12px 0;
    ::v-deep(.data-item) {
      // padding-left: 20px;
      padding-left: 15px;
      padding-right: 15px;
      position: relative;
      height: 100%;
      display: flex;
      align-items: center;
      .icon-item {
        // width: 45px;
        padding: 0 10px;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: flex-end;
        padding-bottom: 10px;
      }
      &:first-child {
        margin-left: auto;
      }
      &:not(:last-child) {
        &:after {
          content: '';
          position: absolute;
          right: 0;
          top: 0;
          width: 1px;
          height: 100%;
          background-color: #464646;
        }
      }
      // &:not(:last-child):after {
      //   content: '';
      //   margin-left: 20px;
      //   display: inline-block;
      //   width: 1px;
      //   height: 16px;
      //   vertical-align: middle;
      //   background-color: #eeeeee;
      // }
      &.is-last:after {
        width: 0;
      }
      .main-ques-info {
        text-align: center;
        font-weight: bold;
        color: $color--primary;
        margin-bottom: 5px;
        max-width: 130px;
      }
    }

    .close-icon {
      width: 32px;
      height: 32px;
      margin-left: 10px;
      font-size: 1.4em;
      border-radius: 50%;
      place-items: center;
      color: #ccc;
      transition: all 0.3s ease-in-out;
      background-color: #222;
      &:hover {
        color: #fff;
        font-weight: bold;
        background-color: rgba(255, 255, 255, 0.1);
      }
    }
  }
}
</style>
//
<style lang="scss">
// .standard-dialog {
//   display: flex;
//   flex-direction: column;
//   .el-dialog__body {
//     flex: 1;
//     padding: 2px !important;
//     position: relative;
//     max-height: 150vh !important;
//   }
//   .el-dialog__footer {
//     padding: 0 !important;
//   }
//   #my-iframe-mask {
//     position: absolute;
//     left: 0;
//     right: 0;
//     bottom: 0;
//     top: 0;
//     z-index: 10;
//     display: none;
//   }
// }
//
</style>
