<template>
  <div id="mediaServerEdit" v-loading="isLoging">
    <el-dialog 
      :title="t('sip.mediaServerEdit998534-0')" 
      :width="dialogWidth" 
      top="2rem" 
      :close-on-click-modal="false"
      :destroy-on-close="true" 
      v-model="showDialog" 
      @close="close"
    >
      <template #header>
        <div class="w-full text-lg">
          <p>流媒体服务器节点</p>
          <el-divider class="mt--10" />
        </div>
      </template>
      
      <div id="formStep" style="margin-top: 1rem; margin-right: 20px">
        <el-form 
          v-if="currentStep == 1" 
          ref="mediaServerFormRef" 
          :rules="rules" 
          :model="mediaServerForm"
          label-width="280px" 
          style="width: 70%"
        >
          <el-form-item :label="t('sip.mediaServerEdit998534-1')" prop="ip">
            <el-input v-model="mediaServerForm.ip" :placeholder="t('sip.mediaServerEdit998534-2')" clearable />
          </el-form-item>
          <el-form-item :label="t('sip.mediaServerEdit998534-3')" prop="portHttp">
            <el-input v-model="mediaServerForm.portHttp" :placeholder="t('sip.mediaServerEdit998534-4')" clearable />
          </el-form-item>
          <el-form-item :label="t('sip.mediaServerEdit998534-5')" prop="secret">
            <el-input v-model="mediaServerForm.secret" :placeholder="t('sip.mediaServerEdit998534-6')" clearable />
          </el-form-item>
          <el-form-item>
            <div style="float: right; font-size: 28px">
              <el-button @click="close">取消</el-button>
              <el-button type="success" @click="checkServer" :loading="btnLoading">测试</el-button>
              <el-button type="primary" v-if="currentStep === 1 && serverCheck === 1" @click="next">{{ t('next') }}</el-button>
            </div>
          </el-form-item>
        </el-form>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form 
              v-if="currentStep === 2 || currentStep === 3" 
              ref="mediaServerForm1Ref" 
              :rules="rules"
              :disabled="!editFlag" 
              :model="mediaServerForm" 
              label-width="140px"
            >
              <el-form-item :label="t('sip.mediaServerEdit998534-7')" prop="serverId">
                <el-input v-model="mediaServerForm.serverId" :placeholder="t('sip.mediaServerEdit998534-7')" clearable />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-8')" prop="ip">
                <el-input v-if="currentStep === 2" v-model="mediaServerForm.ip" disabled />
                <el-input v-if="currentStep === 3" v-model="mediaServerForm.ip" />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-9')" prop="protocol">
                <el-select v-model="mediaServerForm.protocol" style="width: 100%">
                  <el-option key="http" label="http" value="http" />
                  <el-option key="https" label="https" value="https" />
                  <el-option key="ws" label="ws" value="ws" />
                  <el-option key="rtmp" label="rtmp" value="rtmp" />
                  <el-option key="rtsp" label="rtsp" value="rtsp" />
                </el-select>
              </el-form-item>
              <el-form-item label="HookUrl" prop="hookurl">
                <el-input v-model="mediaServerForm.hookurl" placeholder="HookUrl" clearable />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-10')" prop="portHttp">
                <el-input v-if="currentStep === 2" v-model="mediaServerForm.portHttp" disabled />
                <el-input v-if="currentStep === 3" v-model="mediaServerForm.portHttp" />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-11')" prop="portHttps">
                <el-input v-model="mediaServerForm.portHttps" :placeholder="t('sip.mediaServerEdit998534-11')" clearable />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-12')" prop="portRtsp">
                <el-input v-model="mediaServerForm.portRtsp" :placeholder="t('sip.mediaServerEdit998534-12')" clearable />
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="12">
            <el-form 
              v-if="currentStep === 2 || currentStep === 3" 
              ref="mediaServerForm2Ref" 
              :rules="rules"
              :disabled="!editFlag" 
              :model="mediaServerForm" 
              label-width="180px"
            >
              <el-form-item :label="t('sip.mediaServerEdit998534-13')" prop="secret">
                <el-input v-if="currentStep === 2" v-model="mediaServerForm.secret" disabled />
                <el-input v-if="currentStep === 3" v-model="mediaServerForm.secret" />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-14')" prop="domain">
                <el-input v-model="mediaServerForm.domain" :placeholder="t('sip.mediaServerEdit998534-14')" clearable />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-15')">
                <el-switch v-model="mediaServerForm.autoConfig" />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-16')">
                <el-switch 
                  :active-text="t('sip.mediaServerEdit998534-17')"
                  v-model="mediaServerForm.rtpEnable" 
                  :inactive-text="t('sip.mediaServerEdit998534-18')"
                  @change="portRangeChange"
                />
              </el-form-item>
              <el-form-item v-if="!mediaServerForm.rtpEnable" :label="t('sip.mediaServerEdit998534-19')" prop="rtpProxyPort">
                <el-input v-model.number="mediaServerForm.rtpProxyPort" clearable />
              </el-form-item>
              <el-form-item v-if="mediaServerForm.rtpEnable" :label="t('sip.mediaServerEdit998534-19')">
                <el-input 
                  v-model="rtpPortRange1" 
                  :placeholder="t('sip.mediaServerEdit998534-20')"
                  clearable 
                  style="width: 100px" 
                  @change="portRangeChange"
                />
                <el-input 
                  v-model="rtpPortRange2" 
                  :placeholder="t('sip.mediaServerEdit998534-21')"
                  clearable 
                  style="width: 100px" 
                  @change="portRangeChange"
                />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-22')" prop="portRtmp">
                <el-input v-model="mediaServerForm.portRtmp" :placeholder="t('sip.mediaServerEdit998534-22')" clearable />
              </el-form-item>
              <el-form-item :label="t('sip.mediaServerEdit998534-23')" prop="recordPort">
                <el-input v-model.number="mediaServerForm.recordPort" :disabled="!editFlag">
                  <template #append>
                    <el-button 
                      v-if="mediaServerForm.recordPort > 0" 
                      class="el-icon-check" 
                      type="primary"
                      @click="checkRecordServer"
                    />
                    
                  </template>
                </el-input>
                <i v-if="recordServerCheck === 1" class="el-icon-success" style="color: #3caf36; position: absolute; top: 14px"></i>
                <i v-if="recordServerCheck === 2" class="el-icon-loading" style="color: #3caf36; position: absolute; top: 14px"></i>
                <i v-if="recordServerCheck === -1" class="el-icon-error" style="color: #c80000; position: absolute; top: 14px"></i>
              </el-form-item>
              <el-form-item>
                <div style="float: right">
                  <el-button type="primary" @click="onSubmit" v-if="editFlag">提交</el-button>
                  <el-button @click="close" v-if="editFlag">取消</el-button>
                </div>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <!-- 选择用户 -->
    <user-list ref="userListRef" @user-event="getUserData" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import userList from './user-list.vue'
