<template>
  <EdfsDialog
    :title="isBatchTransfer ? '批量迁移' : '数据迁移'"
    :is-show="visible"
    width="50%"
    @on-close="close"
    @on-save="onSave"
  >
    <div class="flex-col gap-10 w-80% m-x-30px">
      <el-row>
        <div class="label">
          <span class="require">*</span>
          数据时间范围:
        </div>
        <el-date-picker
          v-model="form.timeArr"
          type="datetimerange"
          class="flex-1"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-value="(defaultDateRange as any)"
          :disabled-date="disabledAfterToday"
      /></el-row>
    </div>
  </EdfsDialog>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { getPubInitData, type PublishMsg } from '@/utils/zmq'
import { cloneDeep } from 'lodash-es'
import type { IOnlineDevice } from '../type'
import { useMessage } from '@/composables/useMessage'
const message = useMessage()
const disabledAfterToday = (time: { getTime: () => number }) => {
  return time.getTime() > Date.now() // 禁用今天之后的时间
}
const defaultDateRange = [
  dayjs().subtract(1, 'month').startOf('month'),
  dayjs().endOf('month'),
] // 让左侧显示上个月，右侧显示本月
const emit = defineEmits<{
  'on-save': [PublishMsg<'export'>, IOnlineDevice]
}>()

const props = defineProps<{
  isBatchTransfer: boolean
}>()

const visible = ref(false)
const fromData = {
  timeArr: [],
}

const curDevice = ref<IOnlineDevice>()
const form = ref(cloneDeep(fromData))

const batchClientIp = ref('')
const batchPath = ref('')

function open(item: IOnlineDevice, clientIps: string, paths: string) {
  curDevice.value = item
  visible.value = true
  batchClientIp.value = clientIps
  batchPath.value = paths
}

function onSave() {
  if (!verifyData()) return
  if (!curDevice.value) {
    message.error('请选择设备')
    return
  }
  const params = [
    `${props.isBatchTransfer ? batchClientIp.value : curDevice.value.clientIp}`,
    '',
    '',
    '',
    '',
    '',
    `${
      props.isBatchTransfer
        ? batchPath.value
        : `${curDevice.value.site_id}/${curDevice.value.sn}`
    }`,
    `${dayjs(form.value.timeArr[0]).valueOf()},${dayjs(form.value.timeArr[1]).valueOf()}`,
  ]
  const msg = getPubInitData<'export'>('export', params)
  emit('on-save', msg, curDevice.value as IOnlineDevice)
  close()
}

function close() {
  form.value = cloneDeep(fromData)
  visible.value = false
  curDevice.value = undefined
  batchClientIp.value = ''
  batchPath.value = ''
}

function verifyData() {
  if (!form.value.timeArr.length) {
    message.error('请选择数据时间范围')
    return false
  }

  return true
}

defineExpose({
  open,
})
</script>

<style lang="scss" scoped>
.el-row {
  @apply h-32px;
  column-gap: 8px;

  .label {
    color: var(--label-color);
    line-height: 33px;
    text-align: right;
    width: 110px;
    .require {
      color: red;
    }
  }
}
</style>
