<template>
  <div>
    <el-card class="main-card" shadow="never" style="border: 0">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" style="margin-bottom: -20px">
        <el-form-item :label="t('sip.index998533-0')" prop="deviceSipId">
          <el-input
            v-model="queryParams.deviceSipId"
            :placeholder="t('sip.index998533-1')"
            clearable
            size="default"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('sip.index998533-2')" prop="channelSipId">
          <el-input
            v-model="queryParams.channelSipId"
            :placeholder="t('sip.index998533-3')"
            clearable
            size="default"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('sip.index998533-4')" prop="status">
          <el-select
            v-model="queryParams.status"
            :placeholder="t('sip.index998533-5')"
            clearable
            size="default"
            style="width: 150px"
          >
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.VIDEO_DEVICE_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" size="default" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="Refresh" size="default" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="main-card mt-5" shadow="never" style="border: 0">
      <div class="mb-10">
        <el-button type="primary" plain :icon="Plus" size="small" @click="handleAdd">
          添加
        </el-button>
        <el-button type="danger" plain :icon="Delete" size="small" @click="handleDelete">
          删除
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="sipidList"
        @selection-change="handleSelectionChange"
        @cell-dblclick="celldblclick"
        :header-cell-style="{ background: '#f5f5f5' }"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" align="center" />
        <el-table-column label="设备编号" align="center" prop="deviceSipId" min-width="120">
          <template #default="scope">
            <el-link
              :underline="false"
              type="primary"
              @click="handleViewDevice(scope.row.deviceSipId)"
              >{{ scope.row.deviceSipId }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          :label="t('sip.index998533-2')"
          align="center"
          prop="channelSipId"
          min-width="120"
        />
        <el-table-column :label="t('sip.index998533-4')" align="center" prop="status" width="80">
          <template #default="scope">
            <dict-tag
              :type="DICT_TYPE.VIDEO_DEVICE_STATUS"
              :value="scope.row.status"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column :label="t('sip.index998533-8')" align="center" prop="productName" />
        <el-table-column :label="t('sip.index998533-9')" align="center" prop="deviceType">
          <template #default="scope">
            <dict-tag :options="DICT_TYPE.VIDEO_TYPE" :value="scope.row.deviceType" />
          </template>
        </el-table-column>
        <el-table-column :label="t('sip.index998533-15')" align="center" prop="channelType">
          <template #default="scope">
            <dict-tag :options="DICT_TYPE.CHANNEL_TYPE" :value="scope.row.channelType" />
          </template>
        </el-table-column>
        <el-table-column :label="t('sip.index998533-10')" align="center" prop="citycode" />
        <el-table-column
          :label="t('sip.index998533-11')"
          align="center"
          prop="registerTime"
          width="180"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              :icon="Edit"
              @click="handleBinding(scope.row)"
              >{{ t('sip.index998533-12') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="title" v-model="open" width="450px" append-to-body>
      <el-form :model="createForm" ref="createFormRef">
        <el-form-item :label="t('sip.index998533-13')">
          <el-cascader
            :options="cityOptions"
            v-model="createForm.city"
            @change="changeProvince"
            :props="{ checkStrictly: true }"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item :label="t('sip.index998533-9')" prop="deviceType">
          <el-select v-model="createForm.deviceType" :placeholder="t('sip.index998533-14')">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.VIDEO_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('sip.index998533-15')" prop="channelType">
          <el-select v-model="createForm.channelType" :placeholder="t('sip.index998533-16')">
            <el-option
              v-for="dict in getStrDictOptions(DICT_TYPE.CHANNEL_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('sip.index998533-8')" prop="productName">
          <el-input
            readonly
            v-model="createForm.productName"
            :placeholder="t('sip.index998533-17')"
          >
            <template #append>
              <el-button @click="selectProduct()">{{ t('sip.index998533-18') }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item :label="t('sip.index998533-20')" prop="createNum">
          <el-input-number
            controls-position="right"
            v-model="createForm.createNum"
            :max="10"
            :placeholder="t('sip.index998533-19')"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ t('sip.index998533-21') }}</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="title" v-model="bindingOpen" width="450px" append-to-body>
      <div class="mt-2"></div>
      <el-form :model="form" ref="formRef">
        <el-form-item :label="t('sip.index998533-22')" prop="deviceId">
          <el-select
            style="width: 210px"
            v-model="form.reDeviceId"
            size="small"
            :placeholder="t('sip.index998533-23')"
            filterable
            @change="handleUpdateDeviceItem"
          >
            <el-option
              v-for="(item, index) in deviceList"
              :key="index"
              :label="item.deviceName"
              :value="item.deviceId"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item :label="t('sip.index998533-24')" prop="sceneId">
          <el-select
            style="width: 210px"
            v-model="form.reSceneModelId"
            size="small"
            :placeholder="t('sip.index998533-25')"
            filterable
          >
            <el-option
              v-for="(item, index) in sceneList"
              :key="index"
              :label="item.sceneModelName"
              :value="item.sceneModelId"
            />
          </el-select>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormBinding">确定</el-button>
          <el-button @click="cancelBinding">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择产品 -->
    <product-list ref="productListRef" @product-event="getProductData" />
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'
import { regionData, codeToText } from 'element-china-area-data'
import { listChannel, getChannel, delChannel, addChannel, binding } from '@/api/pms/video/channel'
import { getDeviceBySerialNumber, listDeviceShort } from '@/api/pms/video/device'
import { getSceneModelList } from '@/api/pms/video/list'
import productList from './product-list.vue'
import { DICT_TYPE, getDictLabel, getStrDictOptions } from '@/utils/dict'

// 使用组合式API
const router = useRouter()
const store = useStore()
const { t } = useI18n() // 国际化

// 定义 props
const props = defineProps({
  product: {
    type: Object,
    default: null
  }
})

// 定义 emits
const emit = defineEmits(['productEvent'])

function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '')
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// refs
const queryFormRef = ref(null)
const createFormRef = ref(null)
const formRef = ref(null)
const productListRef = ref(null)

// 响应式数据
const isGeneralUser = ref(true)
const loading = ref(true)
const ids = ref([])
const multiple = ref(true)
const total = ref(0)
const sipidList = ref([])
const title = ref('')
const open = ref(false)
const bindingOpen = ref(false)
const deviceList = ref([])
const sceneList = ref([])
const productInfo = ref({})
const city = ref('')

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceSipId: null,
  deviceChannelId: null,
  status: null
})