import { addmediaServer, checkmediaServer, updatemediaServer } from '@/api/pms/video/mediaServer'

// 使用组合式API
const { t } = useI18n()

// 定义 props
const props = defineProps({
  editFlag: {
    type: Boolean,
    default: false,
  },
})

// 定义 emits
const emit = defineEmits(['getServerList', 'delay'])

// refs
const mediaServerFormRef = ref(null)
const mediaServerForm1Ref = ref(null)
const mediaServerForm2Ref = ref(null)
const userListRef = ref(null)

// 数据状态
const tempTenantId = ref('')
const tempTenantName = ref('')
const btnLoading = ref(false)
const dialogWidth = ref('')
const defaultWidth = ref(1000)
const listChangeCallback = ref(null)
const showDialog = ref(false)
const isLoging = ref(false)
const dialogLoading = ref(false)
const currentStep = ref(1)
const platformList = ref([])
const serverCheck = ref(0)
const recordServerCheck = ref(0)
const rtpPortRange1 = ref(30000)
const rtpPortRange2 = ref(30100)

// 表单数据
const mediaServerForm = reactive({
  serverId: '',
  ip: '',
  domain: '',
  productId: '',
  productName: '',
  tenantId: '',
  tenantName: '',
  autoConfig: true,
  hookurl: '',
  secret: '',
  portHttp: '',
  portHttps: '',
  recordPort: '',
  portRtmp: '',
  portRtsp: '',
  rtpEnable: true,
  rtpPortRange: '',
  rtpProxyPort: '',
})

// 校验规则
const isValidIp = (rule, value, callback) => {
  // 校验IP是否符合规则
  var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
  if (!reg.test(value)) {
    return callback(new Error(t('sip.mediaServerEdit998534-24')))
  } else {
    callback()
  }
  return true
}

const isValidPort = (rule, value, callback) => {
  // 校验端口是否符合规则
  var reg = /^(([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5]))$/
  if (!reg.test(value)) {
    return callback(new Error(t('sip.mediaServerEdit998534-25')))
  } else {
    callback()
  }
  return true
}

const rules = reactive({
  ip: [{ required: true, validator: isValidIp, message: t('sip.mediaServerEdit998534-24'), trigger: 'blur' }],
  portHttp: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  portHttps: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  recordPort: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  portRtmp: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  portRtsp: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  rtpPortRange1: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  rtpPortRange2: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  rtpProxyPort: [{ required: true, validator: isValidPort, message: t('sip.mediaServerEdit998534-25'), trigger: 'blur' }],
  secret: [{ required: true, message: '请输入secret', trigger: 'blur' }],
})

// 设置对话框宽度
const setDialogWidth = () => {
  let val = document.body.clientWidth
  if (val < defaultWidth.value) {
    dialogWidth.value = '80%'
  } else {
    dialogWidth.value = defaultWidth.value + 'px'
  }
}

// 生命周期钩子
onMounted(() => {
  setDialogWidth()
})

