<template>
  <div class="bottom-icon-nav">
    <!-- 颜色设置区域 -->
    <div class="color-settings">
      <h3 class="section-title">颜色设置</h3>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="文字选中颜色" required>
            <div class="color-input-group">
              <el-color-picker 
                v-model="selectedTextColor" 
                show-alpha 
                size="large"
                class="color-picker"
                @change="handleSelectedColorChange"
              />
              <el-input 
                v-model="selectedTextColorInput" 
                placeholder="#RRGGBB"
                class="color-input"
                @input="handleSelectedColorInput"
                @blur="validateSelectedColorInput"
              />
              <span class="color-value">{{ selectedTextColor }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="文字未选中颜色" required>
            <div class="color-input-group">
              <el-color-picker 
                v-model="unselectedTextColor" 
                show-alpha 
                size="large"
                class="color-picker"
                @change="handleUnselectedColorChange"
              />
              <el-input 
                v-model="unselectedTextColorInput" 
                placeholder="#RRGGBB"
                class="color-input"
                @input="handleUnselectedColorInput"
                @blur="validateUnselectedColorInput"
              />
              <span class="color-value">{{ unselectedTextColor }}</span>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <!-- 底部导航栏区域 -->
    <div class="icon-nav-section">
      <h3 class="section-title">底部导航栏</h3>
      <div class="icon-grid">
        <!-- 图标项 -->
        <div 
          v-for="item in iconList" 
          :key="item.iconId" 
          class="icon-item"
        >
          <div class="icon-image">
            <img 
              v-if="item.iconSelected" 
              :src="item.iconSelected" 
              :alt="item.iconSelected" 
            />
            <div v-else class="default-icon">
              <el-icon><HomeFilled /></el-icon>
            </div>
          </div>
          <div class="icon-name">
            {{ item.name }}
          </div>
          
          <div class="icon-actions">
            <el-button 
              type="success" 
              size="small" 
              @click.stop="handleUpdate(item)"
            >
              编辑
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click.stop="handleDelete(item)"
            >
              删除
            </el-button>
          </div>
        </div>

        <!-- 添加新项目卡片 -->
        <!-- <div class="add-item" @click="handleAdd">
          <el-icon class="add-icon"><Plus /></el-icon>
          <div class="add-text">添加新项目</div>
        </div> -->
      </div>
    </div>

    <!-- 保存按钮 -->
    <div class="actions">
      <el-button type="primary" size="large" @click="handleSave" :loading="saving">
        保存
      </el-button>
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="720px" append-to-body>
      <el-form ref="iconRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="图标名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入图标名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序" prop="sortNum">
              <el-input-number v-model="form.sortNum" :min="1" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
         

        
        <el-form-item label="选中图标" prop="iconSelected">
          <el-upload
            class="icon-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :before-upload="beforeIconUpload"
            :on-success="handleSelectedIconSuccess"
          >
            <img v-if="form.iconSelected" :src="form.iconSelected" class="icon-preview" />
            <el-icon v-else class="icon-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸 100x100</div>
        </el-form-item>
        
        <el-form-item label="未选中图标" prop="iconUnselected">
          <el-upload
            class="icon-uploader"
            :action="uploadUrl"
            :headers="headers"
            :show-file-list="false"
            :before-upload="beforeIconUpload"
            :on-success="handleUnselectedIconSuccess"
          >
            <img v-if="form.iconUnselected" :src="form.iconUnselected" class="icon-preview" />
            <el-icon v-else class="icon-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸 100x100</div>
        </el-form-item>
        
        <el-form-item label="跳转类型" prop="jumpType">
          <el-radio-group v-model="form.jumpType" @change="handleJumpTypeChange">
            <el-radio :value="1">跳转链接</el-radio>
            <el-radio :value="2">不跳转</el-radio>
            <el-radio :value="3">小程序内链</el-radio>
            <el-radio :value="4">小程序外链</el-radio>
            <el-radio :value="5">H5外链</el-radio>
            <el-radio :value="6">公众号文章</el-radio>
            <el-radio :value="7">公众号</el-radio>
            <el-radio :value="8">电话拨号</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="跳转链接" prop="jumpPath">
          <el-input v-model="form.jumpPath" placeholder="请输入跳转链接" :disabled="form.jumpType === 2" />
        </el-form-item>
        
        <el-form-item label="小程序AppID" prop="appId" v-if="form.jumpType === 4">
          <el-input v-model="form.appId" placeholder="请输入对方小程序的AppID" />
        </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 lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { HomeFilled, Plus } from '@element-plus/icons-vue'
import { 
  listNavBottomIcon, 
  addNavBottomIcon, 
  updateNavBottomIcon, 
  delNavBottomIcon,
  saveColorSettings,
  getColorSettings,
  type VsNavBottomIconVo,
  type VsNavBottomIconBo
} from '@/api/system/common/scenic/nav'

// 响应式数据
const iconList = ref<VsNavBottomIconVo[]>([])
const open = ref(false)
const loading = ref(true)
const title = ref("")
const saving = ref(false)

// 颜色设置
const selectedTextColor = ref('#409EFF')
const unselectedTextColor = ref('#B2B5BD')

// 颜色输入框的值
const selectedTextColorInput = ref('#409EFF')
const unselectedTextColorInput = ref('#B2B5BD')

// 将RGB颜色转换为16进制
const rgbToHex = (rgb: string): string => {
  // 如果是16进制格式，直接返回
  if (rgb.startsWith('#')) {
    return rgb
  }
  
  // 如果是RGB格式，转换为16进制
  const rgbMatch = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/)
  if (rgbMatch) {
    const r = parseInt(rgbMatch[1])
    const g = parseInt(rgbMatch[2])
    const b = parseInt(rgbMatch[3])
    return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
  }
  
  // 如果无法解析，返回默认值
  return '#409EFF'
}

