<template>
  <el-dialog :title="t('sip.product-list998536-0')" v-model="open" append-to-body width="600px">
    <div style="margin-top: 15px">
      <el-form ref="queryFormRef" :inline="true" :model="queryParams">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" size="small" type="primary" @click="handleQuery">{{
            t('search')
          }}</el-button>
          <el-button :icon="Refresh" size="small" @click="resetQuery">{{ t('reset') }}</el-button>
        </el-form-item>
      </el-form>

      <el-table
        ref="singleTableRef"
        v-loading="loading"
        :data="productList"
        @row-click="rowClick"
        highlight-current-row
        size="small"
      >
        <el-table-column label="选择" align="center" width="50">
          <template #default="scope">
            <input :checked="scope.row.isSelect" name="product" type="radio" />
          </template>
        </el-table-column>
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="分类名称" align="center" prop="categoryName" />
        <el-table-column :label="t('sip.product-list998536-1')" align="center" prop="tenantName" />
        <el-table-column :label="t('sip.product-list998536-2')" align="center" prop="networkMethod">
          <template #default="scope">
            <dict-tag
              :options="DICT_TYPE.VIDEO_CENTER_NETWORK_METHOD"
              :value="scope.row.networkMethod"
            />
          </template>
        </el-table-column>
        <el-table-column
          :label="t('sip.mediaServer998535-4')"
          align="center"
          prop="createTime"
          width="100"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </div>
    <template #footer>
      <div class="dialog-footer mt-10 flex justify-end">
        <el-button type="primary" @click="confirmSelectProduct">确认</el-button>
        <el-button @click="closeDialog">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Refresh } from '@element-plus/icons-vue'
import { listProduct } from '@/api/pms/video/product'
import { DICT_TYPE, getDictLabel, getIntDictOptions } from '@/utils/dict'

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
}

const { t } = useI18n() // 国际化
// 定义 props
const props = defineProps({
  productId: {
    type: Number,
    default: 0
  }
})

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

// refs
const queryFormRef = ref(null)
const singleTableRef = ref(null)

// 数据状态
const loading = ref(true)
const total = ref(0)
const open = ref(false)
const productList = ref([])
const product = ref({})

// 查询参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  productName: null,
  categoryId: null,
  categoryName: null,
  tenantId: null,
  tenantName: null,
  isSys: null,
  status: 2, //已发布
  deviceType: 3, // 监控设备
  networkMethod: null
})

// 获取列表数据
const getList = () => {
  loading.value = true
  listProduct(queryParams).then((response) => {
    // 产品列表初始化isSelect值，用于单选
    for (let i = 0; i < response.list.length; i++) {
      response.list[i].isSelect = false
    }
    productList.value = response.list
    total.value = response.total
    if (props.productId != 0) {
      setRadioSelected(props.productId)
    }
    loading.value = false
  })
}

// 搜索操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 重置操作
const resetQuery = () => {
  Object.assign(queryParams, {
    pageNo: 1,
    pageSize: 10,
    productName: null,
    categoryId: null,
    categoryName: null,
    tenantId: null,
    tenantName: null,
    isSys: null,
    status: 2,
    deviceType: 3,
    networkMethod: null
  })
  handleQuery()
}

// 行点击事件
const rowClick = (row) => {
  if (row != null) {
    setRadioSelected(row.productId)
    product.value = row
  }
}

// 设置单选按钮选中
const setRadioSelected = (productId) => {
  for (let i = 0; i < productList.value.length; i++) {
    if (productList.value[i].productId == productId) {
      productList.value[i].isSelect = true
    } else {
      productList.value[i].isSelect = false
    }
  }
}

// 确认选择产品
const confirmSelectProduct = () => {
  emit('productEvent', product.value)
  open.value = false
}

// 关闭对话框
const closeDialog = () => {
  open.value = false
}

// 生命周期钩子
onMounted(() => {
  // 组件创建时的操作可以放在这里
})

// 暴露方法给父组件调用
defineExpose({
  open,
  getList
})
</script>
