<template>
  <div class="app-container-admin">
    <div class="filter-container">
      <div class="filter-item">
        <account-input v-model="listQuery.userId" :placeholder="$t('pages.appManager.administrator.filter.userId')" />
      </div>
      <el-input
        v-model.trim="listQuery.account"
        v-number
        :placeholder="$t('pages.appManager.administrator.filter.account')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-input
        v-model.trim="listQuery.userNickname"
        :placeholder="$t('pages.appManager.administrator.filter.nickname')"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button
        :loading="searchLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        :disabled="searchDisabled"
        @click="handleSearch"
      >
        {{ $t('common.search') }}
      </el-button>

      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        {{ $t('pages.appManager.administrator.action.addAdmin') }}
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      :element-loading-text="$t('pages.appManager.loading')"
      fit
      highlight-current-row
      @cell-mouse-enter="handleMouseEnter"
    >
      <el-table-column :label="$t('pages.appManager.administrator.table.avatar')" align="center">
        <template slot-scope="scope">
          <user-table-exhibit
            :user-profile="scope.row"
            :query-details="true"
            :custom-props="{ userId: 'userId' }"
          />
        </template>
      </el-table-column>
      <el-table-column width="70" :label="$t('pages.appManager.administrator.table.flag')" align="center">
        <template slot-scope="scope">
          <a
            :title="scope.row.countryName"
            @click="copyTextContent(scope.row.countryName)"
          >
            <flag-icon
              :code="scope.row.countryCode"
              style="margin-top: 20px;"
            />
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('pages.appManager.administrator.table.status')" align="center" width="200">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            :active-text="$t('pages.appManager.administrator.status.normal')"
            :inactive-text="$t('pages.appManager.administrator.status.disabled')"
            @change="handleSwitchChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="status" :label="$t('pages.appManager.administrator.table.role')" align="center" width="200">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.roles"
            v-loading="scope.row.id === changeRolesLoadingId"
            :disabled="scope.row.status !== 1"
            style="width: 120px;"
            @change="v => changeRoles(scope.row, v)"
          >
            <el-option
              v-for="(item, index) in roles"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('pages.appManager.administrator.table.createdAt')"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" :label="$t('pages.appManager.administrator.table.actions')" align="center" width="100">
        <template slot-scope="scope">
          <el-dropdown>
            <span class="el-dropdown-link">
              <i class="el-icon-more" />
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="AttributionSystem(scope.row)"
                >{{ $t('pages.appManager.administrator.action.assignPermissions') }}</el-dropdown-item
              >
              <!-- <el-dropdown-item @click.native="attributionRoom(scope.row)">管理房间</el-dropdown-item> -->
              <el-dropdown-item @click.native="handlDel(scope.row.id)"
                >{{ $t('pages.appManager.administrator.action.removeManagement') }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

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

    <auth-system
      v-if="authSystemVisable"
      :user-id="thatSelectedUserId"
      @close="authSystemVisable = false"
    />

    <room-drawer
      v-if="roomDrawerVisable"
      :row="thisRow"
      @close="roomDrawerVisable = false"
    />

    <el-dialog
      :title="textOptTitle"
      :visible.sync="formVisible"
      :before-close="handleClose"
      :close-on-click-modal="false"
      width="400px"
    >
      <div v-loading="submitLoading">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item :label="$t('pages.appManager.administrator.form.uid')" prop="userId">
            <el-input v-model.trim="form.userId" type="text" />
          </el-form-item>
          <el-form-item :label="$t('pages.appManager.administrator.form.role')" prop="roles">
            <el-select v-model="form.roles" style="width: 100%">
              <el-option
                v-for="(item, index) in roles"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm()">{{ $t('pages.appManager.administrator.action.save') }}</el-button>
            <el-button @click="handleClose()">{{ $t('common.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAdministratorTable,
  getUserBaseInfo,
  changeStatusAdministrator,
  changeSysAdministratorRoles
} from "@/api/app-user";
import Pagination from "@/components/Pagination";
import { copyText } from "@/utils";
import { deleteAdministrator, addAdministrator } from "@/api/stream";
import authSystem from "./auth";

function getFormData() {
  return {
    userId: "",
    wage: "0",
    roles: "ADMIN"
  };
}

export default {
  name: "AdministratorTable",
  components: {
    Pagination,
    authSystem
  },
  data() {
    return {
      searchDisabled: false,
      changeRolesLoadingId: "",
      thisRow: {},
      level: 0,
      authSystemVisable: false,
      formVisible: false,
      roomDrawerVisable: false,
      textOptTitle: "",
      thatSelectedUserId: "",
      form: getFormData(),
      submitLoading: false,
      list: [],
      total: 0,
      listQuery: {
        cursor: 1,
        limit: 20,
        userId: "",
        account: "",
        userNickname: ""
      },
      rangeDate: "",
      listLoading: true,
      searchLoading: false,
      clickUserId: ""
    };
  },
  computed: {
    roles() {
      return [
        { name: this.$t("pages.appManager.administrator.role.admin"), value: "ADMIN" },
        { name: this.$t("pages.appManager.administrator.role.superAdmin"), value: "SUPER_ADMIN" },
        { name: this.$t("pages.appManager.administrator.role.manager"), value: "MANAGER" }
      ];
    },
    rules() {
      return {
        userId: [
          {
            required: true,
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (value !== "") {
                getUserBaseInfo(value)
                  .then(res => {
                    if (JSON.stringify(res) === '{"status":200}') {
                      callback(new Error(this.$t("pages.appManager.administrator.validation.uidNotFound")));
                    } else {
                      callback();
                    }
                  })
                  .catch(er => {
                    callback(new Error(er.message));
                  });
              } else {
                callback(new Error(this.$t("pages.appManager.administrator.validation.enterUid")));
              }
            }
          }
        ],
        wage: [
          {
            required: true,
            trigger: "blur",
            pattern: /^([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9]|100)$/,
            message: this.$t("pages.appManager.administrator.validation.range0To100")
          }
        ],
        roles: [
          { required: true, trigger: "blur", message: this.$t("pages.appManager.administrator.validation.requiredRole") }
        ]
      };
    }
  },
  created() {
    this.renderData(true);
  },
  methods: {
    changeRoles(row, newValue) {
      const that = this;
      that.changeRolesLoadingId = row.id;
      changeSysAdministratorRoles({
        id: row.id,
        roles: newValue
      })
        .then(res => {
          that.changeRolesLoadingId = "";
        })
        .catch(er => {
          that.changeRolesLoadingId = "";
          console.error(er);
        });
    },
    renderData(isReset) {
      const that = this;
      if (isReset === true) {
        that.listQuery.cursor = 1;
      }
      that.listLoading = true;
      getAdministratorTable(that.listQuery)
        .then(res => {
          const { body } = res;
          that.total = body.total || 0;
          that.list = body.records;
          that.searchLoading = that.listLoading = false;
        })
        .catch(er => {
          that.searchLoading = that.listLoading = false;
        });
    },
    handleSearch() {
      this.searchLoading = true;
      this.renderData(true);
    },
    handleSwitchChange(row) {
      changeStatusAdministrator({
        id: row.id,
        status: row.status,
        userId: row.userId
      })
        .then(res => {})
        .catch(er => {
          if (row.status === 0) {
            row.status = 1;
          } else if (row.status === 1) {
            row.status = 0;
          }
        });
    },
    handleCreate() {
      this.textOptTitle = this.$t("pages.appManager.administrator.dialog.create");
      this.formVisible = true;
    },
    accountHandleSuccess(data) {
      this.$message({
        message: this.$t("pages.appManager.administrator.message.success"),
        type: "success"
      });
      // this.renderData()
    },
    handleLiveClick(row) {
      window.open(row.liveUrl);
    },
    copyTextContent(text) {
      const that = this;
      copyText(text)
        .then(() => {
          that.$message({
            message: this.$t("pages.appManager.administrator.message.copySuccess"),
            type: "success"
          });
        })
        .catch(() => {
          that.$message({
            message: this.$t("pages.appManager.administrator.message.copyFail"),
            type: "error"
          });
        });
    },
    handleClose() {
      // 去除校验
      this.$refs.form.clearValidate();
      this.formVisible = false;
      this.resetForm();
    },
    resetForm() {
      this.form = getFormData();
    },
    submitForm() {
      const that = this;
      that.$refs.form.validate(valid => {
        if (valid) {
          that.submitLoading = true;
          addAdministrator({
            userId: that.form.userId,
            wage: that.form.wage,
            roles: that.form.roles
          })
            .then(res => {
              that.$opsMessage.success();
              that.submitLoading = false;
              that.formVisible = false;
              that.resetForm();
              that.renderData(true);
            })
            .catch(er => {
              that.submitLoading = false;
              console.error(er);
              this.$emit("fail", er);
            });
        } else {
          console.error("error submit!!");
          return false;
        }
      });
    },
    handlDel(id) {
      const that = this;
      this.$confirm(this.$t("pages.appManager.administrator.confirm.deleteAdmin"), this.$t("pages.appManager.administrator.confirm.title"), {
        confirmButtonText: this.$t("pages.appManager.administrator.confirm.confirm"),
        cancelButtonText: this.$t("pages.appManager.administrator.confirm.cancel")
      })
        .then(() => {
          deleteAdministrator(id)
            .then(res => {
              that.renderData(true);
              that.$opsMessage.success();
            })
            .catch(er => {
              that.$opsMessage.success();
            });
        })
        .catch(() => {});
    },
    renderDataSuccess() {
      this.$message({
        message: this.$t("pages.appManager.administrator.message.success"),
        type: "success"
      });
      this.renderData();
    },
    handleMouseEnter(row) {
      this.thisRow = row;
      this.thatSelectedUserId = row.userId;
    },
    AttributionSystem(row) {
      const that = this;
      this.thatSelectedUserId = row.userId;
      that.authSystemVisable = true;
    },
    attributionRoom(row) {
      const that = this;
      that.roomDrawerVisable = true;
    },
    getLevelName(gender, level) {
      if (gender !== 0) {
        return "-";
      }
      if (level === -1) {
        return "L-1";
      }
      return `L${level}`;
    }
  }
};
</script>
<style scoped lang="scss">
.this-level {
  padding-bottom: 30px;
  display: flex;
  > div {
    width: 150px;
  }
}
</style>
