<template>
  <div class="product normal-form" style="padding: 6px">
    <el-card style="margin: 20px; border: 0; margin-top: 10px" shadow="never">
      <el-form
        class="search-form"
        ref="queryFormRef"
        :inline="true"
        :model="queryParams"
        label-width="68px"
        style="margin-bottom: -20px"
      >
        <el-form-item :label="t('product.index091251-0')" prop="productName">
          <el-input
            v-model="queryParams.productName"
            :placeholder="t('product.index091251-1')"
            clearable
            size="default"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('product.index091251-2')" prop="categoryName">
          <el-input
            v-model="queryParams.categoryName"
            :placeholder="t('product.index091251-3')"
            clearable
            size="default"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('product.index091251-4')" prop="status">
          <el-select
            v-model="queryParams.status"
            :placeholder="t('product.index091251-5')"
            clearable
            size="default"
            style="width: 150px"
          >
            <el-option
              v-for="dict in iot_product_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" size="default" type="primary" @click="handleQuery">{{
            t('product.index091251-6')
          }}</el-button>
          <el-button :icon="Refresh" size="default" @click="resetQuery">{{
            t('product.index091251-7')
          }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="main-card" shadow="never" style="margin: 20px; border: 0">
      <div class="card-toolbar mb8">
        <el-button type="primary" size="small" :icon="Plus" @click="handleEditProduct(0)"
          >新增</el-button
        >
        <el-radio-group v-model="showType" class="float-right ml-10" plain size="small">
          <el-radio-button label="card"
            ><el-icon><Menu /></el-icon
          ></el-radio-button>
          <el-radio-button label="list"
            ><el-icon><Fold /></el-icon
          ></el-radio-button>
        </el-radio-group>
      </div>
      <template v-if="total > 0">
        <el-row
          v-if="showType == 'card'"
          v-loading="loading"
          type="flex"
          :gutter="30"
          style="flex-wrap: wrap"
        >
          <el-col
            v-for="(item, index) in productList"
            :key="index"
            :xs="24"
            :sm="12"
            :md="8"
            :lg="6"
            :xl="6"
            style="margin-bottom: 30px; text-align: center"
          >
            <el-card
              :body-style="{ padding: '20px' }"
              shadow="hover"
              class="card-item"
              style="border: 0"
            >
              <el-row type="flex" :gutter="10" justify="space-between">
                <el-col :span="16" style="text-align: left">
                  <el-link
                    :underline="false"
                    style="font-weight: bold; font-size: 16px; line-height: 32px"
                    @click="handleDeviceDetail(item)"
                  >
                    <el-tooltip
                      class="item"
                      effect="dark"
                      content="分享的设备"
                      placement="top-start"
                    >
                      <svg-icon
                        v-if="item.isOwner != 1"
                        class="mr-5"
                        iconClass="share"
                        className="share"
                        style="font-size: 20px; vertical-align: -6px"
                      />
                    </el-tooltip>
                    <svg-icon v-if="item.isOwner == 1" icon-class="device" />
                    <b class="card-item__title" @click="handleDeviceDetail(item)">{{
                      item.productName
                    }}</b>
                    <!-- <el-tag type="info">{{ item.tenantName }}</el-tag> -->
                  </el-link>
                </el-col>
                <el-col type="flex" :span="8">
                  <li
                    v-if="item.status == 2"
                    class="table-status text-[#67c23a]"
                    style="text-align: right"
                  >
                    <span class="status-content">已发布</span>
                  </li>
                  <li v-else class="table-status text-[#999999]" style="text-align: right">
                    <span class="status-content">未发布</span>
                  </li>
                </el-col>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="17">
                  <el-descriptions
                    :column="1"
                    size="small"
                    style="margin-top: 10px; white-space: nowrap"
                  >
                    <el-descriptions-item label="所属分类">
                      <el-link type="primary" :underline="false">{{ item.categoryName }}</el-link>
                    </el-descriptions-item>
                    <el-descriptions-item label="产品类型">
                      <dict-tag :type="DICT_TYPE.VIDEO_PRODUCT_TYPE" :value="item.deviceType" />
                    </el-descriptions-item>
                    <el-descriptions-item label="联网方式">
                      <dict-tag
                        :type="DICT_TYPE.VIDEO_CENTER_NETWORK_METHOD"
                        :value="item.networkMethod"
                      />
                    </el-descriptions-item>
                    <el-descriptions-item label="设备授权">
                      <el-tag v-if="item.isAuthorize == 1" type="success" size="small"
                        >已启用</el-tag
                      >
                      <el-tag v-else type="info" size="small">未启用</el-tag>
                    </el-descriptions-item>
                  </el-descriptions>
                </el-col>
                <el-col :span="7">
                  <div style="margin-top: 10px">
                    <el-image
                      v-if="item.imgUrl != null && item.imgUrl != ''"
                      style="width: 100%; height: auto"
                      lazy
                      :preview-src-list="[baseUrl + item.imgUrl]"
                      :src="baseUrl + item.imgUrl"
                      fit="cover"
                    />
                    <el-image
                      v-else-if="item.deviceType == 2"
                      style="width: 100%; height: auto"
                      :preview-src-list="[gatewaySvg]"
                      :src="gatewaySvg"
                      fit="cover"
                    />
                    <el-image
                      v-else-if="item.deviceType == 3"
                      style="width: 100%; height: auto"
                      :preview-src-list="[videoSvg]"
                      :src="videoSvg"
                      fit="cover"
                    />
                    <el-image
                      v-else
                      style="width: 100%; height: auto"
                      :preview-src-list="[productSvg]"
                      :src="productSvg"
                      fit="cover"
                    />
                  </div>
                </el-col>
              </el-row>
              <div class="card-item__footer">
                <el-button size="small" class="detail-btn" @click="handleEditProduct(item)"
                  >查看详情</el-button
                >
                <el-button
                  v-if="item.status == 1 && item.isOwner != 0"
                  size="small"
                  class="delete-btn"
                  @click="handleDelete(item)"
                  >删除</el-button
                >
                <el-button
                  v-if="item.status == 2 && item.isOwner != 0"
                  size="small"
                  class="success-btn"
                  :disabled="item.isAuthorize != 1"
                  @click="handleDeviceAuthorize(item)"
                >
                  设备授权
                </el-button>
                <el-button size="small" type="warning" @click="handleViewDevice(item.productId)"
                  >查看设备</el-button
                >
              </div>
            </el-card>
          </el-col>
        </el-row>
        <el-table v-else v-loading="loading" class="base-table" :data="productList" :border="false">
          <el-table-column
            label="图标"
            align="center"
            header-align="center"
            prop="productId"
            width="72"
          >
            <template #default="{ row }">
              <el-image
                v-if="row.imgUrl != null && row.imgUrl != ''"
                style="width: 24px; height: 24px"
                lazy
                :preview-src-list="[baseUrl + row.imgUrl]"
                :src="baseUrl + row.imgUrl"
                fit="cover"
              />
              <el-image
                v-else-if="row.deviceType == 2"
                style="width: 24px; height: 24px"
                :preview-src-list="[gatewaySvg]"
                :src="gatewaySvg"
                fit="cover"
              />
              <el-image
                v-else-if="row.deviceType == 3"
                style="width: 24px; height: 24px"
                :preview-src-list="[videoSvg]"
                :src="videoSvg"
                fit="cover"
              />
              <el-image
                v-else
                style="width: 24px; height: 24px"
                :preview-src-list="[productSvg]"
                :src="productSvg"
                fit="cover"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="名称"
            align="left"
            header-align="left"
            prop="productName"
            min-width="120"
          />
          <el-table-column label="所属分类" align="left" prop="categoryName" min-width="120" />
          <el-table-column label="所属类型" align="left" prop="deviceType" min-width="120">
            <template #default="{ row }">
              <dict-tag :type="DICT_TYPE.VIDEO_PRODUCT_TYPE" :value="row.deviceType" />
            </template>
          </el-table-column>
          <el-table-column label="联网方式" align="left" prop="networkMethod" min-width="120">
            <template #default="{ row }">
              <dict-tag :type="DICT_TYPE.VIDEO_CENTER_NETWORK_METHOD" :value="row.networkMethod" />
            </template>
          </el-table-column>
          <el-table-column label="设备授权" align="center" prop="isAuthorize" min-width="120">
            <template #default="{ row }">
              <el-tag v-if="row.isAuthorize == 1" type="success" size="small">已启用</el-tag>
              <el-tag v-else type="info" size="small">未启用</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布状态" align="center" prop="status" min-width="120">
            <template #default="{ row }">
              <li v-if="row.status == 2" class="table-status success"
                ><span class="status-content">已发布</span></li
              >
              <li v-else class="table-status"><span class="status-content">未发布</span></li>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="300"
          >
            <template #default="{ row }">
              <el-button type="primary" plain style="padding: 5px" @click="handleEditProduct(row)"
                >查看详情</el-button
              >
              <el-button
                type="primary"
                plain
                style="padding: 5px"
                @click="handleViewDevice(row.productId)"
                >查看设备</el-button
              >
              <el-button
                v-if="row.status == 2 && row.isOwner != 0"
                type="success"
                plain
                style="padding: 5px"
                @click="handleDeviceAuthorize(row)"
                >设备授权</el-button
              >
              <el-button
                v-if="row.status == 1 && row.isOwner != 0"
                type="danger"
                plain
                style="padding: 5px"
                @click="handleDelete(row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-empty v-else description="暂无数据，请添加产品" />
      <div class="mt-5 flex justify-right">
        <el-pagination
          v-show="total > 0"
          :total="total"
          v-model:current-page="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[12, 24, 36, 60]"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="getList"
          @update:page-size="getList"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { listProduct, delProduct, changeProductStatus, deviceCount } from '@/api/pms/video/product'
import { delSipconfigByProductId } from '@/api/pms/video/sipConfig'
// import { checkPermi } from '@/utils/permission'
import { getAccessToken } from '@/utils/auth'
import { Search, Refresh, InfoFilled, Menu, Fold, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { download } from '@/config/axios/service'
import productSvg from '@/assets/imgs/product.svg'
import videoSvg from '@/assets/imgs/video.svg'
import gatewaySvg from '@/assets/imgs/gateway.svg'
import { getDicts } from '@/api/pms/video/dicts'
import { DICT_TYPE } from '@/utils/dict'

const { t } = useI18n() // 国际化

// 定义组件名称
defineOptions({
  name: 'Product'
})

// 获取实例和路由
const router = useRouter()
const route = useRoute()

// 字典定义
const iot_product_status = ref([])
const iot_device_type = []
const iot_network_method = []
const iot_vertificate_method = []
const iot_device_chip = []

// 响应式数据
const queryFormRef = ref(null)
const openTemp = ref(false)
const loading = ref(true)
const total = ref(0)
const productList = ref([])
const title = ref('')
const open = ref(false)
const isShowScada = ref(false)
const showType = ref('card')
const uniqueId = ref(0)
const baseUrl = ref(import.meta.VITE_BASE_URL)

const queryParams = reactive({
  pageNo: 1,
  pageSize: 12,
  showSenior: true,
  productName: null,
  categoryId: null,
  categoryName: null,
  tenantId: null,
  tenantName: null,
  isSys: null,
  status: null,
  deviceType: null,
  networkMethod: null
})

const form = reactive({})
const upload = reactive({
  open: false,
  title: '',
  headers: {
    Authorization: 'Bearer ' + getAccessToken()
  },
  url: import.meta.VITE_BASE_URL + '/iot/product/temp'
})

// 导入模板
function importTemplate() {
  download('iot/product/temp-json', {}, `产品模板${new Date().getTime()}.xlsx`)
}

// 文件上传中处理
function handleFileUploadProgress(event, file, fileList) {
  upload.isUploading = true
}

// 查询产品列表
function getList() {
  loading.value = true
  listProduct(queryParams).then((response) => {
    productList.value = response.list
    total.value = response.total
    loading.value = false
  })
}

// 同步获取产品下的设备数量
function getDeviceCountByProductId(productId) {
  return new Promise((resolve, reject) => {
    deviceCount(productId)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

// 更新产品状态
async function handleChangeProductStatus(productId, status, deviceType) {
  let message = t('product.index091251-30')
  if (status == 2) {
    // 发布
    // let hasPermission = checkPermi(['iot:product:add'])
    // if (!hasPermission) {
    //   ElMessage.error(t('product.index091251-31'))
    //   return
    // }
    message = t('product.index091251-32')
  } else if (status == 1) {
    // 取消发布
    // let hasPermission = checkPermi(['iot:product:edit'])
    // if (!hasPermission) {
    //   ElMessage.error(t('product.index091251-31'))
    //   return
    // }
    let result = await getDeviceCountByProductId(productId)
    if (result.data > 0) {
      message = t('product.index091251-33', [result.data])
    }
  }
  ElMessageBox.confirm(message, t('product.index091251-34'), {
    confirmButtonText: t('product.index091251-35'),
    cancelButtonText: t('product.index091251-36'),
    type: 'warning'
  })
    .then(() => {
      let data = {
        productId,
        status,
        deviceType
      }

      changeProductStatus(data)
        .then((response) => {
          getList()
          ElMessage.success(response.msg)
        })
        .catch(() => {})
    })
    .catch(() => {})
}

function handleTemp() {
  openTemp.value = true
}

// 查看设备按钮操作
function handleViewDevice(productId) {
  router.push({
    path: '/iotvideopms/videodevice',
    query: {
      t: Date.now(),
      productId: productId
    }
  })
}

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

// 搜索按钮操作
function handleQuery() {
  queryParams.pageNo = 1
  getList()
}

// 重置按钮操作
function resetQuery() {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 删除按钮操作
function handleDelete(row) {
  const productIds = row.productId || 0
  let msg = ''
  ElMessageBox.confirm(t('product.index091251-39', [productIds]))
    .then(function () {
      // 删除SIP配置
      delSipconfigByProductId(productIds).then((response) => {})
      delProduct(productIds).then((response) => {
        msg = response.msg
        getList()
      })
    })
    .then(() => {
      ElMessage.success('删除成功')
    })
    .catch(() => {})
}

// 修改按钮操作
function handleEditProduct(row) {
  let productId = 0
  if (row != 0) {
    productId = row.productId || 0
  }
  router.push({
    name: 'VideoCenterProductEdit',
    query: {
      productId: productId,
      pageNo: queryParams.pageNo
    }
  })
}

// 重置表单
function reset() {
  form.datatype = undefined
}

// 查看设备详情
function handleDeviceDetail(item) {
  // 实现查看详情逻辑
}

// 设备授权操作
function handleDeviceAuthorize(item) {
  // 实现设备授权逻辑
}

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

  getDicts('iot_product_status').then((response) => {
    iot_product_status.value = response
  })
})

// activated钩子
if (route.query.t) {
  const time = route.query.t
  if (time != null && time != uniqueId.value) {
    uniqueId.value = time
    queryParams.pageNo = Number(route.query.pageNo)
    getList()
  }
}
</script>

<style lang="scss" scoped>
.product {
  --font-grey: #606266;
  --success-color: #67c23b;
  padding: 20px;
  --primary-color: #0147eb;

  .search-form {
    .el-form-item {
      ::v-deep .el-form-item__label {
        font-weight: normal;
        color: var(--font-grey);
      }
    }
  }

  .el-table {
    ::v-deep .el-table__header th {
      color: #9a9da3;
      border-color: #f6f8fa;
      background-color: #f5f7fa;
    }

    ::v-deep .el-table__body .el-table__cell {
      color: #606266;
      padding: 8px 0;
      border-color: #f6f8fa;

      .el-button {
        border-color: transparent;
        background: transparent;

        &:hover {
          &.el-button--danger {
            color: #ff9999;
          }

          &.el-button--primary {
            color: #91a8f8;
          }
        }

        &.el-button {
          margin-left: 2px;
        }
      }
    }
  }

  .pagination-container {
    ::v-deep .el-pagination {
      .el-pager li:not(.disabled).active {
        background-color: var(--primary-color);
      }
    }
  }

  .card-item {
    height: 100%;
    border-radius: 4px;
    background-image: linear-gradient(#e9f1fc, #fefefe);

    ::v-deep .el-card__body {
      display: flex;
      height: 100%;
      flex-direction: column;
      justify-content: space-between;
    }

    .card-item__title {
      vertical-align: -2px;
      margin-right: 0.5em;
    }

    .el-descriptions {
      ::v-deep .el-descriptions__body {
        background: transparent;
      }
    }

    .card-item__footer {
      margin-top: 1em;
      text-align: right;
      display: flex;
      justify-content: center;

      .el-button {
        background: #f5f7fa;
        border-color: #f5f7fa;
        color: #333;
        font-weight: bold;

        &.detail-btn {
          color: var(--primary-color);
        }

        &.delete-btn {
          color: #ff6363;
        }

        &.success-btn {
          color: var(--success-color);
        }

        &:hover {
          border-color: var(--primary-color);
          color: var(--primary-color);
        }
      }
    }
  }
}
</style>
