<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <!-- 系统 -->
      <el-select
        v-model="listQuery.sysOrigin"
        placeholder="系统"
        style="width:120px;"
        class="filter-item"
        @change="changeSysOrigin"
      >
        <el-option
          v-for="item in permissionsSysOriginPlatforms"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
          <span style="float: left;">
            <sys-origin-icon :icon="item.value" :desc="item.value"
          /></span>
          <span style="float: left;margin-left:10px">{{ item.label }}</span>
        </el-option>
      </el-select>

      <!-- 平台 -->
      <el-select
        v-model="listQuery.platform"
        style="width: 120px"
        class="filter-item"
        placeholder="平台"
      >
        <el-option
          v-for="(item, index) in appPlatforms"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>

      <!-- 状态 -->
      <el-select
        v-model="listQuery.showcase"
        placeholder="状态"
        style="width: 120px"
        class="filter-item"
        @change="handleSearch"
      >
        <el-option label="上架" :value="1" />
        <el-option label="下架" :value="2" />
        <el-option label="过期" :value="3" />
      </el-select>

      <!-- 区域 -->
      <el-select
        v-model="listQuery.region"
        v-loading="loading"
        placeholder="区域"
        style="width:120px;"
        class="filter-item"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="(item, index) in regions"
          :key="index"
          :label="item.regionName"
          :value="item.id"
        />
      </el-select>

      <!-- 国家 -->
      <el-select
        v-model="listQuery.countryCode"
        v-loading="loadingCountry"
        placeholder="国家"
        style="width: 200px"
        class="filter-item"
        clearable
        collapse-tags
        @change="changeCountry"
      >
        <el-option
          v-for="item in countryList"
          :key="item.id"
          :label="item.country.aliasName || item.country.enName"
          :value="item.country.alphaTwo"
        >
          <span style="float: left;">
            <img :src="item.country.nationalFlag" width="30"
          /></span>
          <span style="float: left;margin-left:10px">{{
            item.country.aliasName || item.country.enName
          }}</span>
        </el-option>
      </el-select>

      <!-- 搜索按钮 -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >
        搜索
      </el-button>

      <!-- 新增按钮 -->
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>

    <!-- 表单 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <!-- 封面 -->
      <el-table-column label="封面" align="center" width="400">
        <template slot-scope="scope">
          <el-image
            :lazy="true"
            style="width: 351px; height: 111px"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"
          />
        </template>
      </el-table-column>

      <!-- 小图 -->
      <el-table-column label="小图" align="center" width="150">
        <template slot-scope="scope">
          <el-image
            :lazy="true"
            style="width: 150px; height: 111px"
            :src="scope.row.smallCover"
            :preview-src-list="[scope.row.smallCover]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>

      <!-- alert图 -->
      <el-table-column label="alert图" align="center" width="150">
        <template slot-scope="scope">
          <el-image
            :lazy="true"
            style="width: 150px; height: 111px"
            :src="scope.row.alertCover"
            :preview-src-list="[scope.row.alertCover]"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>

      <!-- 类型 -->
      <el-table-column prop="type" label="类型" align="center" />

      <!-- 展示位 -->
      <el-table-column
        prop="displayPositionNames"
        label="展示位"
        align="center"
      />

      <!-- 系统 -->
      <el-table-column label="归属系统" align="center">
        <template slot-scope="scope">
          <sys-origin-icon
            :icon="scope.row.sysOrigin"
            :desc="scope.row.sysOrigin"
          />
        </template>
      </el-table-column>

      <!-- 区域 -->
      <el-table-column prop="regionNameStr" label="区域" align="center" />

      <!-- 排序 -->
      <el-table-column prop="sort" label="排序" align="center" />

      <!-- 内容 -->
      <el-table-column prop="content" label="内容" align="center">
        <template slot-scope="scope">
          <el-popover placement="top-start" trigger="hover">
            <div class="popover-content">
              <div><strong>内容：</strong>{{ scope.row.content }}</div>
              <div><strong>参数：</strong>{{ scope.row.params }}</div>
              <div><strong>描述：</strong>{{ scope.row.depict }}</div>
              <div><strong>开始时间：</strong>{{ scope.row.startTime }}</div>
              <div><strong>过期时间：</strong>{{ scope.row.expiredTime }}</div>
            </div>
            <el-button slot="reference" type="text">查看</el-button>
          </el-popover>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <div>
            <el-tag
              v-if="scope.row.expired === true && scope.row.showcase === false"
              type="warning"
              >下架+过期</el-tag
            >
            <el-tag
              v-else-if="
                scope.row.expired === true && scope.row.showcase === true
              "
              type="warning"
              >上架+过期</el-tag
            >
            <el-tag v-else-if="scope.row.expired === true" type="warning"
              >过期</el-tag
            >
            <el-tag v-else-if="scope.row.showcase === false" type="danger"
              >下架</el-tag
            >
            <el-tag v-else-if="scope.row.showcase === true">上架</el-tag>
          </div>
        </template>
      </el-table-column>

      <!-- 操作按钮列表 -->
      <el-table-column fixed="right" label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click.native="handleUpdate()">修改</el-button>
          <el-button type="text" @click.native="handlDel(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.cursor"
      :limit.sync="listQuery.limit"
      @pagination="renderData"
    />

    <!-- 编辑组件 -->
    <form-edit
      v-if="formEditVisible"
      :row="thatRow"
      :sys-origin="listQuery.sysOrigin"
      @close="formEditVisible = false"
      @success="formEditSuccess"
    />
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { appPlatforms, sysOriginPlatforms } from "@/constant/origin";

