<template>
  <view class="container" style="paddingBottom:1rpx;">
    <u-navbar
      leftIconSize="40rpx"
      leftIconColor="#333333"
      :title="title"
    >
    </u-navbar>
    <view class="section">
      <view class="section-title">{{ title }}</view>
      <view class="form-view">
        <u--form labelPosition="left" :model="form" :rules="rules" ref="uForm" label-width="160rpx"
          :labelStyle="{ color: '#333333', fontSize: '30rpx', marginRight: '24rpx' }">
          <u-form-item label="字典类型">
            <u--input v-model="form.dictType" readonly disabledColor="#ffffff" placeholder="字典类型"
              inputAlign="left" :customStyle="inputBaseStyle"></u--input>
          </u-form-item>

          <u-form-item label="数据标签" prop="dictLabel" required>
            <u--input v-model="form.dictLabel" placeholder="请输入数据标签"
              inputAlign="left" :customStyle="getInputStyle('dictLabel')"></u--input>
          </u-form-item>

          <u-form-item label="数据键值" prop="dictValue" required>
            <u--input v-model="form.dictValue" placeholder="请输入数据键值"
              inputAlign="left" :customStyle="getInputStyle('dictValue')"></u--input>
          </u-form-item>

          <u-form-item label="显示排序" prop="dictSort" required>
            <u--input v-model="form.dictSort" type="number" placeholder="请输入显示排序"
              inputAlign="left" :customStyle="getInputStyle('dictSort')"></u--input>
          </u-form-item>

          <u-form-item label="回显样式" prop="listClassName" @click="showListClassPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="listClassName" readonly placeholder="请选择回显样式" :customStyle="getInputStyle('listClassName')" disabledColor="#ffffff" inputAlign="left"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="状态" prop="statusName" @click="showStatusPicker = true">
            <view class="input-with-arrow">
              <u--input v-model="statusName" readonly placeholder="请选择状态" :customStyle="getInputStyle('statusName')" disabledColor="#ffffff" inputAlign="left"></u--input>
              <text class="arrow-icon">▼</text>
            </view>
          </u-form-item>

          <u-form-item label="备注" prop="remark" labelPosition="top">
            <u--textarea v-model="form.remark" placeholder="请输入备注" autoHeight inputAlign="left" count
              maxlength="500" style="border: 2rpx solid #dcdfe6 !important; height: 160rpx;"></u--textarea>
          </u-form-item>
        </u--form>
        <view class="form-btn">
          <u-button type="primary" text="提交" @click="submit"></u-button>
        </view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <u-picker itemHeight="88" :show="showStatusPicker" :columns="statusList" keyName="dictLabel" @cancel="showStatusPicker = false"
      @confirm="handleStatusConfirm"></u-picker>
    <u-picker itemHeight="88" :show="showListClassPicker" :columns="listClassList" keyName="label" @cancel="showListClassPicker = false"
      @confirm="handleListClassConfirm"></u-picker>
  </view>
</template>

<script setup>
import { ref, reactive, getCurrentInstance } from 'vue'
import { getData, addData, updateData } from '@/api/system/dict/data'
import { getDicts } from "@/api/system/dict/data"
import { onLoad } from "@dcloudio/uni-app"

const { proxy } = getCurrentInstance()
const statusList = ref([])
const listClassList = ref([[
  { value: 'default', label: '默认' },
  { value: 'primary', label: '主要' },
  { value: 'success', label: '成功' },
  { value: 'info', label: '信息' },
  { value: 'warning', label: '警告' },
  { value: 'danger', label: '危险' }
]])
const title = ref('添加字典数据')
const showStatusPicker = ref(false)
const showListClassPicker = ref(false)
const statusName = ref('')
const listClassName = ref('')
const inputBaseStyle = {
  background: '#ffffff',
  border: '2rpx solid #dcdfe6',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const errorFields = ref([])
const inputErrorStyle = {
  background: '#fef0f0',
  border: '2rpx solid #f56c6c',
  borderRadius: '8rpx',
  padding: '0 24rpx',
  height: '68rpx',
  width: '100%',
  boxSizing: 'border-box'
}
const getInputStyle = (field) => {
  return errorFields.value.includes(field) ? inputErrorStyle : inputBaseStyle
}

const form = reactive({
  dictCode: undefined,
  dictType: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  dictSort: '0',
  listClass: 'default',
  status: '0',
  remark: undefined
})

const rules = {
  dictLabel: [
    { required: true, message: '数据标签不能为空', trigger: ['blur', 'change'] }
  ],
  dictValue: [
    { required: true, message: '数据键值不能为空', trigger: ['blur', 'change'] }
  ],
  dictSort: [
    { required: true, message: '显示排序不能为空', trigger: ['blur', 'change'] }
  ]
}

onLoad((option) => {
  getDicts('sys_normal_disable').then(res => {
    statusList.value = [res.data]
  })

  if (option.dictCode) {
    title.value = '修改字典数据'
    getDetail(option.dictCode)
  } else if (option.dictType) {
    form.dictType = option.dictType
    // 新增时默认显示状态和回显样式
    setTimeout(() => {
      updateStatusName()
      updateListClassName()
    }, 100)
  }
})

// 获取详情
function getDetail(dictCode) {
  getData(dictCode).then(res => {
    Object.assign(form, res.data)
    updateStatusName()
    updateListClassName()
  })
}

// 更新状态名称显示
function updateStatusName() {
  if (statusList.value.length > 0 && statusList.value[0].length > 0) {
    const item = statusList.value[0].find(v => v.dictValue === form.status)
    statusName.value = item ? item.dictLabel : ''
  }
}

// 更新回显样式名称显示
function updateListClassName() {
  if (listClassList.value.length > 0 && listClassList.value[0].length > 0) {
    const item = listClassList.value[0].find(v => v.value === form.listClass)
    listClassName.value = item ? item.label : ''
  }
}

// 状态选择确认
function handleStatusConfirm(e) {
  form.status = e.value[0].dictValue
  statusName.value = e.value[0].dictLabel
  showStatusPicker.value = false
}

// 回显样式选择确认
function handleListClassConfirm(e) {
  form.listClass = e.value[0].value
  listClassName.value = e.value[0].label
  showListClassPicker.value = false
}

// 提交
function submit() {
  errorFields.value = []
  proxy.$refs['uForm'].validate().then(() => {
    if (form.dictCode) {
      updateData(form).then(() => {
        proxy.$refs['uToast'].show({
          message: '修改成功', complete() {
            uni.navigateBack()
          }
        })
      })
    } else {
      addData(form).then(() => {
        proxy.$refs['uToast'].show({
          message: '新增成功', complete() {
            uni.navigateBack()
          }
        })
      })
    }
  }).catch(errors => {
    if (errors && errors.length > 0) {
      errorFields.value = errors.map(err => err.field)
    }
    proxy.$modal.msgError('请填写完整信息')
  })
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
}

.section {
  margin: 24rpx;
  padding: 0;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  overflow: hidden;

  .section-title {
    padding: 16rpx 24rpx;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #ffffff;
    line-height: 1.2;
    font-size: 28rpx;
    font-weight: 600;
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      width: 6rpx;
      height: 28rpx;
      background: #ffffff;
      border-radius: 3rpx;
      margin-right: 12rpx;
    }
  }

  .form-view {
    padding: 24rpx;



    .form-btn {
      padding-top: 16rpx;
    }
  }
}
</style>


