<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-position="top">
      <el-form-item label="角色" prop="postIds" label-position="top">
        <el-select v-model="queryParams.postIds" placeholder="请选择角色" clearable>
          <el-option
            v-for="post in postOptions"
            :key="post.postId"
            :label="post.postName"
            :value="Number(post.postId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="首页" prop="homePageType" label-position="top">
        <el-select v-model="queryParams.homePageType" placeholder="请选择首页" clearable>
          <el-option
            v-for="dict in home_page_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" label-position="top">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label-position="top">
        <div class="item-search">&nbsp;</div>
        <div class="item-search">
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </div>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:postHomePage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:postHomePage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:postHomePage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:postHomePage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postHomePageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="配置名称" prop="name" />
      <el-table-column label="角色" prop="postIds">
        <template #default="scope">
          {{ getPostNamesByIds(scope.row.postIds) }}
        </template>
      </el-table-column>
      <el-table-column label="首页" prop="homePageType">
        <template #default="scope">
          <dict-tag :options="home_page_type" :value="scope.row.homePageType" />
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="createBy" />
      <el-table-column label="创建时间" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新者" prop="updateBy" />
      <el-table-column label="更新时间" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column label="操作" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['system:postHomePage:edit']"><i class="fa fa-edit"></i>编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['system:postHomePage:remove']"><i class="fa fa-trash"></i>删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改首页配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postHomePageRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="配置名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="角色" prop="postIds">
          <el-select v-model="form.postIds" placeholder="请选择角色" clearable multiple>
            <el-option
              label="默认"
              :value="-1"
            />
            <el-option
              v-for="post in postOptions"
              :key="post.postId"
              :label="post.postName"
              :value="Number(post.postId)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="首页" prop="homePageType">
          <el-select v-model="form.homePageType" placeholder="请选择首页" clearable>
            <el-option
              v-for="dict in home_page_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </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">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PostHomePage">
import { listPostHomePage, addPostHomePage, delPostHomePage, getPostHomePage, updatePostHomePage, listPost, listRole } from "@/api/system/postHomePage"

const { proxy } = getCurrentInstance()
const { sys_normal_disable, home_page_type } = proxy.useDict("sys_normal_disable", "home_page_type")

const postHomePageList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const postOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    postIds: undefined,
    homePageType: undefined,
    status: undefined
  },
  rules: {
    name: [{ required: true, message: "配置名称不能为空", trigger: "blur" }],
    postIds: [{ required: true, message: "角色不能为空", trigger: "blur" }],
    homePageType: [{ required: true, message: "首页不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 根据角色ID获取角色名称 */
function getPostNameById(postId) {
  if (postId === "-1" || postId === -1) {
    return "默认"
  }
  // 确保类型匹配，将postId转换为字符串进行比较
  const postIdStr = String(postId);
  const post = postOptions.value.find(item => String(item.postId) === postIdStr)
  return post ? post.postName : postId
}

/** 根据角色IDs获取角色名称列表 */
function getPostNamesByIds(postIds) {
  if (!postIds) return ""
  
  // 如果是字符串，先转换为数组
  const ids = Array.isArray(postIds) ? postIds : postIds.toString().split(",")
  
  return ids.map(id => getPostNameById(id)).join(", ")
}

/** 获取岗位列表 */
function getPostList() {
  listPost({ status: "0" }).then(response => {
    postOptions.value = response.data
  })
}

/** 获取角色列表 */
function getRoleList() {
  listRole({ status: "0" }).then(response => {
    postOptions.value = []
    if(response.data.length>0) {
      console.log(response.data);
      for(let i=0;i<response.data.length;i++) {
        const role = response.data[i]
        role.postId = role.roleId
        role.postName = role.roleName
        postOptions.value.push(role)
      }
    }
  })
}

/** 查询首页配置列表 */
function getList() {
  loading.value = true
  // 处理查询参数
  const params = { ...queryParams.value }
  
  // 如果postIds有值且是数组，转换为逗号分隔的字符串
  if (params.postIds && Array.isArray(params.postIds)) {
    params.postIds = params.postIds.join(',')
  }
  
  listPostHomePage(params).then(response => {
    postHomePageList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    postIds: undefined,
    homePageType: undefined,
    status: "0", // 默认正常状态
    name: undefined,
    remark: undefined
  }
  proxy.resetForm("postHomePageRef")
}

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

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加首页配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || (ids.value.length > 0 ? ids.value[0] : null)
  if (id) {
    getPostHomePage(id).then(response => {
      form.value = response.data
      // 处理多选框的值
      if (form.value.postIds && typeof form.value.postIds === 'string') {
        // 将逗号分隔的字符串转换为数组，并确保数据类型正确
        form.value.postIds = form.value.postIds.split(',').map(id => {
          // 如果是数字字符串，转换为数字；否则保持字符串
          return isNaN(id) ? id : Number(id)
        })
      }
      open.value = true
      title.value = "修改首页配置"
    })
  } else {
    proxy.$modal.msgWarning("请选择要修改的数据")
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["postHomePageRef"].validate(valid => {
    if (valid) {
      // 处理表单数据
      const formData = { ...form.value }
      
      // 处理多选框的值
      if (Array.isArray(formData.postIds)) {
        formData.postIds = formData.postIds.join(',')
      }
      
      // 确保所有必需字段都有值
      if (!formData.postIds) {
        proxy.$modal.msgError("请选择角色")
        return
      }
      
      if (!formData.homePageType) {
        proxy.$modal.msgError("请选择首页")
        return
      }
      
      if (!formData.name) {
        proxy.$modal.msgError("请输入配置名称")
        return
      }
      
      if (!formData.status) {
        formData.status = "0" // 默认正常状态
      }
      
      // 根据当前操作类型决定调用新增还是修改接口
      // 如果是新增操作（title为"添加首页配置"），调用新增接口
      if (title.value === "添加首页配置") {
        addPostHomePage(formData).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError("新增失败: " + response.msg)
          }
        }).catch(error => {
          proxy.$modal.msgError("新增失败: " + error.message)
        })
      } else {
        // 否则是修改操作
        updatePostHomePage(formData).then(response => {
          if (response.code === 200) {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError("修改失败: " + response.msg)
          }
        }).catch(error => {
          proxy.$modal.msgError("修改失败: " + error.message)
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id ? [row.id] : ids.value
  if (ids && ids.length > 0) {
    proxy.$modal.confirm('是否确认删除选中的数据项？').then(function() {
      return delPostHomePage(ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  } else {
    proxy.$modal.msgWarning("请选择要删除的数据")
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/postHomePage/export", queryParams.value, `postHomePage_${new Date().getTime()}.xlsx`)
}

// getPostList()
getRoleList()
getList()
</script>