<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="官方品牌名称" prop="brandName">
              <el-input v-model="queryParams.brandName" placeholder="请输入官方品牌名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="第三方品牌名称" prop="thirdPartyBrandName">
              <el-input v-model="queryParams.thirdPartyBrandName" placeholder="请输入第三方品牌名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="productBrandList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="55" align="center" />
        <el-table-column label="官方品牌Id" align="center" prop="productBrandId" />
        <el-table-column label="官方品牌名称" align="center" prop="brandName" />
        <el-table-column label="第三方品牌Id" align="center" prop="id" />
        <el-table-column label="第三方品牌名称" align="center" prop="thirdPartyBrandName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
          <template #default="scope">
            <el-tooltip content="绑定官方品牌" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 绑定官方品牌对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="productBrandFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="第三方品牌名称">
          <el-input v-model="form.thirdPartyBrandName" disabled />
        </el-form-item>
        <el-form-item label="绑定官方品牌" prop="productBrandId">
          <el-select
            v-model="form.productBrandId"
            placeholder="请选择官方品牌"
            filterable
            remote
            :remote-method="remoteSearchBrand"
            :loading="brandLoading"
            :reserve-keyword="false"
            clearable
            style="width: 100%"
            @clear="handleBrandClear"
            @change="handleBrandChange"
          >
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.brandName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="官方品牌名称">
          <el-input v-model="form.brandName" disabled placeholder="选择官方品牌后自动填充" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductBrand" lang="ts">
import { listProductBrand, getProductBrand, updateProductBrand } from '@/api/external/productBrand';
import { ProductBrandVO, ProductBrandQuery, ProductBrandForm } from '@/api/external/productBrand/types';
import { listBrand } from '@/api/product/brand';
import { BrandVO } from '@/api/product/brand/types';
import cache from '@/plugins/cache';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const productBrandList = ref<ProductBrandVO[]>([]);
const brandList = ref<BrandVO[]>([]);
const defaultBrandList = ref<BrandVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const total = ref(0);

const brandLoading = ref(false);
let brandSearchTimer: ReturnType<typeof setTimeout> | undefined;

const queryFormRef = ref<ElFormInstance>();
const productBrandFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ProductBrandForm = {
  id: undefined,
  productBrandId: undefined,
  brandName: undefined,
  thirdPartyBrandName: undefined,
}
const data = reactive<PageData<ProductBrandForm, ProductBrandQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    brandName: undefined,
    thirdPartyBrandName: undefined,
    itemId: undefined,
    params: {
    }
  },
  rules: {
    productBrandId: [
      { required: true, message: "请选择官方品牌", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询第三方产品品牌信息列表 */
const getList = async () => {
  loading.value = true;
  const params = {
    ...queryParams.value
  };
  const res = await listProductBrand(params);
  productBrandList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 获取官方品牌列表 */
const getBrandList = async (brandName?: string) => {
  const res = await listBrand({ pageNum: 1, pageSize: 500, brandName } as any);
  const list = (res as any).rows || res.data || [];
  brandList.value = list;
  if (!brandName) {
    defaultBrandList.value = list;
  }
}

const handleBrandClear = () => {
  if (brandSearchTimer) {
    clearTimeout(brandSearchTimer);
    brandSearchTimer = undefined;
  }
  brandList.value = defaultBrandList.value || [];
}

const remoteSearchBrand = (query: string) => {
  const q = (query || '').trim();
  if (!q) {
    brandList.value = defaultBrandList.value || [];
    return;
  }

  if (brandSearchTimer) clearTimeout(brandSearchTimer);
  brandSearchTimer = setTimeout(async () => {
    brandLoading.value = true;
    await getBrandList(q).finally(() => (brandLoading.value = false));
  }, 300);
}

/** 初始化项目Key（从缓存获取） */
const initProjectKey = () => {
  const currentProject = cache.local.getJSON('currentProject');
  if (currentProject && currentProject.id) {
    queryParams.value.itemId = currentProject.id;
  }
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  productBrandFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProductBrandVO[]) => {
  ids.value = selection.map(item => item.id);
}

/** 绑定官方品牌操作 */
const handleUpdate = async (row?: ProductBrandVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getProductBrand(_id, queryParams.value.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "绑定官方品牌";
}

/** 官方品牌选择变化 */
const handleBrandChange = (brandId: string | number) => {
  const selectedBrand = brandList.value.find(item => item.id === brandId);
  if (selectedBrand) {
    form.value.brandName = selectedBrand.brandName;
  } else {
    form.value.brandName = undefined;
  }
}

/** 提交按钮 */
const submitForm = () => {
  productBrandFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await updateProductBrand(form.value).finally(() => buttonLoading.value = false);
      proxy?.$modal.msgSuccess("绑定成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('external/productBrand/export', {
    ...queryParams.value
  }, `productBrand_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  // 从缓存获取项目Key并初始化
  initProjectKey();
  if (queryParams.value.itemId) {
    getList();
  }
  brandLoading.value = true;
  getBrandList().finally(() => (brandLoading.value = false));
});
</script>
