<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="所在位置" prop="tenant_id">
        <el-cascader
          size="small"
          style="width: 240px"
          v-model="queryParams.tenant_id"
          clearable
          separator="-"
          placeholder="请选择，支持搜索"
          :options="bannerLocalList"
          filterable
          :props="{ emitPath: false, value: 'title', label: 'title' }"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="所属站点" prop="tenant_id" v-if="is_super">
        <SiteOptions v-model="queryParams" />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @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="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="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="local" align="center" />
      <el-table-column label="是否显示多图" prop="is_multiple" align="center">
        <template slot-scope="scope">
          {{ scope.row.is_multiple ? "是" : "否" }}
        </template>
      </el-table-column>
      <el-table-column label="图片" prop="images" align="center">
        <template slot-scope="scope">
          <ImagePreview :width="50" :height="50" :src="scope.row.images" />
        </template>
      </el-table-column>
      <el-table-column label="建议上传图片尺寸" prop="size" align="center" />
      <el-table-column label="所属站点" prop="area" align="center" />
      <el-table-column label="创建时间" prop="created_at" align="center">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created_at) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page_num"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属站点:" prop="tenant_id" v-if="is_super">
          <SiteOptions v-model="form" />
        </el-form-item>
        <el-form-item label="所在位置:" prop="local">
          <div style="display: flex">
            <el-autocomplete
              style="flex: 1"
              v-model="form.local"
              :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="size">
          <el-input v-model="form.size" 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="is_multiple">
          <el-radio v-model="form.is_multiple" :label="1">是</el-radio>
          <el-radio v-model="form.is_multiple" :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>
import {
  bannerLocal,
  bannerList,
  bannerAdd,
  bannerEdit,
  bannerDelete,
} from "@/api/website/siteSet";
export default {
  data() {
    return {
      is_super: this.$store.getters.is_super,
      loading: true,
      showSearch: true,
      bannerLocalList: [],
      queryParams: {
        title: undefined,
        mode: undefined,
        tenant_id: undefined,
        page_num: 1,
        page_size: 10,
      },
      total: 0,
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      restaurants: [],
      // 表单参数
      form: {},
      rules: {
        tenant_id: [
          {
            required: true,
            message: "归属导航不能为空",
            trigger: ["blur", "change"],
          },
        ],
        local: [
          { required: true, message: "所在位置不能为空", trigger: "change" },
        ],
        title: [
          { required: true, message: "数据名称不能为空", trigger: "blur" },
        ],
        size: [
          { required: true, message: "建议尺寸不能为空", trigger: "blur" },
        ],
        images: [
          {
            required: true,
            message: "图片不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  methods: {
    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);
        }
      });
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleQuery() {
      this.queryParams.page_num = 1;
      this.getList();
    },
    getList() {
      this.loading = true;
      bannerList(this.queryParams).then((res) => {
        this.dataList = res.data.data;
        this.total = res.data.count;
        this.loading = false;
      });
    },
    getBannerLocal() {
      bannerLocal({}).then((res) => {
        this.bannerLocalList = res.data;
        this.filterLocal(res.data, "", this.restaurants);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.memberOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        tenant_id: undefined,
        title: undefined,
        local: undefined,
        size: undefined,
        domains: [],
        images: undefined,
        is_multiple: 0,
      };
      this.resetForm("form");
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增";
    },
    querySearch(queryString, cb) {
      let restaurants = this.restaurants;
      let results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.title.toLowerCase().indexOf(queryString.toLowerCase()) !=
          -1
        );
      };
    },
    handleSelect(item) {
      console.log(item);
    },
    removeDomain(item) {
      let index = this.form.domains.indexOf(item);
      if (index !== -1) {
        this.form.domains.splice(index, 1);
      }
    },
    addDomain() {
      this.form.domains.push({
        title: "",
      });
    },
    handleUpdate(row) {
      this.reset();
      this.form = Object.assign({}, this.form, row);
      let arr = this.form.local.split(">");
      this.form.local = arr[0];
      for (let i = 1; i < arr.length; i++) {
        this.form.domains.push({ title: arr[i] });
      }
      this.open = true;
      this.title = "修改";
    },
    submitForm() {
      let formData = Object.assign({}, this.form);
      for (let i = 0; i < formData.domains.length; i++) {
        const item = formData.domains[i];
        formData.local += ">" + item.title;
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (formData.id != undefined) {
            bannerEdit(formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getBannerLocal();
            });
          } else {
            bannerAdd(formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getBannerLocal();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除编号为"' + row.id + '"的数据项？')
        .then(function () {
          return bannerDelete({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
  created() {
    this.getList();
    this.getBannerLocal();
  },
};
</script>