<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="$t('pages.badgeManagement.common.type')"
          clearable
          style="width:200px;"
          class="filter-item"
          @change="handleSearch"
        >
          <el-option-group
            v-for="(group, groupIndex) in badgeGroups"
            :key="groupIndex"
            :label="$t(group.labelKey)"
          >
            <el-option
              v-for="item in group.options"
              :key="item.value"
              :label="$t(group.labelKey) + ' - ' + $t(item.labelKey)"
              :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="$t('pages.badgeManagement.filter.badgeName')"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-input
          v-model="listQuery.badgeKey"
          :placeholder="$t('pages.badgeManagement.filter.badgeKey')"
          clearable
          style="width: 200px;"
          class="filter-item"
        />
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          @click="handleSearch"
        >
          {{ $t('common.search') }}
        </el-button>
        <el-button
          v-if="buttonPermissions.includes('content:manager:badge:add')"
          class="filter-item"
          type="primary"
          icon="el-icon-edit"
          @click="handleCreate"
        >
          {{ $t('common.add') }}
        </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">
                    {{ $t('pages.badgeManagement.action.operationOptions') }}<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)"
                      >{{ $t('pages.badgeManagement.action.editRule') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        buttonPermissions.includes(
                          'content:manager:badge:edit:source'
                        )
                      "
                      @click.native="clickEditSource(item)"
                      >{{ $t('pages.badgeManagement.action.editResource') }}</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        buttonPermissions.includes('content:manager:badge:del')
                      "
                      @click.native="handlDel(item.id)"
                      >{{ $t('pages.badgeManagement.common.delete') }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div class="card-content">
              <div class="title">{{ $t('pages.badgeManagement.common.ruleInfo') }}</div>
              <div class="contetn">
                <el-row>
                  <el-col :span="12"> ID：{{ item.id }} </el-col>
                  <el-col :span="12"> {{ $t('pages.badgeManagement.common.badgeType') }}：{{ item.typeName }} </el-col>
                  <el-col :span="12"> {{ $t('pages.badgeManagement.common.badgeKey') }}：{{ item.badgeKey }} </el-col>
                  <el-col :span="12"> {{ $t('pages.badgeManagement.common.level') }}：{{ item.badgeLevel }} </el-col>
                  <el-col :span="12"> {{ $t('pages.badgeManagement.common.milestone') }}：{{ item.milestone }} </el-col>
                  <el-col :span="12">
                    {{ $t('pages.badgeManagement.common.createdAt') }}：{{ item.createTime | dateFormat }}
                  </el-col>
                </el-row>
              </div>
              <div class="title">{{ $t('pages.badgeManagement.common.resourceInfo') }}</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"
        :modal-append-to-body="true"
        :append-to-body="true"
        :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="$t('pages.badgeManagement.common.type')" prop="type">
              <el-select
                v-model="form.type"
                :placeholder="$t('pages.badgeManagement.common.type')"
                clearable
                style="width:100%;"
                class="filter-item"
              >
                <el-option-group
                  v-for="(group, groupIndex) in badgeGroups"
                  :key="groupIndex"
                  :label="$t(group.labelKey)"
                >
                  <el-option
                    v-for="item in group.options"
                    :key="item.value"
                    :label="$t(group.labelKey) + '-' + $t(item.labelKey)"
                    :value="item.value"
                  />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('pages.badgeManagement.common.badgeName')" prop="badgeName">
              <el-input v-model.trim="form.badgeName" type="text" />
            </el-form-item>
            <el-form-item :label="$t('pages.badgeManagement.common.badgeKey')" prop="badgeKey">
              <el-input v-model.trim="form.badgeKey" type="text" />
            </el-form-item>
            <el-form-item :label="$t('pages.badgeManagement.common.level')" prop="badgeLevel">
              <el-input v-model.trim="form.badgeLevel" type="number" />
            </el-form-item>
            <el-form-item :label="$t('pages.badgeManagement.form.milestoneProgress')" prop="milestone">
              <el-input v-model.trim="form.milestone" type="number" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm()">{{ $t('common.save') }}</el-button>
              <el-button @click="handleClose()">{{ $t('common.cancel') }}</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;">
      {{ $t('pages.badgeManagement.message.noPermission') }}
    </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: [
        {
          labelKey: "pages.badgeManagement.group.user",
          options: [
            { labelKey: "pages.badgeManagement.group.achievement", value: "ACHIEVEMENT" },
            { labelKey: "pages.badgeManagement.group.administrator", value: "ADMINISTRATOR" },
            { labelKey: "pages.badgeManagement.group.activity", value: "ACTIVITY" }
          ]
        },
        {
          labelKey: "pages.badgeManagement.group.honor",
          options: [
            { labelKey: "pages.badgeManagement.group.administrator", value: "HONOR_ADMIN" },
            { labelKey: "pages.badgeManagement.group.activity", 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: this.$t('pages.badgeManagement.validation.selectType'), trigger: "blur" }],
        badgeName: [
          { required: true, message: this.$t('pages.badgeManagement.validation.badgeName'), trigger: "blur" }
        ],
        badgeKey: [
          { required: true, message: this.$t('pages.badgeManagement.validation.badgeKey'), trigger: "blur" }
        ],
        badgeLevel: [
          { required: true, message: this.$t('pages.badgeManagement.validation.level'), trigger: "blur" }
        ],
        milestone: [
          { required: true, message: this.$t('pages.badgeManagement.validation.milestone'), 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(this.$t('pages.badgeManagement.confirm.delete'), this.$t('common.tip'), {
        type: "warning"
      })
        .then(() => {
          this.listLoading = true;
          deleteBadge(id).then(res => {
            this.listLoading = false;
            this.$message({
              message: this.$t('pages.badgeManagement.message.deleteSuccess'),
              type: "success"
            });
            this.renderData();
          });
        })
        .catch(() => {});
    },
    handleClose() {
      this.$refs.form.clearValidate();
      this.fileList = [];
      this.formVisible = false;
    },
    handleCreate() {
      this.formVisible = true;
      this.textOptTitle = this.$t('pages.badgeManagement.dialog.add');
      this.form = getFormData();
    },
    handleUpdate(row) {
      this.textOptTitle = this.$t('pages.badgeManagement.dialog.edit');
      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>