import { bannerTable, deleteBanner } from "@/api/banner";
import { regionConfigTable } from "@/api/sys";
import { listPayOpenCountry } from "@/api/sys-pay";

import Pagination from "@/components/Pagination";
import FormEdit from "./form-edit.vue";

export default {
  components: { Pagination, FormEdit },
  data() {
    return {
      thatRow: {},
      appPlatforms,
      sysOriginPlatforms,
      txtVal: 0,
      loading: false,
      regions: [],
      activeGiftId: "",
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      pushTextHistory: [],
      list: [],
      delarr: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        showcase: 1,
        sysOrigin: "HALAR",
        platform: "Android",
        region: "",
        countryCode: ""
      },
      formEditVisible: false,
      textOptTitle: "",
      listLoading: true,

      selectedCountry: {}, // 存储完整的国家对象
      countryList: [],
      loadingCountry: false
    };
  },
  computed: {
    ...mapGetters(["permissionsSysOriginPlatforms"])
  },
  created() {
    const that = this;
    const querySystem = this.permissionsSysOriginPlatforms[0];
    if (!querySystem) {
      return;
    }
    that.listQuery.sysOrigin = querySystem.value;
    this.listRegion();
    that.renderData();

    this.loadOpenCountry();
  },
  methods: {
    renderData(isClean) {
      const that = this;
      if (isClean === true) {
        this.listQuery.cursor = 1;
        this.listQuery.list = [];
      }
      that.listLoading = true;
      bannerTable(that.listQuery).then(res => {
        const { body } = res;
        that.total = body.total || 0;
        that.list = body.records;
        that.listLoading = false;
      });
    },
    listRegion() {
      const that = this;
      that.loading = true;
      regionConfigTable({ sysOrigin: that.listQuery.sysOrigin })
        .then(res => {
          that.regions = res.body || [];
          that.loading = false;
        })
        .catch(er => {
          that.loading = false;
        });
    },
    handleSearch() {
      this.renderData(true);
    },
    renderDataSuccess() {
      this.$message({
        message: "Successful",
        type: "success"
      });
      this.renderData();
    },
    changeSysOrigin() {
      this.listRegion();
      this.handleSearch();
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true;
      this.thatSelectedUserId = row.id;
    },

    // 选择国家
    changeCountry(val) {
      const that = this;
      console.log("val", val);

      if (!val) {
        // 如果没有选择国家，清空相关字段
        that.listQuery.countryCode = "";
        that.selectedCountry = {};
      } else {
        // 选择了一个国家
        that.selectedCountry =
          this.countryList.find(item => item.country.alphaTwo === val) || {};

        // 使用传统的方式访问嵌套属性
        that.listQuery.countryCode = that.selectedCountry.country
          ? that.selectedCountry.country.alphaTwo
          : "";
      }

      this.renderData();
    },

    // 获取国家列表
    loadOpenCountry() {
      const that = this;

      that.loadingCountry = true;
      listPayOpenCountry()
        .then(res => {
          that.loadingCountry = false;
          that.countryList = res.body || [];
          that.listQuery.countryCode = "";
          that.selectedCountry = {};
          // that.renderData();
        })
        .catch(er => {
          that.loadingCountry = false;
          console.error(er);
        });
    },

    // 删除
    handlDel(row) {
      this.$confirm("确认删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteBanner(row.id, row.sysOrigin).then(res => {
            this.listLoading = false;
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.renderData();
          });
        })
        .catch(() => {});
    },
    handleCreate() {
      this.thatRow = null;
      this.formEditVisible = true;
    },
    handleUpdate() {
      this.formEditVisible = true;
    },
    handleMouseEnter(row) {
      this.thatRow = row;
    },
    formEditSuccess() {
      this.formEditVisible = false;
      this.renderData();
    }
  }
};
</script>
<style scoped lang="scss">
.popover-content {
  max-width: 300px;
  line-height: 20px;
}
</style>