// 表单参数
const createForm = reactive({
  city: '',
  deviceType: '',
  channelType: '',
  createNum: 1,
  remark: '',
  area: '',
  productId: null,
  productName: '',
  tenantId: null,
  tenantName: '',
  citycode: ''
})

const form = reactive({})

// 表单校验规则
const rules = {
  protocol: [
    {
      required: true,
      message: t('sip.index998533-26'),
      trigger: 'blur'
    }
  ],
  ip: [
    {
      required: true,
      message: t('sip.index998533-27'),
      trigger: 'blur'
    }
  ],
  domain: [
    {
      required: true,
      message: t('sip.index998533-28'),
      trigger: 'blur'
    }
  ],
  secret: [
    {
      required: true,
      message: t('sip.index998533-29'),
      trigger: 'blur'
    }
  ],
  portHttp: [
    {
      required: true,
      message: t('sip.index998533-30'),
      trigger: 'blur'
    }
  ],
  portHttps: [
    {
      required: true,
      message: t('sip.index998533-31'),
      trigger: 'blur'
    }
  ],
  portRtmp: [
    {
      required: true,
      message: t('sip.index998533-32'),
      trigger: 'blur'
    }
  ],
  portRtsp: [
    {
      required: true,
      message: t('sip.index998533-33'),
      trigger: 'blur'
    }
  ],
  rtpPortRange: [
    {
      required: true,
      message: t('sip.index998533-34'),
      trigger: 'blur'
    }
  ],
  delFlag: [
    {
      required: true,
      message: t('sip.index998533-35'),
      trigger: 'blur'
    }
  ],
  createBy: [
    {
      required: true,
      message: t('sip.index998533-36'),
      trigger: 'blur'
    }
  ],
  createTime: [
    {
      required: true,
      message: t('sip.index998533-37'),
      trigger: 'blur'
    }
  ]
}

// 城市选项
const cityOptions = regionData

// 监听 product prop 变化
watch(
  () => props.product,
  (newVal, oldVal) => {
    productInfo.value = newVal
    if (productInfo.value && productInfo.value.productId != 0) {
      queryParams.productId = productInfo.value.productId
      // deviceParams.productId = productInfo.value.productId
      getList()
    }
  }
)

// 查看设备操作
const handleViewDevice = (serialNumber) => {
  router.push({
    path: '/iotvideopms/videodevice',
    query: {
      t: Date.now(),
      sn: serialNumber
    }
  })
}

// 选择产品
const selectProduct = () => {
  open.value = false
  productListRef.value.open = true
  productListRef.value.getList()
}

// 获取选中的产品
const getProductData = (product) => {
  open.value = true
  createForm.productId = product.productId
  createForm.productName = product.productName
  createForm.tenantId = product.tenantId
  createForm.tenantName = product.tenantName
}

// 行政区划改变
const changeProvince = (data) => {
  if (data && data[0] != null && data[1] != null && data[2] != null) {
    const str = codeToText[data[0]] + '/' + codeToText[data[1]] + '/' + codeToText[data[2]]
    createForm.citycode = str
  }
}

