<template>
  <a-config-provider :locale="getAntdLocale">
    <a-modal
      :visible="visible"
      :title="!room ? t('room.createRoom') : t('room.editRoom')"
      :after-close="onCancel"
      width="912px"
      :style="{
        top: '10px',
        minWidth: '912px'
      }"
      @cancel="visible = false"
    >
      <template #footer>
        <a-button class="action-bottom" size="middle" @click="visible = false">
          {{ t('base.cancel') }}
        </a-button>
        <a-button
          class="action-bottom"
          type="primary"
          size="middle"
          @click="saveRoom"
        >
          {{ t('base.save') }}
        </a-button>
        <!-- <a-button
        v-if="room"
        class="action-bottom"
        type="primary"
        size="middle"
        @click="startSync"
      >
        开始带看
      </a-button> -->
      </template>
      <div class="edit-room-layout">
        <div class="scene">
          <iframe
            v-if="current.scenes.length"
            :src="`${mainURL}/smg.html?m=${current.scenes[0].num}&mobile=true&lang=${returnLocale}`"
            frameborder="0"
          />
          <img v-else :src="unScenePng" />
        </div>
        <a-form
          ref="formRef"
          class="info"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
          :model="current"
        >
          <h4>{{ t('room.roomInfo') }}</h4>
          <a-form-item
            :label="t('room.form.title')"
            name="title"
            :rules="[{ required: true, message: t('room.form.titleRequired') }]"
          >
            <a-input
              v-model:value.trim="current.title"
              :placeholder="t('room.form.titleplaceHolder')"
              :maxlength="15"
              show-count
              :disabled="isRoomEnd"
            />
          </a-form-item>
          <a-form-item :label="t('room.form.desc')" name="desc">
            <a-textarea
              v-model:value="current.desc"
              :placeholder="t('room.form.descplaceHolder')"
              :maxlength="200"
              show-count
              :disabled="isRoomEnd"
            />
          </a-form-item>
          <h4>{{ t('room.form.host') }}</h4>
          <a-form-item
            :label="t('room.form.nickname')"
            name="leaderName"
            :rules="[
              { required: true, message: t('room.form.nicknameRequired') },
              { validator: handleNickRegex }
            ]"
          >
            <a-input
              v-model:value.trim="current.leaderName"
              :placeholder="t('room.form.nicknameDesc')"
              :maxlength="15"
              show-count
              :disabled="isRoomEnd"
            />
          </a-form-item>
          <h4>{{ t('room.form.selectScene') }}</h4>
          <a-form-item
            :label="t('room.form.addScene')"
            class="select-scene"
            name="scenes"
            style="margin-bottom: 2px"
          >
          </a-form-item>
          <EditScenes
            :class="{ disabled: isRoomEnd }"
            :scenes="current.scenes"
            @delete="deleteScene"
            @insert="scene => current.scenes.push(scene)"
          />
          <h4>{{ t('room.form.advanceConfig') }}</h4>
          <a-form-item
            label="使用时间"
            class="select-scene"
            name="useTimeList"
            style="margin-bottom: 2px"
            :rules="[{ required: true, message: `请输入房间使用时间` }]"
          >
            <a-range-picker
              :show-time="{ format: 'HH:mm' }"
              format="YYYY-MM-DD HH:mm:ss"
              style="width: 80%"
              :disabled="isRoomEnd"
              v-model:value="current.useTimeList"
            />
          </a-form-item>

          <a-form-item
            label="设置密码"
            name="visitPassword"
            style="margin-bottom: 2px"
          >
            <v-otp-input
              v-model:value="current.visitPassword"
              class="otp-container"
              input-classes="otp-input"
              input-type="number"
              separator="-"
              :num-inputs="4"
              :should-auto-focus="false"
              :class="{ disabled: isRoomEnd }"
              :is-input-num="true"
              :conditionalClass="['one', 'two', 'three', 'four']"
              :placeholder="['-', '-', '-', '-']"
            />
          </a-form-item>
          <a-form-item label="授权" name="scenes" style="margin-bottom: 2px">
            <a-button
              type="primary"
              size="small"
              ghost
              :disabled="isRoomEnd"
              @click="authvisible = true"
            >
              <template #icon><plus-outlined /></template>添加用户</a-button
            >

            <span
              class="user-label"
              style="margin-left: 5px"
              v-for="lab in current.userObjList"
            >
              {{ lab.userName }}
              <CloseOutlined @click="handleAssistantUseDelete(lab.userName)" />
            </span>
          </a-form-item>
          <a-form-item
            label="设置房间人数"
            class="maxMan"
            name="maxMan"
            style="margin-bottom: 2px"
            :rules="[{ required: true, message: t('room.form.titleRequired') }]"
          >
            <a-input-number
              v-model:value="current.maxMan"
              placeholder="请输入房间人数"
              :min="5"
              :max="50"
              :disabled="isRoomEnd"
              style="width: 80%"
            >
              <template #addonBefore>
                <UserOutlined />
              </template>
            </a-input-number>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <a-modal
      v-model:visible="authvisible"
      title="添加用户"
      centered
      @ok="handleAuthConfirm"
    >
      <a-form layout="inline" :model="authformState">
        <a-form-item
          label="用户账号"
          name="userName"
          style="margin-bottom: 20px"
          :rules="[{ required: true, message: `请输入房间使用时间` }]"
        >
          <a-input
            v-model:value="authformState.userName"
            placeholder="请输入完整的账号"
          />
        </a-form-item>
        <a-form-item
          label="使用时间"
          name="useTimeList"
          style="margin-bottom: 20px"
          :rules="[{ required: true, message: `请输入房间使用时间` }]"
        >
          <a-range-picker
            :show-time="{ format: 'HH:mm' }"
            format="YYYY-MM-DD HH:mm:ss"
            style="width: 90%"
            v-model:value="authformState.useTimeList"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-config-provider>
