<template>
  <div class="badge-index">
    <div v-if="buttonPermissions.includes('content:manager:badge:query')">
      <div class="filter-container">
        <el-select
          v-model="listQuery.type"
          placeholder="类型"
          clearable
          style="width:200px;"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option-group
            v-for="(group, groupIndex) in badgeGroups"
            :key="groupIndex"
            :label="group.label"
          >
            <el-option
              v-for="item in group.options"
              :key="item.value"
              :label="group.label + ' - ' + item.label"
              :value="item.value"
            />
          </el-option-group>
        </el-select>
        <el-input
          v-model.trim="listQuery.id"
          placeholder="ID"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-input
          v-model="listQuery.badgeName"
          placeholder="徽章名称"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-input
          v-model="listQuery.badgeKey"
          placeholder="徽章Key"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          v-if="buttonPermissions.includes('content:manager:badge:add')"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          新增
        </el-button>
      </div>

      <el-row v-loading="listLoading" :gutter="10">
        <el-col
          v-for="(item, index) in list"
          :key="index"
          :xs="24"
          :md="12"
          :lg="8"
        >
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.badgeName }}</span>

              <div
                v-if="isShowOperationBut"
                style="float: right; padding: 3px 0"
              >
                <el-dropdown>
                  <span class="el-dropdown-link">
                    操作选项<i class="el-icon-arrow-down el-icon--right" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-if="
                        buttonPermissions.includes(
                          'content:manager:badge:edit:rule'
                        )
                      "
                      @click.native="handleUpdate(item)"
                      >编辑规则</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        buttonPermissions.includes(
                          'content:manager:badge:edit:source'
                        )
                      "
                      @click.native="clickEditSource(item)"
                      >编辑资源</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        buttonPermissions.includes('content:manager:badge:del')
                      "
                      @click.native="handlDel(item.id)"
                      >删除</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div class="card-content">
              <div class="title">规则信息</div>
              <div class="contetn">
                <el-row>
                  <el-col :span="12"> ID：{{ item.id }} </el-col>
                  <el-col :span="12"> 徽章类型：{{ item.typeName }} </el-col>
                  <el-col :span="12"> 徽章key：{{ item.badgeKey }} </el-col>
                  <el-col :span="12"> 等级：{{ item.badgeLevel }} </el-col>
                  <el-col :span="12"> 里程碑：{{ item.milestone }} </el-col>
                  <el-col :span="12">
                    创建时间：{{ item.createTime | dateFormat }}
                  </el-col>
                </el-row>
              </div>
              <div class="title">资源信息</div>
              <div class="content flex-l">
                <div
                  v-for="(sItem, sIndex) in item.badgePictures"
                  :key="sIndex"
                  class="origin-source"
                >
                  <div class="sys-origin">
                    <sys-origin-icon :icon="sItem.sysOrigin" size="20" />
                  </div>
                  <div class="badge">
                    <el-image
                      style="width: 20px; height: 20px"
                      :src="sItem.selectUrl"
                      :preview-src-list="[sItem.selectUrl]"
                    >
                      <div slot="error" class="image-slot">
                        <i class="el-icon-picture-outline" />
                      </div>
                    </el-image>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.cursor"
        :limit.sync="listQuery.limit"
        @pagination="renderData"
      />
      <el-dialog
        :title="textOptTitle"
        :visible.sync="formVisible"
        :before-close="handleClose"
        width="450px"
      >
        <div v-loading="submitLoading">
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="110px"
            style="margin-right: 50px;"
          >
            <el-form-item label="类型" prop="type">
              <el-select
                v-model="form.type"
                placeholder="类型"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option-group
                  v-for="(group, groupIndex) in badgeGroups"
                  :key="groupIndex"
                  :label="group.label"
                >
                  <el-option
                    v-for="item in group.options"
                    :key="item.value"
                    :label="group.label + '-' + item.label"
                    :value="item.value"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="徽章名称" prop="badgeName">
              <el-input v-model.trim="form.badgeName" type="text" />
            </el-form-item>
            <el-form-item label="徽章key" prop="badgeKey">
              <el-input v-model.trim="form.badgeKey" type="text" />
            </el-form-item>
            <el-form-item label="等级" prop="badgeLevel">
              <el-input v-model.trim="form.badgeLevel" type="number" />
            </el-form-item>
            <el-form-item label="里程碑进度" prop="milestone">
              <el-input v-model.trim="form.milestone" type="number" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm()">保存</el-button>
              <el-button @click="handleClose()">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>

      <source-edit
        v-if="sourceEditVisible"
        :row="sourceEditRow"
        @close="editSourceClose"
      />
    </div>
    <div v-else style="text-align: center;">
      抱歉您无权查看，请联系管理员开通查看权限【运营管理-数据配置-徽章配置管理:manager:badge:query】
    </div>
  </div>
</template>