// 打开对话框
const openDialog = (param, callback) => {
  showDialog.value = true
  listChangeCallback.value = callback
  if (param != null) {
    if (param.autoConfig === 1) {
      param.autoConfig = param.autoConfig === 1
    } else if (param.autoConfig === 0) {
      param.autoConfig = param.autoConfig === 1
    }

    if (param.rtpEnable === 1) {
      param.rtpEnable = param.rtpEnable === 1
    } else if (param.rtpEnable === 0) {
      param.rtpEnable = param.rtpEnable === 1
    }

    Object.assign(mediaServerForm, param)
    currentStep.value = 3
    if (param.rtpPortRange) {
      let rtpPortRange = mediaServerForm.rtpPortRange.split(',')
      if (rtpPortRange.length > 0) {
        rtpPortRange1.value = rtpPortRange[0]
        rtpPortRange2.value = rtpPortRange[1]
      }
    }
  }
}

// 检查服务器
const checkServer = () => {
  mediaServerFormRef.value.validate((valid) => {
    if (valid) {
      btnLoading.value = true
      serverCheck.value = 0
      let query = {
        ip: mediaServerForm.ip,
        port: mediaServerForm.portHttp,
        secret: mediaServerForm.secret,
      }
      checkmediaServer(query)
        .then((response) => {
          btnLoading.value = false
          if (response != null) {
            Object.assign(mediaServerForm, response)
            mediaServerForm.autoConfig = true
            mediaServerForm.rtpEnable = true
            mediaServerForm.protocol = 'http'
            mediaServerForm.domain = 'yanfan.com'
            mediaServerForm.enabled = 1
            mediaServerForm.tenantId = tempTenantId.value
            mediaServerForm.tenantName = tempTenantName.value
            mediaServerForm.serverId = 'yanfan'
            mediaServerForm.hookurl = 'java:8080'
            mediaServerForm.portHttps = 8443
            mediaServerForm.recordPort = 18081
            mediaServerForm.portRtmp = 1935
            mediaServerForm.portRtsp = 554
            mediaServerForm.rtpProxyPort = ''
            rtpPortRange1.value = 30000
            rtpPortRange2.value = 30100
            serverCheck.value = 1
            ElMessage.success(t('sip.mediaServerEdit998534-26'))
          } else {
            serverCheck.value = -1
            ElMessage.error(t('sip.mediaServerEdit998534-27'))
          }
        })
        .catch((error) => {
          serverCheck.value = -1
          ElMessage({
            showClose: true,
            message: error,
            type: 'error',
          })
        })
    }
  })
}

// 下一步
const next = () => {
  currentStep.value = 2
  defaultWidth.value = 900
  setDialogWidth()
}

// 检查录制服务器
const checkRecordServer = () => {
  recordServerCheck.value = 2
  if (mediaServerForm.recordPort <= 0 || mediaServerForm.recordPort > 65535) {
    recordServerCheck.value = -1
     ElMessage({
      showClose: true,
      message: t('sip.mediaServerEdit998534-28'),
      type: 'error',
    })
    return
  }
}

// 提交表单
const onSubmit = () => {
  dialogLoading.value = true
  mediaServerForm.rtpEnable = mediaServerForm.rtpEnable ? 1 : 0
  mediaServerForm.autoConfig = mediaServerForm.autoConfig ? 1 : 0
  if (mediaServerForm.id != null) {
    updatemediaServer(mediaServerForm).then((response) => {
      ElMessage.success('更新成功')
      emit('getServerList')
      emit('delay')
      showDialog.value = false
    })
  } else {
    portRangeChange()
    addmediaServer(mediaServerForm).then((response) => {
      ElMessage.success('添加成功')
      emit('getServerList')
      emit('delay')
      showDialog.value = false
    })
  }

}

// 关闭对话框
const close = () => {
  showDialog.value = false
  dialogLoading.value = false
  Object.assign(mediaServerForm, {
    serverId: '',
    ip: '',
    domain: '',
    autoConfig: true,
    hookurl: '',
    secret: '',
    portHttp: '',
    portHttps: '',
    recordPort: '',
    portRtmp: '',
    portRtsp: '',
    rtpEnable: true,
    rtpPortRange: '',
    rtpProxyPort: '',
  })
  rtpPortRange1.value = 30000
  rtpPortRange2.value = 30100
  listChangeCallback.value = null
  currentStep.value = 1
}

// 端口范围变化
const portRangeChange = () => {
  if (mediaServerForm.rtpEnable) {
    mediaServerForm.rtpPortRange = rtpPortRange1.value + ',' + rtpPortRange2.value
    console.log(mediaServerForm.rtpPortRange)
  }
}

// 选择用户
const selectUser = () => {
  userListRef.value.open = true
  userListRef.value.getList()
}

// 获取用户数据
const getUserData = (user) => {
  tempTenantId.value = user.userId
  tempTenantName.value = user.userName
  mediaServerForm.tenantId = user.userId
  mediaServerForm.tenantName = user.userName
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>