</template>

<script lang="ts">
import { ref, UnwrapRef, defineComponent, reactive, computed, unref } from 'vue'
import { createRoom, useRoomStore } from '@/store/modules/room'
import { props } from './props'
import { message } from 'ant-design-vue'
import { mainURL } from '@/env'
import EditScenes from './scene-list.vue'
import unScenePng from '@/assets/images/un-scene.png'
import VOtpInput from 'vue3-otp-input'
import type { Scene } from '@/store/modules/scene'
import type { FormInstance } from 'ant-design-vue'
import { useI18n } from '@/hook/useI18n'
import { useLocale } from '@/locales/useLocale'
import dayjs, { Dayjs } from 'dayjs'
import { addAuthUser } from '@/api'

// const titleValidator = ref({
//   validator: (_, value) =>
//     !value.includes(' ')
//       ? Promise.resolve()
//       : Promise.reject(new Error('No spaces allowed'))
// })

interface AuthUserFormState {
  userName: string
  useTimeList: Dayjs[]
}

export default defineComponent({
  name: 'EditRoom',
  components: { EditScenes, VOtpInput },
  props,
  setup(props) {
    const visible = ref(true)
    const authvisible = ref(false)

    const authformState: UnwrapRef<AuthUserFormState> = reactive({
      userName: '',
      useTimeList: []
    })
    const { getAntdLocale } = useLocale()
    const roomStore = useRoomStore()
    const isRoomEnd = computed(() => roomStore.roomStatus === 2)
    const { getLocale } = useLocale()
    const { t } = useI18n()
    const returnLocale = computed(() => {
      if (unref(getLocale).includes('zh')) {
        return 'zh'
      }
      return unref(getLocale)
    })
    const otpInput = ref('')
    const formRef = ref<FormInstance>()
    const current = reactive(createRoom(props.room || {}))
    if (current.useTimeList?.length) {
      current.useTimeList = current.useTimeList?.map(i => dayjs(i))
    }
    if (!current.visitPassword) {
      current.visitPassword = ''
    }
    if (!current.userObjList) {
      current.userObjList = []
    }

    const deleteScene = (scene: Scene) => {
      const index = current.scenes.indexOf(scene)
      if (~index) {
        current.scenes.splice(index, 1)
      }
    }
    const saveRoom = async () => {
      await formRef.value?.validate()
      if (!current.scenes.length) {
        return message.error(t('room.form.addLeastScene'))
      }
      if (
        current.visitPassword?.length &&
        current.visitPassword.length > 0 &&
        current.visitPassword.length < 4
      ) {
        return message.error('密码缺失，请填写完整！')
      } else {
        current.takeLookLock = 1
      }

      if (current.visitPassword?.length === 0) {
        current.takeLookLock = 0
      }
      current.cover = current.scenes[0].cover
      console.log('save', current)
      props.onSave && props.onSave(current)
      visible.value = false
    }
    // const startSync = () => {
    //   window.open(roomStore.getShareUrl({

    //   }))
    // }

    const handleNickRegex = async (_: any, value: string) => {
      console.log('value', value)
      const regex = new RegExp(
        '^([\u4E00-\uFA29]|[\uE7C7-\uE7F3]|[a-zA-Z0-9_]){1,15}$'
      )
      if (value?.length && !regex.test(value)) {
        return Promise.reject(t('room.nickNameRegrexError'))
      }
      return Promise.resolve('')
    }

    const handleAuthConfirm = async () => {
      if (authformState.userName?.length) {
        const userName = authformState.userName
        const res = await addAuthUser(userName)
        if (res) {
          const isExist = current.userObjList?.findIndex(
            i => i.userName === authformState.userName
          )
          console.log('isExist', isExist === -1)
          if (isExist === -1) {
            current.userObjList?.push(authformState)
          }

          authvisible.value = false
          console.log('current', current)
        }
      } else {
        message.error('用户账号不能为空！')
      }
    }

    const handleAssistantUseDelete = (userName: string) => {
      const users = current.userObjList || []
      const index = users.findIndex(i => i.userName === userName) 
      if (index > -1) {
        current.userObjList?.splice(index, 1)
      }
    }

    return {
      handleNickRegex,
      returnLocale,
      t,
      visible,
      current,
      formRef,
      deleteScene,
      saveRoom,
      // startSync,
      mainURL,
      unScenePng,
      getAntdLocale,
      dayjs,
      otpInput,
      authvisible,
      handleAuthConfirm,
      authformState,
      isRoomEnd,
      handleAssistantUseDelete
      // authTargetUser,
      // authTargetUserTime
    }
  }
})
</script>