// 处理选中颜色输入框变化
const handleSelectedColorInput = (value: string) => {
  // 实时同步到颜色选择器
  if (value.startsWith('#')) {
    selectedTextColor.value = value
  }
}

// 处理选中颜色选择器变化
const handleSelectedColorChange = (value: string) => {
  // 当颜色选择器改变时，将16进制值填充到输入框
  if (value) {
    const hexValue = rgbToHex(value)
    selectedTextColorInput.value = hexValue
  }
}

// 处理未选中颜色输入框变化
const handleUnselectedColorInput = (value: string) => {
  // 实时同步到颜色选择器
  if (value.startsWith('#')) {
    unselectedTextColor.value = value
  }
}

// 处理未选中颜色选择器变化
const handleUnselectedColorChange = (value: string) => {
  // 当颜色选择器改变时，将16进制值填充到输入框
  if (value) {
    const hexValue = rgbToHex(value)
    unselectedTextColorInput.value = hexValue
  }
}

// 验证选中颜色输入框
const validateSelectedColorInput = () => {
  const hexRegex = /^#[0-9A-Fa-f]{6}$/
  if (!hexRegex.test(selectedTextColorInput.value)) {
    ElMessage.warning('请输入正确的16进制颜色格式，如 #FF0000')
    selectedTextColorInput.value = selectedTextColor.value
  }
}

// 验证未选中颜色输入框
const validateUnselectedColorInput = () => {
  const hexRegex = /^#[0-9A-Fa-f]{6}$/
  if (!hexRegex.test(unselectedTextColorInput.value)) {
    ElMessage.warning('请输入正确的16进制颜色格式，如 #FF0000')
    unselectedTextColorInput.value = unselectedTextColor.value
  }
}

// 处理跳转类型变化
const handleJumpTypeChange = (value: number) => {
  if (value === 2) {
    form.jumpPath = '#'
  } else if (value === 4) {
    form.jumpPath = ''
  }
}

const form = reactive<VsNavBottomIconBo>({
  iconId: undefined,
  name: '',
  pic: '',
  iconSelected: '',
  iconUnselected: '',
  jumpType: 2,
  jumpPath: '#',
  appId: '',
  sortNum: 1,
  remark: ''
})

