<template>
  <div class="app-container content-page">
    <el-card class="box-card border-none main-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="header-title">{{ form.id ? '修改商品' : '创建商品' }}</span>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px" class="goods-form">
        <!-- 1. 商品名称 -->
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名称" class="form-input" />
        </el-form-item>

        <!-- 2. 商品类型 -->
        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择" class="form-input" clearable>
            <el-option
              v-for="dict in main_goods_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>

        <!-- 3. 绑定岗位 -->
        <el-form-item label="绑定岗位" prop="positionId">
          <el-select v-model="form.positionId" placeholder="请选择" class="form-input" clearable @change="handlePostChange">
            <el-option
              v-for="item in positionOptions"
              :key="item.id"
              :label="item.postName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 4. 商品内容 -->
        <el-form-item label="商品内容" prop="contentType">
          <div class="content-type-section">
            <el-radio-group v-model="form.contentType" class="content-toggle">
              <el-radio-button :label="1">富文本</el-radio-button>
              <el-radio-button :label="2">链接</el-radio-button>
            </el-radio-group>

            <div class="content-field mt20">
              <!-- 富文本编辑器 -->
              <div v-if="form.contentType === 1" class="editor-wrapper">
                <editor v-model="form.content" :min-height="300" />
              </div>

              <!-- 链接输入 -->
              <div v-else class="link-wrapper">
                <el-input v-model="form.content" placeholder="https://" class="form-input" />
              </div>
            </div>
          </div>
        </el-form-item>

        <!-- 底部按钮 -->
        <div class="form-actions mt40">
          <el-button @click="handleCancel" class="cancel-btn">取消</el-button>
          <el-button type="primary" @click="handleSave" class="save-btn">保存</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getGoods, addGoods, updateGoods } from '@/api/main/goods';
import { GoodsForm } from '@/api/main/goods/types';
import { listPosition } from '@/api/main/position';

const { proxy } = getCurrentInstance() as any;
const { main_goods_type } = proxy.useDict('main_goods_type');

const router = useRouter();
const route = useRoute();
const formRef = ref();
const positionOptions = ref<any[]>([]);

const form = ref<GoodsForm>({
  productName: '',
  productType: undefined,
  contentType: 1,
  content: '',
  positionId: undefined,
  positionName: ''
});

const rules = {
  productName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  productType: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
  contentType: [{ required: true, message: '请选择内容类型', trigger: 'change' }]
};

/** 查询岗位列表 */
const getPositionList = async () => {
  const res = await listPosition();
  positionOptions.value = res.rows || [];
};

/** 处理岗位变更 */
const handlePostChange = (val: any) => {
  const post = positionOptions.value.find(item => item.id === val);
  if (post) {
    form.value.positionName = post.postName;
  }
};

onMounted(async () => {
  await getPositionList();
  const id = route.query.id as string;
  if (id) {
    const res = await getGoods(id);
    Object.assign(form.value, res.data);
    // 确保后端返回的数值类型能匹配字典里的字符串类型的 value
    if (form.value.productType !== undefined && form.value.productType !== null) {
      form.value.productType = Number(form.value.productType) as any;
    }
  }
});

const handleCancel = () => {
  proxy.$tab.closePage();
};

const handleSave = () => {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 提交时保持字符串或数字，后端通常都能兼容
      if (form.value.id) {
        await updateGoods(form.value);
        ElMessage.success('修改成功');
      } else {
        await addGoods(form.value);
        ElMessage.success('新增成功');
      }
      proxy.$tab.closePage();
    }
  });
};
</script>

<style scoped lang="scss">
.w100 {
  width: 100%;
}

.content-page {
  background-color: #fff;
  min-height: calc(100vh - 84px);
  padding: 40px;
  display: flex;
  justify-content: center;
}

.main-card {
  width: 100%;
  max-width: 900px;
  border: none !important;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.goods-form {
  margin-top: 20px;
}

.form-input {
  width: 100%;
  max-width: 480px;
}

.content-type-section {
  width: 100%;
}

.content-toggle {
  :deep(.el-radio-button__inner) {
    padding: 8px 20px;
    border-radius: 4px;
    margin-right: 10px;
    border: 1px solid #dcdfe6 !important;
    box-shadow: none !important;
  }
  
  :deep(.el-radio-button:first-child .el-radio-button__inner) {
    border-radius: 4px;
  }
  
  :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
    background-color: #fff;
    color: #409eff;
    border-color: #409eff !important;
  }
}

.editor-wrapper {
  background: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.mt20 { margin-top: 20px; }
.mt40 { margin-top: 40px; }

.form-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.cancel-btn {
  width: 100px;
}

.save-btn {
  width: 100px;
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  
  &::before {
    margin-right: 4px !important;
  }
}
</style>
