<template>
  <div class="app-container">
    <el-form
        :model="queryParams"
        ref="queryFormRef"
        v-show="showSearch"
        :inline="true"
        @submit.native.prevent
    >
      <el-form-item label="所在位置" prop="local">
        <!-- <el-cascader
          size="default"
          style="width: 240px"
          v-model="queryParams.local"
          clearable
          separator="-"
          placeholder="请选择，支持搜索"
          :options="bannerLocalList"
          filterable
          :props="{ emitPath: false, value: 'title', label: 'title' }"
        ></el-cascader> -->

        <el-input
            v-model="queryParams.locals"
            placeholder="请输入所在位置"
            clearable
            size="default"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属站点" prop="tenantId">
        <el-select
            v-model="queryParams.tenantId"
            placeholder="请选择，支持搜索"
            size="default"
            filterable
        >
          <el-option
              v-for="item in siteList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            icon="search"
            size="default"
            @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="refresh" size="default" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="plus"
            size="default"
            @click="handleAdd"
        >新增
        </el-button
        >
      </el-col>
      <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据编号" prop="id" align="center"/>
      <el-table-column label="banner图名称" prop="title" align="center"/>
      <el-table-column label="所在位置" prop="locals" align="center"/>
      <el-table-column label="是否显示多图" align="center">
        <template #default="{ row }">
          {{ row.multipleFlag === "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="images" align="center">
        <template #default="{ row }">
          <ImagePreview :width="50" :height="50"
                        :src="row.images"/>
        </template>
      </el-table-column>
      <el-table-column label="建议上传图片尺寸" prop="sizes" align="center"/>
      <el-table-column label="所属站点" prop="area" align="center">
        <template #default="{ row }">
          {{ siteList.find((el) => el.id === row.tenantId)?.name || "无" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="created_at" align="center">
        <template #default="{ row }">
          <span>{{ row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
      >
        <template #default="{ row }">
          <el-button
              size="small"
              type="text"
              icon="edit"
              @click="handleUpdate(row)"
          >编辑
          </el-button
          >
          <el-button
              size="small"
              type="text"
              icon="delete"
              @click="handleDelete(row)"
          >删除
          </el-button
          >
        </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-dialog :title="title" v-model="showEditDialog" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属站点:" prop="tenantId">
          <el-select
              v-model="form.tenantId"
              placeholder="请选择，支持搜索"
              size="default"
              filterable
          >
            <el-option
                v-for="item in siteList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在位置:" prop="locals">
          <div style="display: flex">
            <el-autocomplete
                style="flex: 1"
                v-model="form.locals"
                :fetch-suggestions="querySearch"
                placeholder="请输入"
                value-key="title"
                @select="handleSelect"
            ></el-autocomplete>
            <el-button
                type="primary"
                style="margin-left: 15px"
                @click="addDomain"
                v-if="form.domains ? (form.domains.length ? false : true) : false"
            >添加子节点
            </el-button
            >
          </div>
        </el-form-item>
        <el-form-item
            v-for="(domain, index) in form.domains"
            :label="'上级子节点'"
            :key="domain.key"
            :prop="'domains.' + index + '.title'"
            :rules="{
            required: true,
            message: '子节点不能为空',
            trigger: 'blur',
          }"
        >
          <div style="display: flex">
            <el-input v-model="domain.title"></el-input>
            <el-button
                style="margin-left: 30px"
                @click.prevent="removeDomain(domain)"
            >删除
            </el-button
            >
            <el-button
                v-if="index + 1 == form.domains.length"
                type="primary"
                @click="addDomain"
            >添加
            </el-button
            >
          </div>
        </el-form-item>
        <el-form-item label="图片名称:" prop="title">
          <el-input v-model="form.title" placeholder="请输入banner图名称"/>
        </el-form-item>
        <el-form-item label="建议尺寸:" prop="sizes">
          <el-input v-model="form.sizes" placeholder="请输入图片建议尺寸"/>
        </el-form-item>
        <el-form-item label="图片:" prop="images">
          <ImageUpload v-model="form.images" :isShowTip="false" :limit="2"/>
        </el-form-item>
        <el-form-item label="显示多张:" prop="multipleFlag">
          <el-radio v-model="form.multipleFlag" label="1">是</el-radio>
          <el-radio v-model="form.multipleFlag" label="0">否</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Banner">
import {
  bannerLocal,
  bannerList,
  bannerAdd,
  bannerEdit,
  bannerDelete,
} from "@/api/website/siteSet";
import {tenantSelect} from "@/api/subPlatform/tenant";
import {reactive, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {resolveStaticUrl} from "@/utils/uri";

const loading = ref(true); // 是否正在加载
const showSearch = ref(true); // 是否显示搜索栏
const queryFormRef = ref(null);
const formRef = ref(null);
const siteList = ref([]);
const total = ref(0);
const dataList = ref([]);
const bannerLocalList = ref([]);
const restaurants = ref([]);

// 弹出层标题
const title = ref("");
// 是否显示弹出层
const showEditDialog = ref(false);

const data = reactive({
  queryParams: {
    locals: undefined,
    tenantId: undefined,
    pageNum: 1,
    pageSize: 10,
  }, // 表单参数
  form: {},
  rules: {
    tenantId: [
      {
        required: true,
        message: "所属站点不能为空",
        trigger: ["blur", "change"],
      },
    ],
    local: [{required: true, message: "所在位置不能为空", trigger: "change"}],
    title: [{required: true, message: "数据名称不能为空", trigger: "blur"}],
    // sizes: [{required: true, message: "建议尺寸不能为空", trigger: "blur"}],
    images: [
      {
        required: true,
        message: "图片不能为空",
        trigger: ["blur", "change"],
      },
    ],
  },
});
const {queryParams, form, rules} = toRefs(data);

const filterLocal = (data, parentTitle, out) => {
  data.forEach((item) => {
    let title = item.title;
    if (parentTitle != "") title = parentTitle + ">" + item.title;

    out.push({title: title});

    if (item.children && item.children.length > 0) {
      this.filterLocal(item.children, title, out);
    }
  });
};
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields();
  }
  handleQuery();
};
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};
const getList = async () => {
  loading.value = true;
  const resp = await bannerList(queryParams.value);
  dataList.value = resp.rows;
  total.value = resp.total;
  loading.value = false;
};

// 获取站点列表
const getSiteList = async () => {
  const resp = await tenantSelect();
  siteList.value = resp.rows;
};
const getBannerLocal = () => {
  bannerLocal({}).then((res) => {
    bannerLocalList.value = res.data;
    filterLocal(res.data, "", restaurants.value);
  });
};
// 取消按钮
const cancel = () => {
  showEditDialog.value = false;
  // this.memberOpen = false;
  reset();
};
// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    tenantId: undefined,
    title: undefined,
    locals: undefined,
    size: undefined,
    domains: [],
    images: undefined,
    multipleFlag: 0,
  };
  // this.resetForm("form");
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
const handleAdd = () => {
  reset();
  showEditDialog.value = true;
  title.value = "新增";
};
const querySearch = (queryString, cb) => {
  let _restaurants = restaurants.value;
  let results = queryString
      ? _restaurants.filter(createFilter(queryString))
      : _restaurants;
  // 调用 callback 返回建议列表的数据
  cb(results);
};
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
        restaurant.title.toLowerCase().indexOf(queryString.toLowerCase()) != -1
    );
  };
};
const handleSelect = (item) => {
  console.log(item);
};
const removeDomain = (item) => {
  let index = form.value.domains.indexOf(item);
  if (index !== -1) {
    form.value.domains.splice(index, 1);
  }
};
const addDomain = () => {
  form.value.domains.push({
    title: "",
  });
};
const handleUpdate = (row) => {
  reset();
  form.value = Object.assign({}, form.value, row);
  let arr = form.value.locals.split(">");
  // form.value.local = arr[0];
  form.value.locals = arr[0];
  for (let i = 1; i < arr.length; i++) {
    form.value.domains.push({title: arr[i]});
  }
  showEditDialog.value = true;
  title.value = "修改";
};
const submitForm = async () => {
  let formData = Object.assign({}, form.value);
  for (let i = 0; i < formData.domains.length; i++) {
    const item = formData.domains[i];
    formData.locals += ">" + item.title;
  }
  await formRef.value.validate();
  if (formData.id != undefined) {
    await bannerEdit(formData);
    ElMessage.success("修改成功");
    showEditDialog.value = false;
    getList();
    // this.getBannerLocal();
  } else {
    await bannerAdd(formData);
    ElMessage.success("新增成功");
    showEditDialog.value = false;
    getList();
    // this.getBannerLocal();
  }
};
/** 删除按钮操作 */
const handleDelete = (row) => {
  ElMessageBox.confirm(`是否确认删除编号为${row.id}的数据项？`)
      .then(async () => {
        await bannerDelete(row.id);
        getList();
        ElMessage.success("删除成功");
      })
      .catch(() => {
      });
};
getList();
getSiteList();
// getBannerLocal();
</script>
