<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import dayjs from 'dayjs'

import { extensionVipLength, getUserVipLength } from '#/api'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  extensionData: {
    type: Object,
    default: Object,
  },
})
const emits = defineEmits(['update:modelValue', 'onRefresh'])

const vipList = [
  {
    value: '年',
  },
  {
    value: '月',
  },
  {
    value: '日',
  },
]
const userViplength = ref<{
  label: string
  value: number | string
}>({
  value: '',
  label: '年',
})
const isActive = ref(true) // 是否勾选顺延

watch(
  () => isActive.value,
  () => {
    if (userViplength.value.value) {
      handleChangeTime()
    }
  },
)

const show = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

// 表单数据

const _formData = {
  createTime: '',
  account: '',
  endTime: '',
  firstLoginTime: '',
  delayInvokeRecordTime: '',
  invokeFlag: 0,
  id: '',
}
const formRef = ref<FormInstance | undefined>()
const formData = reactive<Record<string, any>>({
  ..._formData,
})
const vipEndTime = ref('')

// 确定延期
async function handleSave() {
  if (
    (formData.invokeFlag && !vipEndTime.value) ||
    (!formData.invokeFlag && !userViplength.value.value)
  ) {
    return ElMessage.warning('请勿输入空时间')
  }
  extensionVipLength({
    createUser: props.extensionData?.id,
    postponeTimeStr: userViplength.value.value
      ? userViplength.value.value + userViplength.value.label
      : null,
    newVipEndTime:
      formData.invokeFlag || formData.endTime ? vipEndTime.value : null,
  }).then((res) => {
    ElMessage.success(res)
    show.value = false
    emits('onRefresh')
  })
}
function handleChangeTime() {
  switch (userViplength.value.label) {
    case '年': {
      addTime('year')
      break
    }
    case '日': {
      addTime('day')
      break
    }
    case '月': {
      addTime('month')
      break
    }
  }
}

function addTime(type: 'day' | 'month' | 'year') {
  vipEndTime.value = formData.endTime
    ? `${dayjs(isActive.value ? formData.endTime : new Date())
        .add(userViplength.value.value as number, type)
        .format('YYYY-MM-DD')} 23:59:59`
    : ''
}

function onClear() {
  Object.assign(formData, _formData)
  vipEndTime.value = ''
  userViplength.value = {
    value: '',
    label: '年',
  }
}

function handleOpen() {
  isActive.value = true
  onClear()
  if (props.extensionData?.id) {
    getUserVipLength({
      userId: props.extensionData.id,
    }).then((res) => {
      formData.endTime = res.rows[0].vipEndTime
    })
  }
  for (const key in formData) {
    formData[key] = (props.extensionData as any)[key]
  }
}
function disabledDate(time: Date) {
  return time.getTime() < Date.now() - 8.64e7 // 只能选择今天及今天之后的日期
  // return time.getTime() < Date.now() - 8.64e6; // 只能选择今天之后的日期，今天的日期也不能选
}
function pickerChange(_: string) {
  userViplength.value = {
    value: '',
    label: '年',
  }
}
</script>

<template>
  <el-dialog
    v-model="show"
    width="600px"
    title="延期"
    class="box"
    center
    destroy-on-close
    @closed="onClear"
    @open="handleOpen"
  >
    <el-form ref="formRef" label-width="90px" :model="formData">
      <el-form-item label="用户账号:" prop="account">
        <el-row>
          <el-col :span="12">
            {{ formData.account }}
          </el-col>
          <el-col :span="12">
            <el-checkbox v-model="isActive" label="顺延" size="large" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="注册时长:" prop="account">
        {{ formData.createTime }}
      </el-form-item>
      <el-form-item label="激活时间:" prop="account">
        <!-- formData.delayInvokeRecordTime
                        ? formData.invokeFlag
                            ? formData.firstLoginTime
                            : null
                        : formData.createTime -->
        {{
          formData.delayInvokeRecordTime
            ? formData.invokeFlag
              ? formData.firstLoginTime
              : null
            : formData.createTime
        }}
      </el-form-item>
      <el-form-item label="延期时长:" prop="vipLengthTime">
        <el-row>
          <el-col :span="8" style="margin-right: 8px">
            <el-input
              v-model.number="userViplength.value"
              placeholder="请输入"
              @change="handleChangeTime"
            />
          </el-col>
          <el-col :span="5">
            <el-select
              v-model="userViplength.label"
              placeholder="请选择"
              @change="handleChangeTime"
            >
              <el-option
                v-for="item in vipList"
                :key="item.value"
                :label="item.value"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="到期时间:" prop="account">
        {{ formData.endTime }}
      </el-form-item>
      <el-form-item label-width="132px" label="延期后到期时间:" prop="account">
        <!-- 不是立即激活就禁用掉 -->
        <el-date-picker
          v-model="vipEndTime"
          :disabled="!formData.invokeFlag"
          type="datetime"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择日期"
          :default-time="new Date(2000, 1, 1, 23, 59, 59)"
          :disabled-date="disabledDate"
          @change="pickerChange"
        />
        <!-- <el-date-picker
                    v-model="vipEndTime"
                    type="date"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    :default-time="[
                        new Date(2000, 1, 1, 23, 59, 59),
                        new Date(2000, 1, 1, 23, 59, 59),
                    ]"
                    :disabled-date="disabledDate"
                /> -->
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">取消</el-button>
        <el-button type="primary" @click="handleSave"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.box {
  .el-row {
    width: 100%;

    .el-checkbox.el-checkbox--large {
      height: 20px;
    }
  }
}
</style>