const rules = {
  name: [
    { required: true, message: "图标名称不能为空", trigger: "blur" }
  ],
  pic: [
    { required: true, message: "图标图片不能为空", trigger: "change" }
  ],
  sortNum: [
    { required: true, message: "排序不能为空", trigger: "blur" }
  ]
}

// 上传相关
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadUrl = baseUrl + '/resource/oss/upload'
const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token') || ''
}

// 初始化数据
onMounted(() => {
  getList()
  loadColorSettings()
})

// 加载颜色设置
const loadColorSettings = async () => {
  try {
    const response = await getColorSettings()
    if (response.code === 200 && response.data) {
      const data = response.data as { selectedTextColor: string; unselectedTextColor: string }
      // 确保颜色值是16进制格式
      const hexSelectedColor = rgbToHex(data.selectedTextColor || '#409EFF')
      const hexUnselectedColor = rgbToHex(data.unselectedTextColor || '#B2B5BD')
      
      // 同步更新颜色选择器和输入框
      selectedTextColor.value = hexSelectedColor
      unselectedTextColor.value = hexUnselectedColor
      selectedTextColorInput.value = hexSelectedColor
      unselectedTextColorInput.value = hexUnselectedColor
    }
  } catch (error) {
    console.error('加载颜色设置失败:', error)
    // 使用默认的16进制颜色值
    const defaultSelectedColor = '#409EFF'
    const defaultUnselectedColor = '#B2B5BD'
    selectedTextColor.value = defaultSelectedColor
    unselectedTextColor.value = defaultUnselectedColor
    selectedTextColorInput.value = defaultSelectedColor
    unselectedTextColorInput.value = defaultUnselectedColor
  }
}