// 获取设备详情
const getDeviceBySerial = (serialNumber) => {
  openDevice.value = true
  getDeviceBySerialNumber(serialNumber).then((response) => {
    // device.value = response.data
  })
}

// 查询通道列表
const getList = () => {
  listChannel(queryParams).then((response) => {
    sipidList.value = response.list
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 表单重置
const reset = () => {
  Object.assign(createForm, {
    id: null,
    deviceSipId: null,
    channelSipId: null,
    status: 0,
    registertime: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
    createNum: 1
  })
  // resetForm('createForm')
}

// 搜索按钮操作
const handleQuery = () => {
  loading.value = true
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  // resetForm('queryForm')
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}

// 批量新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = t('sip.index998533-38')
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const id = row.id || ids.value
  console.log(row)
  getChannel(id).then((response) => {
    Object.assign(createForm, response.data)
    open.value = true
    title.value = t('sip.index998533-39')
  })
}

// 处理绑定
const handleBinding = (row) => {
  Object.assign(form, row)
  bindingOpen.value = true
  title.value = t('sip.index998533-40')
}

// 获取设备列表
const getDeviceList = () => {
  const params = {
    showChild: true,
    pageNo: 1,
    pageSize: 9999
  }
  listDeviceShort(params).then((res) => {
    console.log('*******************************', res)
    deviceList.value = res
  })
}

// 获取场景列表数据
const getSceneListDatas = () => {
  const params = {
    pageNo: 1,
    pageSize: 9999
  }
  getSceneModelList(params).then((res) => {
    if (res.code === 200) {
      sceneList.value = res.rows
    } else {
      // $message.error(res.msg)
    }
  })
}

// 取消绑定
const cancelBinding = () => {
  bindingOpen.value = false
  reset()
}

// 确认绑定设备或场景
const submitFormBinding = () => {
  const data = {
    channelId: form.channelSipId,
    reDeviceId: form.reDeviceId,
    reSceneModelId: form.reSceneModelId
  }
  binding(data).then((response) => {
    if (response.code === 200) {
      bindingOpen.value = false
      ElMessage.success(t('sip.index998533-41'))
    } else {
      ElMessage.error('失败')
    }
  })
}

// 提交按钮
const submitForm = () => {
  if (createForm.createNum < 1) {
    // $modal.alertError(t('sip.index.998533-42'))
    return
  }
  if (!createForm.productId || createForm.productId == 0) {
    // $modal.alertError(t('sip.index.998533-43'))
    return
  }
  createForm.deviceSipId = createForm.city[2] + '0000' + createForm.deviceType + '0'
  createForm.channelSipId = createForm.city[2] + '0000' + createForm.channelType + '0'
  if (
    createForm.deviceType !== '' &&
    createForm.channelType !== '' &&
    createForm.city.length === 3
  ) {
    console.log(createForm)
    addChannel(createForm.createNum, createForm).then((response) => {
      // $modal.msgSuccess(t('addSuccess'))
      open.value = false
      getList()
    })
  } else {
    // $message({
    //     type: 'error',
    //     message: t('sip.index.998533-44'),
    // })
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const sipIds = row.id || ids.value
  // $modal
  //     .confirm(t('sip.index.998533-45') + sipIds + t('notify.channel.index.333541-18'))
  //     .then(function() {
  //         return delChannel(sipIds)
  //     })
  //     .then(() => {
  //         getList()
  //         // $modal.msgSuccess(t('delSuccess'))
  //     })
  //     .catch(() => {})
}

// 禁用有绑定设备的复选框,status:1=未使用，2=已使用
const selectable = (row) => {
  if (row.status == 2 || isGeneralUser.value) {
    return false
  }
  return true
}

// 表格增加复制功能
const celldblclick = (row, column, cell, event) => {
  // $copyText(row[column.property]).then(
  //     (e) => {
  //         onCopy()
  //     },
  //     function(e) {
  //         onError()
  //     }
  // )
}

// 复制成功
const onCopy = () => {
  // $notify({
  //     title: t('success'),
  //     message: t('sip.index.998533-46'),
  //     type: 'success',
  //     offset: 50,
  //     duration: 2000,
  // })
}

// 复制失败
const onError = () => {
  // $notify({
  //     title: t('fail'),
  //     message: t('sip.index.998533-47'),
  //     type: 'error',
  //     offset: 50,
  //     duration: 2000,
  // })
}

// 处理更新设备项
const handleUpdateDeviceItem = (value) => {
  // 实现具体逻辑
}

// 生命周期钩子
onMounted(() => {
  // 普通用户只能查看自己的通道
  // if (store.state.user.roles.indexOf('general') === -1) {
  //     isGeneralUser.value = false
  // }
  getList()
  getDeviceList()
  // getSceneListDatas()
})
</script>

<style scoped>
.createNum {
  width: 300px;
}

.createNum input {
  width: 260px;
}
</style>