<style lang="scss" scoped>
.edit-room-layout {
  display: flex;
  max-height: 700px;
  overflow: hidden;

  .info {
    max-height: 700px;
    overflow-y: scroll;
    overflow-x: hidden;
  }
}

.scene {
  flex: none;
  width: 320px;
  margin-right: 30px;
  height: 692px;
  background: #f7f8fa;
  display: flex;
  align-items: center;

  iframe {
    width: 320px;
    height: 100%;
  }

  img {
    width: 100%;
    display: block;
  }
}

.info {
  flex: 1;
  // min-width: 500px;
  .ant-form-item {
    width: 100%;
  }
  h4 {
    font-size: 18px;
    color: #333;
    font-weight: 400;

    &:not(:first-child) {
      margin-top: 20px;
    }
  }
}
.disabled {
  pointer-events: none;
  cursor: not-allowed;
  opacity: 0.5;
}
.user-label {
  background: #eee;
  padding: 5px 5px;
  font-size: 13px;
}
</style>

<style lang="scss">
.edit-room-layout {
  min-width: 864px;
  .ant-form-item {
    margin-bottom: 16px;
  }

  .ant-input-affix-wrapper,
  .ant-input {
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #ebedf0;
    padding: 6px 11px;
    // height: 36px;
  }

  textarea.ant-input {
    resize: none;
    height: 120px;
  }

  .ant-input-textarea {
    position: relative;

    &::after {
      position: absolute;
      bottom: 4px;
      right: 8px;
      margin: 0;
    }
  }

  .ant-form-item-label {
    padding-bottom: 0;
    > label {
      color: #646566;
    }
  }
}

.action-bottom {
  border-radius: 4px;
  min-width: 100px;
}

.select-scene label::before {
  display: inline-block;
  margin-right: 4px;
  color: #ff4d4f;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
.otp-container {
  input::placeholder {
    font-size: 15px;
    text-align: center;
    font-weight: 600;
  }
}
.otp-input {
  width: 40px;
  height: 40px;
  padding: 5px;
  margin: 0 10px;
  font-size: 20px;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.3);
  text-align: center;
  &.is-complete {
    background-color: #e4e4e4;
  }
  &::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
}
</style>
