<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="请输入品牌名称" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌首字母" prop="brandInitials" required>
              <el-input v-model="form.brandInitials" placeholder="请输入品牌首字母" :disabled="isView" />
            </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="请输入品牌英文名称" :disabled="isView" />
            </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="请输入推荐系数"
                :disabled="isView"
              />
            </el-form-item>
          </el-col>
        </el-row>

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

        <el-form-item label="品牌LOGO" prop="brandLogo" required>
          <image-upload v-model="form.brandLogo" valueType="url" :isShowTip="false" :disabled="isView" />
        </el-form-item>

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

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

        <el-form-item label="品牌介绍" prop="brandDescribe">
          <template v-if="isView">
            <div class="w-full" v-html="form.brandDescribe"></div>
          </template>
          <template v-else>
            <editor v-model="form.brandDescribe" :min-height="192" />
          </template>
        </el-form-item>

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

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="上传营业执照" prop="license">
              <image-upload v-model="form.license" valueType="url" :isShowTip="false" :disabled="isView" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传商标注册证" prop="registrationCertificate">
              <image-upload v-model="form.registrationCertificate" valueType="url" :isShowTip="false" :disabled="isView" />
            </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%"
            :disabled="isView"
          />
        </el-form-item> -->

        <el-form-item v-if="!isAdd" label="授权信息：" style="margin-bottom: 0">
          <div class="w-full">
            <el-table :data="form.supplierAuthorizeList" border style="width: 100%">
              <el-table-column type="index" label="序号" align="center" width="80" />
              <el-table-column prop="supplierName" label="供应商名称" align="center" />
              <el-table-column prop="brandName" label="品牌名称" align="center" />
              <el-table-column label="一级类目" align="center">
                <template #default="scope">
                  <span>{{ scope.row.categorysMap?.oneLevelName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="二级类目" align="center">
                <template #default="scope">
                  <span>{{ scope.row.categorysMap?.twoLevelName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column label="三级类目" align="center">
                <template #default="scope">
                  <span>{{ scope.row.categorysMap?.threeLevelName || '-' }}</span>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="authorizationEndTime" label="截止时间" align="center">
                <template #default="scope">
                  <span>{{ scope.row.authorizationEndTime ? scope.row.authorizationEndTime.split(' ')[0] : '-' }}</span>
                </template>
              </el-table-column> -->
              <el-table-column prop="province" label="授权区域(省)" align="center" show-overflow-tooltip />
              <el-table-column prop="city" label="授权区域(市)" align="center" show-overflow-tooltip />
              <el-table-column prop="authorizedStatus" label="状态" align="center">
                <template #default="scope">
                  <dict-tag :options="authorized_status" :value="scope.row.authorizedStatus" />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="100">
                <template #default="scope">
                  <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <el-form-item v-if="!isView">
          <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 { authorized_status } = toRefs<any>(proxy?.useDict('authorized_status'));

const isAdd = computed(() => route.query.type === 'add');
const isView = computed(() => route.query.type === 'view');

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


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,
  supplierAuthorizeList: [],
}

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

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

/** 获取品牌详情 */
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;
  }
};


/** 查看授权详情 */
const handleView = (row: any) => {
  router.push({
    path: '/supplierexam/detail',
    query: { id: row.id }
  });
};

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

/** 提交表单 */
const submitForm = () => {
  if (isView.value) return;
  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>
