<template>
    <div class="app-container p-5">
      <el-form
        :model="queryParams"
        ref="queryForm"
        class="main-search"
            :inline="true"
        v-show="showSearch"
      >
        <el-form-item label="商品分类名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品分类名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="所属店铺" prop="store">
          <el-select
            v-model="queryParams.storeId"
            placeholder="所属店铺"
            clearable
            style="width: 180px"
          >
            <el-option
              :key="0"
              label="公共分类"
              v-if="!storeId"
              :value="0"
            />
            <el-option
              v-for="storeInfo in storeOptions"
              :key="storeInfo.id"
              :label="storeInfo.name"
              :value="storeInfo.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="状态"
            clearable
            style="width: 240px"
          >
            <el-option key="A" label="启用" value="A" />
            <el-option key="N" label="禁用" value="N" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleQuery">
            搜索
          </el-button>
          <el-button size="mini" @click="resetQuery">
            重置
          </el-button>
          <el-button
            type="primary"
            plain
            size="mini"
            @click="handleAdd"
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
  
      <el-table
        ref="tables"
        v-loading="loading"
        :data="list"
        @selection-change="handleSelectionChange"
        :default-sort="defaultSort"
        @sort-change="handleSortChange"
      >
        <el-table-column label="商品分类 ID" prop="id" width="80">
          <template #default="scope">
            <span>{{ showIdLastFour(scope.row.id) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属店铺" align="center">
          <template #default="scope">
            <span v-if="scope.row.storeName">{{ scope.row.storeName }}</span>
            <span v-else>全部分类</span>
          </template>
        </el-table-column>
        <el-table-column label="名称" align="center" prop="name" />
        <el-table-column label="图片" align="center" width="200">
          <template #default="scope">
            <img class="list-img" :src="scope.row.logo" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="A"
              inactive-value="N"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-if="storeId == scope.row.storeId || storeId == 0"
              @click="handleUpdate(scope.row)"
            >
              修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-if="storeId == scope.row.storeId || storeId == 0"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 添加或修改对话框 -->
      <el-dialog
        :title="title"
        v-model="open"
        class="common-dialog"
        width="700px"
        append-to-body
      >
        <el-form ref="addForm" :model="form" :rules="rules" >
          <el-row>
            <el-col :span="24">
              <el-form-item label="商品分类名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入商品分类名称"
                  maxlength="30"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="排序序号" prop="sort">
                <el-input-number v-model="form.sort" :min="0" />
                <div class="form-tips">提示：序号越大越靠前</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="9">
              <el-form-item label="图片" prop="image">
                <el-upload
                  :action="uploadAction"
                  :before-upload="beforeUpload"
                  accept="image/*"
                  list-type="picture-card"
                  :class="{ hide: hideUpload }"
                  :file-list="uploadFiles"
                  :auto-upload="true"
                  :show-file-list="false"
                  :headers="uploadHeader"
                  :on-success="handleUploadSuccess"
                >
                  <img v-if="form.logo" :src="form.logo" class="list-img" />
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <p class="form-tips">提示：请上传图片，仅支持图片格式，大小不超过 20MB</p>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  v-model="form.description"
                  type="textarea"
                  placeholder="请输入备注内容"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio key="A" label="A" value="A">启用</el-radio>
                  <el-radio key="N" label="N" value="N">禁用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  
  // 从 Vuex 中获取 storeId，这里假设 Vuex 配置正确
  const storeId = ref(0)
  
  // 遮罩层
  const loading = ref(true)
  // 标题
  const title = ref('')
  // 选中数组
  const ids = ref([])
  // 非多个禁用
  const multiple = ref(true)
  // 显示搜索条件
  const showSearch = ref(true)
  // 图片根目录
  const imagePath = ref('')
  // 总条数
  const total = ref(0)
  // 表格数据
  const list = ref([])
  // 店铺列表
  const storeOptions = ref([])
  // 是否显示弹出层
  const open = ref(false)
  // 默认排序
  const defaultSort = ref({ prop: 'sort', order: 'descending' })
  // 表单参数
  const form = ref({
    storeId: 0,
    id: '',
    name: '',
    logo: '',
    sort: 0,
    status: 'A'
  })
  // 上传地址
  const uploadAction = ref('/backendApi/file/upload')
  const uploadHeader = ref({ 'Access-Token': '假token' })
  // 隐藏上传
  const hideUpload = ref(false)
  // 上传文件列表
  const uploadFiles = ref([])
  // 查询参数
  const queryParams = reactive({
    page: 1,
    pageSize: 10,
    name: '',
    status: ''
  })
  // 表单校验
  const rules = ref({
    name: [
      { required: true, message: '商品分类名称为必填项', trigger: 'blur' },
      {
        min: 2,
        max: 200,
        message: '商品分类名称长度应在 2 到 200 个字符之间',
        trigger: 'blur'
      }
    ],
    logo: [
      { required: true, message: '请上传图片', trigger: 'blur' }
    ]
  })
  
  // 假数据模拟
  const fakeGoodsCateList = [
    {
      id: 1,
      storeName: '店铺1',
      name: '分类1',
      logo: 'https://example.com/logo1.png',
      createTime: '2023-01-01 00:00:00',
      updateTime: '2023-01-01 00:00:00',
      status: 'A'
    },
    {
      id: 2,
      storeName: null,
      name: '分类2',
      logo: 'https://example.com/logo2.png',
      createTime: '2023-01-02 00:00:00',
      updateTime: '2023-01-02 00:00:00',
      status: 'N'
    }
  ]
  
  const fakeStoreOptions = [
    { id: 1, name: '店铺1' },
    { id: 2, name: '店铺2' }
  ]
  
  onMounted(() => {
    getList()
  })
  
  // 查询分类列表
  const getList = () => {
    loading.value = true
    // 使用假数据
    list.value = fakeGoodsCateList
    total.value = fakeGoodsCateList.length
    storeOptions.value = fakeStoreOptions
    loading.value = false
  }
  
  // 搜索按钮操作
  const handleQuery = () => {
    queryParams.page = 1
    getList()
  }
  
  // 重置按钮操作
  const resetQuery = () => {
    // 这里简单重置表单数据，未实现完整的表单重置
    queryParams.name = ''
    queryParams.status = ''
    queryParams.page = 1
    getList()
  }
  
  // 状态修改
  const handleStatusChange = (row) => {
    let text = row.status == 'A' ? '启用' : '禁用'
    ElMessageBox.confirm(`确认要将 ${row.name} 设置为 ${text} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 模拟状态修改成功
      ElMessage.success(`${text} 成功`)
    }).catch(() => {
      row.status = row.status === 'N' ? 'A' : 'N'
    })
  }
  
  // 多选框选中数据
  const handleSelectionChange = (selection) => {
    ids.value = selection.map((item) => item.id)
    multiple.value = !selection.length
  }
  
  // 排序触发事件
  const handleSortChange = (column, prop, order) => {
    queryParams.orderByColumn = column.prop
    queryParams.isAsc = column.order
    getList()
  }
  
  // 新增按钮操作
  const handleAdd = () => {
    reset()
    open.value = true
    title.value = '新增商品分类'
  }
  
  // 表单重置
  const reset = () => {
    form.value = {
      id: '',
      storeId: storeId.value,
      name: '',
      status: 'A',
      logo: '',
      sort: 0,
      description: ''
    }
    uploadFiles.value = []
  }
  
  // 取消按钮
  const cancel = () => {
    open.value = false
    reset()
  }
  
  const addForm = ref(null)
  // 提交按钮
  const submitForm = () => {
    // const formEl = getCurrentInstance().refs.form
    addForm.value.validate((valid) => {
      if (valid) {
        if (form.value.logo.length < 1) {
          form.value.logo = '/static/defaultImage/none.png'
        }
        if (form.value.id) {
          // 模拟修改成功
          ElMessage.success('修改成功')
          open.value = false
          getList()
        } else {
          // 模拟新增成功
          ElMessage.success('新增成功')
          open.value = false
          getList()
        }
      }
    })
  }
  
  // 修改按钮操作
  const handleUpdate = (row) => {
    reset()
    const id = row.id
    // 模拟获取数据成功
    form.value = {
      id: id,
      storeId: row.storeId,
      name: row.name,
      logo: row.logo,
      sort: row.sort,
      status: row.status,
      description: '模拟描述'
    }
    uploadFiles.value = [{ url: form.value.logo, status: 'finished' }]
    open.value = true
    title.value = '编辑商品分类'
  }
  
  // 删除按钮操作
  const handleDelete = (row) => {
    const name = row.name
    ElMessageBox.confirm(`确认要删除 ${name} 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      // 模拟删除成功
      getList()
      ElMessage.success('删除成功')
    }).catch(() => {})
  }
  
  // 图片上传之前的大小和类型判断
  const beforeUpload = (file) => {
    // 限制文件大小为 20MB
    const isImage = file.type.startsWith('image/') // 判断文件类型是否为图片
    const isLt2M = file.size / 1024 / 1024 < 20 // 判断文件大小是否小于 20MB
  
    if (!isImage) {
      ElMessage.error('仅支持上传图片')
    }
  
    if (!isLt2M) {
      ElMessage.error('图片大小不能超过 20MB')
    }
  
    return isImage && isLt2M // 返回 true 则允许上传，返回 false 则阻止上传
  }
  
  const handleUploadSuccess = (file) => {
    form.value.logo = file.data.url
  }
  
  const showIdLastFour = (id) => {
    return String(id).slice(-4)
  }
  
  const parseTime = (time) => {
    return time
  }
  
  </script>
  
  <style scoped>
  .common-dialog >>> .el-upload--picture-card {
    width: 60px;
    height: 50px;
    line-height: 60px;
  }
  </style>    