<template>
  <div class="p-4">
    <div class="mb-4">
      <el-button link type="primary" @click="goBack">返回</el-button>
    </div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">{{ pageTitle }}</span>
        </div>
      </template>

      <el-form ref="brandFormRef" :model="form" :rules="rules" label-width="140px" class="max-w-5xl">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌名称" prop="brandName">
              <el-input v-model="form.brandName" placeholder="京东方" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌首字母" prop="brandInitials">
              <el-input v-model="form.brandInitials" placeholder="请输入品牌首字母" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌名称（英文）" prop="brandEnglishName">
              <el-input v-model="form.brandEnglishName" placeholder="请输入品牌英文名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌推荐系数" prop="recommendValue">
              <el-input-number
                v-model="form.recommendValue"
                :min="0"
                :max="9999"
                controls-position="right"
                style="width: 100%"
                placeholder="请输入推荐系数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="品牌标题" prop="brandTitle">
          <el-input v-model="form.brandTitle" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="品牌LOGO" prop="brandLogo">
          <image-upload v-model="form.brandLogo" />
        </el-form-item>

        <el-form-item label="品牌故事" prop="brandStory">
          <el-input v-model="form.brandStory" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="是否显示" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
          <div class="text-gray-500 text-sm mt-2">
            当品牌下还没有商品的时候。分类的品牌区不会不显示品牌。
          </div>
        </el-form-item>

        <el-form-item label="品牌介绍" prop="brandDescribe">
          <editor v-model="form.brandDescribe" :min-height="192" />
        </el-form-item>

        <el-form-item label="商标注册人" prop="brandRegistrant">
          <el-input v-model="form.brandRegistrant" placeholder="请输入商标注册人" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上传营业执照" prop="license">
              <image-upload v-model="form.license" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传商标注册证" prop="registrationCertificate">
              <image-upload v-model="form.registrationCertificate" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="到期时间" prop="expireTime">
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择"
            style="width: 100%"
          />
        </el-form-item>

        <el-divider content-position="left">授权信息</el-divider>

        <el-table :data="authorizationList" border style="margin-bottom: 20px">
          <el-table-column label="供应商名称" prop="supplierName" align="center" />
          <el-table-column label="品牌名称" prop="brandName" align="center" />
          <el-table-column label="一级类目" prop="firstCategory" align="center" />
          <el-table-column label="二级类目" prop="secondCategory" align="center" />
          <el-table-column label="三级类目" prop="thirdCategory" align="center" />
          <el-table-column label="截止时间" prop="deadline" align="center" />
          <el-table-column label="授权区域(省)" prop="provinceArea" align="center" />
          <el-table-column label="授权区域(市)" prop="cityArea" align="center" />
          <el-table-column label="状态" prop="status" align="center" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="handleEditAuth(scope.$index)">编辑</el-button>
              <el-button link type="danger" size="small" @click="handleDeleteAuth(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button type="primary" plain @click="handleAddAuth">添加授权</el-button>

        <el-form-item>
          <el-button type="primary" :loading="buttonLoading" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="BrandEdit">
import { getBrand, addBrand, updateBrand } from '@/api/product/brand';
import { BrandForm } from '@/api/product/brand/types';

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const brandFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const pageTitle = computed(() => {
  return route.query.type === 'add' ? '新增品牌' : '编辑品牌';
});

// 授权信息列表
const authorizationList = ref<any[]>([]);

const initFormData: BrandForm = {
  id: undefined,
  brandNo: undefined,
  brandName: undefined,
  brandInitials: undefined,
  brandEnglishName: undefined,
  recommendValue: undefined,
  brandLogo: undefined,
  brandTitle: undefined,
  brandBigImage: undefined,
  brandStory: undefined,
  isShow: 1,
  brandRegistrant: undefined,
  license: undefined,
  registrationCertificate: undefined,
  expireTime: undefined,
  brandDescribe: undefined,
  position: undefined,
  care: undefined,
  dataSource: undefined,
  remark: undefined,
}

const form = ref<BrandForm>({ ...initFormData });

const rules = reactive({
  brandName: [
    { required: true, message: "品牌名称不能为空", trigger: "blur" }
  ],
  brandInitials: [
    { required: false, message: "品牌首字母缩写不能为空", trigger: "blur" }
  ],
  brandEnglishName: [
    { required: false, message: "品牌英文名称不能为空", trigger: "blur" }
  ]
});

/** 获取品牌详情 */
const getDetail = async () => {
  const id = route.query.id as string;
  if (id && route.query.type !== 'add') {
    const res = await getBrand(id);
    form.value = res.data;
    // TODO: 加载授权信息列表
  }
};

/** 添加授权 */
const handleAddAuth = () => {
  authorizationList.value.push({
    supplierName: '',
    brandName: form.value.brandName,
    firstCategory: '',
    secondCategory: '',
    thirdCategory: '',
    deadline: '',
    provinceArea: '',
    cityArea: '',
    status: ''
  });
};

/** 编辑授权 */
const handleEditAuth = (index: number) => {
  // TODO: 实现编辑授权逻辑
  proxy?.$modal.msgInfo('编辑授权功能待实现');
};

/** 删除授权 */
const handleDeleteAuth = (index: number) => {
  authorizationList.value.splice(index, 1);
};

/** 提交表单 */
const submitForm = () => {
  brandFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateBrand(form.value);
        } else {
          await addBrand(form.value);
        }
        proxy?.$modal.msgSuccess("操作成功");
        goBack();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 返回 */
const goBack = () => {
  router.back();
};

onMounted(() => {
  getDetail();
});
</script>
