<template>
  <div style="padding: 6px">
    <el-card v-show="showSearch" style="margin-bottom: 5px; border: 0" shadow="never">
      <el-form :model="queryParams" ref="queryFormRef" inline style="margin-bottom: -20px">
        <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>
          <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" shadow="never" style="border: 0">
      <div class="card-toolbar mb8">
        <el-button type="primary" :icon="Plus" size="default" @click="handleAdd">新增</el-button>
      </div>

      <el-table
        class="base-table"
        v-loading="loading"
        :data="categoryList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="产品分类名称" align="center" prop="categoryName" min-width="150" />
        <el-table-column
          label="备注"
          align="left"
          header-align="center"
          prop="remark"
          min-width="150"
        />
        <el-table-column label="系统定义" align="center" prop="isSys" min-width="150">
          <template #default="scope">
            <el-icon v-if="scope.row.isSys == 1" style="color: #346cef; font-size: 20px"
              ><Check
            /></el-icon>
            <el-icon v-else style="font-size: 20px"><CircleClose /></el-icon>
          </template>
        </el-table-column>
        <el-table-column label="显示顺序" align="center" prop="orderNum" min-width="150" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200"
        >
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              plain
              text
              style="padding: 5px"
              :icon="View"
              @click="handleUpdate(scope.row)"
              v-if="scope.row.isSys == '0' ? true : !isTenant"
            >
              查看
            </el-button>
            <el-button
              size="small"
              type="danger"
              plain
              text
              style="padding: 5px"
              :icon="Delete"
              @click="handleDelete(scope.row)"
              v-if="scope.row.isSys == '0' ? true : !isTenant"
            >
              删除
            </el-button>
            <span style="font-size: 10px; color: #999" v-if="scope.row.isSys == '1' && isTenant"
              >系统定义，不能修改</span
            >
          </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-dialog v-model="open" title="产品分类" width="500px" append-to-body>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="分类名称" prop="categoryName">
            <el-input v-model="form.categoryName" placeholder="请输入产品分类名称" />
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input-number
              controls-position="right"
              v-model="form.orderNum"
              type="number"
              style="width: 150px"
              placeholder="请输入显示顺序"
            />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm" v-show="form.categoryId">修 改</el-button>
            <el-button type="primary" @click="submitForm" v-show="!form.categoryId"
              >新 增</el-button
            >
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'
import {
  Search,
  Refresh,
  InfoFilled,
  Check,
  CircleClose,
  Plus,
  View,
  Delete
} from '@element-plus/icons-vue'
import { parseTime } from '@/utils/dateUtil'

// API 导入
import {
  addCategory,
  delCategory,
  getCategory,
  listCategory,
  updateCategory
} from '@/api/pms/video/category'

const { t } = useI18n() // 国际化
// 定义响应式数据
const isTenant = ref(false)
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const categoryList = ref([])
const open = ref(false)
const queryFormRef = ref(ElForm)
const formRef = ref()

// 查询参数
const queryParams = reactive({
  showSenior: false,
  pageNo: 1,
  pageSize: 20,
  categoryName: null,
  isSys: null
})

// 表单参数
const form = reactive({
  categoryId: null,
  categoryName: null,
  tenantId: null,
  tenantName: null,
  isSys: null,
  parentId: null,
  orderNum: null,
  delFlag: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  remark: null
})

// 表单校验规则
const rules = {
  categoryName: [
    {
      required: true,
      message: t('product.category142342-4'),
      trigger: 'blur'
    }
  ],
  isSys: [
    {
      required: true,
      message: t('product.category142342-5'),
      trigger: 'blur'
    }
  ]
}

// 初始化
const init = () => {
  // 这里假设 store 可通过 useStore 获取
  // const store = useStore()
  // if (store.state.user.roles.indexOf('tenant') !== -1) {
  //   isTenant.value = true
  // }
}

// 获取列表数据
const getList = () => {
  loading.value = true
  listCategory(queryParams).then((response) => {
    console.log(response)
    categoryList.value = response.list
    total.value = response.total
    loading.value = false
  })

  // 测试数据
  // setTimeout(() => {
  //     categoryList.value = [
  //     {
  //       categoryId: 1,
  //       categoryName: '分类1',
  //       tenantId: null,
  //       tenantName: null,
  //       isSys: '0',
  //       parentId: null,
  //       orderNum: 1,
  //       delFlag: null,
  //       createBy: null,
  //       createTime: '2023-05-05T09:09:09.000+00:00',
  //     }
  //   ]
  //   total.value = 1
  //   loading.value = false
  // }, 1000)
}

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

// 重置表单
const reset = () => {
  Object.assign(form, {
    categoryId: null,
    categoryName: null,
    tenantId: null,
    tenantName: null,
    isSys: null,
    parentId: null,
    orderNum: null,
    delFlag: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  })

  // 修复：正确调用表单重置方法
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

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

// 重置查询
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.categoryId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = t('product.category142342-6')
}

// 修改操作
const handleUpdate = (row) => {
  reset()
  const categoryId = row.categoryId || ids.value

  Object.assign(form, row)
  open.value = true
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (form.categoryId != null) {
        updateCategory(form).then((response) => {
          ElMessage.success('更新成功')
          open.value = false
          getList()
        })
      } else {
        addCategory(form).then((response) => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除操作
const handleDelete = (row) => {
  const categoryIds = row.categoryId || ids.value
  let msg = ''
  ElMessageBox.confirm(t('product.category142342-8', [categoryIds]), '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      return delCategory(categoryIds).then((response) => {
        msg = response.msg
      })
    })
    .then(() => {
      getList()
      ElMessage.success(msg)
    })
    .catch(() => {})
}

// 在挂载时获取数据
onMounted(() => {
  getList()
  init()
})
</script>