<script>
import { badgeTable, updateBadge, deleteBadge, addBadge } from "@/api/badge";
import Pagination from "@/components/Pagination";
import SourceEdit from "./source-edit";
import { mapGetters } from "vuex";
function getFormData() {
  return {
    id: "",
    badgeName: "",
    type: "",
    badgeKey: "",
    badgeLevel: "",
    milestone: ""
  };
}
export default {
  name: "BadgeRule",
  components: { Pagination, SourceEdit },
  data() {
    return {
      sourceEditVisible: false,
      sourceEditRow: null,
      badgeGroups: [
        {
          label: "用户",
          options: [
            { label: "成就", value: "ACHIEVEMENT" },
            { label: "管理员", value: "ADMINISTRATOR" },
            { label: "活动", value: "ACTIVITY" }
          ]
        },
        {
          label: "荣誉",
          options: [
            { label: "管理员", value: "HONOR_ADMIN" },
            { label: "活动", value: "HONOR_ACTIVITY" }
          ]
        }
        // {
        //   label: '房间',
        //   options: [{ label: '成就', value: 'ROOM_ACHIEVEMENT' }]
        // },
        // { label: '家族', options: [{ label: '等级', value: 'FAMILY' }] }
      ],
      pushTextHistoryLoading: false,
      pushTextHistoryVisible: false,
      fileList: [],
      pushTextHistory: [],
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        badgeName: "",
        badgeKey: "",
        type: "ACHIEVEMENT"
      },
      formVisible: false,
      textOptTitle: "",
      form: getFormData(),
      submitLoading: false,
      rules: {
        type: [{ required: true, message: "请选择类型", trigger: "blur" }],
        badgeName: [
          { required: true, message: "请填写徽章名称", trigger: "blur" }
        ],
        badgeKey: [
          { required: true, message: "请填写徽章key", trigger: "blur" }
        ],
        badgeLevel: [
          { required: true, message: "请填写等级", trigger: "blur" }
        ],
        milestone: [
          { required: true, message: "请填写可领取里程碑", trigger: "blur" }
        ]
      },
      listLoading: true
    };
  },
  computed: {
    ...mapGetters(["buttonPermissions"]),
    isShowOperationBut() {
      return (
        this.buttonPermissions.includes("content:manager:badge:edit:rule") ||
        this.buttonPermissions.includes("content:manager:badge:edit:source") ||
        this.buttonPermissions.includes("content:manager:badge:del")
      );
    }
  },
  created() {
    this.renderData();
  },
  methods: {
    renderData(isClean) {
      const that = this;
      if (isClean === true) {
        that.listQuery.cursor = 1;
      }
      that.listLoading = true;
      badgeTable(that.listQuery).then(res => {
        const { body } = res;
        that.total = body.total || 0;
        that.list = body.records;
        that.listLoading = false;
      });
    },
    handleSearch() {
      this.renderData();
    },
    renderDataSuccess() {
      this.$message({
        message: "Successful",
        type: "success"
      });
      this.renderData();
    },
    queryUserDetails(row) {
      this.userDeatilsDrawer = true;
      this.thatSelectedUserId = row.id;
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true;
          if (that.form.id) {
            updateBadge(that.form)
              .then(res => {
                that.submitLoading = false;
                that.formVisible = false;
                that.form = getFormData();
                that.fileList = [];
                that.renderData();
              })
              .catch(er => {
                that.submitLoading = false;
                that.$emit("fial", er);
              });
            return;
          }
          addBadge(that.form)
            .then(res => {
              that.submitLoading = false;
              that.formVisible = false;
              that.form = getFormData();
              that.fileList = [];
              that.renderData();
            })
            .catch(er => {
              that.submitLoading = false;
              console.error(er);
              that.$emit("fial", er);
            });
        } else {
          console.error("error submit!!");
          return false;
        }
      });
    },
    // 删除
    handlDel(id) {
      this.$confirm("确认删除吗？", "提示", {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteBadge(id).then(res => {
            this.listLoading = false;
            this.$message({
              message: "删除成功",
              type: "success"
            });
            this.renderData();
          });
        })
        .catch(() => {});
    },
    handleClose() {
      // 去除校验
      this.$refs.form.clearValidate();
      this.fileList = [];
      this.formVisible = false;
    },
    handleCreate() {
      this.formVisible = true;
      this.textOptTitle = "添加";
      this.form = getFormData();
    },
    handleUpdate(row) {
      this.textOptTitle = "修改";
      this.formVisible = true;
      this.form = Object.assign(this.form, row);
    },
    clickEditSource(row) {
      this.sourceEditVisible = true;
      this.sourceEditRow = row;
    },
    editSourceClose() {
      this.sourceEditVisible = false;
      this.sourceEditRow = null;
      this.renderData();
    }
  }
};
</script>
<style scoped lang="scss">
.box-card {
  margin-bottom: 10px;
  height: 340px;
  overflow: hidden;
  .card-content {
    line-height: 30px;
    .title {
      font-weight: bold;
    }
    .content {
      overflow: auto;
      white-space: nowrap;
      .origin-source {
        padding: 5px;
      }
    }
  }
}
</style>