/** 查询底部图标导航列表 */
async function getList() {
  loading.value = true
  try {
    const response = await listNavBottomIcon({
      pageNum: 1,
      pageSize: 50
    })
    
    if (response.code === 200) {
      iconList.value = response.rows || []
    } else {
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加底部图标导航"
}

/** 修改按钮操作 */
function handleUpdate(row: VsNavBottomIconVo) {
  reset()
  const formData = {
    iconId: row.iconId,
    name: row.name,
    pic: row.pic,
    iconSelected: row.iconSelected || '',
    iconUnselected: row.iconUnselected || '',
    jumpType: row.jumpType || 2,
    jumpPath: row.jumpType === 2 ? (row.jumpPath || '#') : row.jumpPath,
    appId: row.appId,
    sortNum: row.sortNum,
    remark: row.remark || ''
  }
  Object.assign(form, formData)
  open.value = true
  title.value = "修改底部图标导航"
}

/** 提交按钮 */
async function submitForm() {
  try {
    let response
    if (form.iconId != null) {
      response = await updateNavBottomIcon(form)
    } else {
      response = await addNavBottomIcon(form)
    }
    
    if (response.code === 200) {
      ElMessage.success(form.iconId ? "修改成功" : "新增成功")
      open.value = false
      getList()
    } else {
      ElMessage.error(response.msg || "操作失败")
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

/** 删除按钮操作 */
async function handleDelete(row: VsNavBottomIconVo) {
  const _iconId = row.iconId!
  const itemName = row.name || '未知'
  
  try {
    // 第一次确认
    await ElMessageBox.confirm(
      `是否确认删除图标导航"${itemName}"？`, 
      '第一次确认', 
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 第二次确认
    await ElMessageBox.confirm(
      `请再次确认是否删除图标导航"${itemName}"？`, 
      '第二次确认', 
      {
        confirmButtonText: '再次确认删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 第三次确认
    await ElMessageBox.confirm(
      `最后一次确认：是否删除图标导航"${itemName}"？\n\n请输入"DELETE"确认删除：`, 
      '最终确认', 
      {
        confirmButtonText: '最终确认删除',
        cancelButtonText: '取消',
        type: 'error',
        inputPattern: /^DELETE$/,
        inputErrorMessage: '请输入"DELETE"确认删除'
      }
    )
    
    // 执行删除
    const response = await delNavBottomIcon(_iconId)
    if (response.code === 200) {
      ElMessage.success("删除成功")
      getList()
    } else {
      ElMessage.error(response.msg || "删除失败")
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

/** 重置操作 */
function reset() {
  form.iconId = undefined
  form.name = ''
  form.pic = ''
  form.iconSelected = ''
  form.iconUnselected = ''
  form.jumpType = 2
  form.jumpPath = '#'
  form.appId = ''
  form.sortNum = 1
  form.remark = ''
}

// 图标上传前验证
const beforeIconUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图标上传成功
const handleIconSuccess = (response: any) => {
  if (response.code === 200) {
    form.pic = response.data.url
    ElMessage.success('图标上传成功')
  } else {
    ElMessage.error(response.msg || '图标上传失败')
  }
}

// 选中图标上传成功
const handleSelectedIconSuccess = (response: any) => {
  if (response.code === 200) {
    form.iconSelected = response.data.url
    ElMessage.success('选中图标上传成功')
  } else {
    ElMessage.error(response.msg || '选中图标上传失败')
  }
}

// 未选中图标上传成功
const handleUnselectedIconSuccess = (response: any) => {
  if (response.code === 200) {
    form.iconUnselected = response.data.url
    ElMessage.success('未选中图标上传成功')
  } else {
    ElMessage.error(response.msg || '未选中图标上传失败')
  }
}

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

// 处理保存颜色设置
const handleSave = async () => {
  saving.value = true
  try {
    // 验证输入框的值
    validateSelectedColorInput()
    validateUnselectedColorInput()
    
    // 使用输入框的值进行保存
    const hexSelectedColor = selectedTextColorInput.value
    const hexUnselectedColor = unselectedTextColorInput.value
    
    const response = await saveColorSettings({
      selectedTextColor: hexSelectedColor,
      unselectedTextColor: hexUnselectedColor
    })
    
    if (response.code === 200) {
      ElMessage.success('保存成功')
    } else {
      ElMessage.error(response.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}
</script>

<style lang="scss" scoped>
.bottom-icon-nav {
  padding: 20px;
}

.color-settings {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  
  .color-picker {
    margin-right: 10px;
  }
  
  .color-input-group {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .color-picker {
      flex-shrink: 0;
    }
    
    .color-input {
      width: 120px;
      flex-shrink: 0;
    }
    
    .color-value {
      font-family: monospace;
      color: #606266;
      font-size: 14px;
      flex-shrink: 0;
    }
  }
}

.icon-nav-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #409EFF;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
}

.icon-item {
  position: relative;
  padding: 20px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s ease;
  
  &:hover {
    border-color: #409EFF;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
  }
  
  .icon-image {
    margin-bottom: 15px;
    
    img {
      width: 50px;
      height: 50px;
      border-radius: 8px;
      object-fit: cover;
    }
    
    .default-icon {
      width: 50px;
      height: 50px;
      margin: 0 auto;
      background: #f5f7fa;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #909399;
      font-size: 24px;
    }
  }
  
  .icon-name {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 15px;
  }
  
  .icon-actions {
    display: flex;
    gap: 8px;
    justify-content: center;
  }
}

.add-item {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 150px;
  
  &:hover {
    border-color: #409EFF;
    color: #409EFF;
  }
  
  .add-icon {
    font-size: 32px;
    margin-bottom: 8px;
    color: #c0c4cc;
  }
  
  .add-text {
    font-size: 14px;
    color: #606266;
  }
}

.actions {
  text-align: left;
  margin-top: 20px;
}

.icon-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover {
    border-color: #409EFF;
  }
  
  .icon-uploader-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .icon-preview {
    width: 100px;
    height: 100px;
    object-fit: cover;
  }
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

.color-picker {
  width: 100%;
  margin-top: 10px;
}

.color-value {
  display: block;
  margin-top: 5px;
  font-size: 14px;
  color: #606266;
}

.dialog-footer {
  text-align: right;
}
</style>

