<template>
  <div>
    <card-container>
      <vxe-toolbar>
        <template #buttons>
          <el-button icon="el-icon-plus" type="primary" size="small" @click="isShowAdd = true">新增</el-button>
          <el-button icon="el-icon-search" type="primary" plain size="small" @click="getList">搜索</el-button>
        </template>
      </vxe-toolbar>
      <vxe-table
        stripe
        style="margin-top: 10px;"
        ref="table"
        :loading="loading"
        keep-source
        show-overflow
        :column-config="{ resizable: true }"
        :edit-rules="validRules"
        :edit-config="{ trigger: 'manual', mode: 'row', showStatus: true, isHover: true }"
        :align="allAlign"
        :data="tableData">
        <vxe-column type="seq" width="58" align="center"></vxe-column>
        <vxe-column field="name" width="140" title="姓名" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
        <vxe-column field="username" width="160" title="用户名" :edit-render="{ name: 'input', attrs: { type: 'text'} }"></vxe-column>
        <vxe-column field="password" width="160" title="密码" :edit-render="{ name: 'input', attrs: { type: 'password'} }">
          <template #default="{ row }">
            <span>***</span>
          </template>
        </vxe-column>
        <vxe-column field="roles" title="角色" min-width="200" show-overflow="tooltip">
          <template #default="{ row }">
            <div>
              <el-tag v-for="item in row.roles" :key="item.id">{{ item.name }}</el-tag>
            </div>
          </template>
        </vxe-column>
        <vxe-column field="sortnumber" width="80" title="排序" align="center" :edit-render="{ name: 'input', attrs: { type: 'number' } }"></vxe-column>
        <vxe-column field="operate" title="操作" min-width="240">
          <template #default="{ row }">
            <template v-if="isActiveStatus(row)">
              <el-button size="small" type="primary" @click="saveRowEvent(row)">保存</el-button>
              <el-button size="small" type="primary" plain @click="cancelRowEvent(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="small" type="success" @click="bind(row)">绑定角色</el-button>
              <el-button size="small" type="warning" @click="editRowEvent(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="destroyRowEvent(row)">删除</el-button>
            </template>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        style="margin-top: 10px;"
        @size-change="e => {
          select.rows = e;
          select.page = 1;
          getList();
        }"
        @current-change="e => {
          select.page = e;
          getList();
        }"
        :current-page="select.page"
        :page-sizes="[20, 30, 40, 50]"
        :page-size="select.rows"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </card-container>

    <AddUser :is-show.sync="isShowAdd" @refresh="getList"></AddUser>
    <BindRoles ref="BindRoles" :is-show.sync="isShowBind" @refresh="getList"></BindRoles>
  </div>
</template>

<script>
import BindRoles from './components/BindRoles.vue'
import AddUser from "./components/AddUser.vue"
import { deepCopy } from "@/utils"
import { index, save, destroy } from "@/api/user"
export default {
  components: {
    AddUser,
    BindRoles
  },
  data() {
    return {
      isShowBind: false,
      isShowAdd: false,

      select: {
        page: 1,
        rows: 20,
        keyword: ""
      },
      loading: false,
      total: 0,
      allAlign: null,
      tableData: [],
      validRules: {

      },
      form: {
        id: "",
        name: "",
        username: "",
        password: "",
        sortnumber: 0
      }
    }
  },
  methods: {
    bind (row) {
      this.isShowBind = true
      this.$refs['BindRoles'].setForm(['id', 'role_id'],[row.id,row.roles?.map(i => i.id)||[]])
    },

    editRowEvent (row) {
      if (this.$refs['table']) {
        this.$refs['table'].setEditRow(row)
      }
    },
    cancelRowEvent (row) {
      if (this.$refs['table']) {
        this.$refs['table'].clearEdit().then(() => {
          // 还原行数据
          this.$refs['table'].revertData(row)
        })
      }
    },

    async getList () {
      this.loading = true;
      try {
        const res = await index(this.select)
        this.tableData = res.data;
        this.total = res.total;
        console.log(res)
        this.loading = false;
      } catch (err) {
        console.error(err)
        this.loading = false;
      }
    },

    async saveRowEvent (row) {
      try {
        await this.$confirm("确认保存？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        let form = deepCopy(this.form)
        for (let key in form) {
          form[key] = row[key]
        }
        this.loading = true;
        await save(form)
        await this.getList();
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
    async destroyRowEvent (row) {
      try {
        await this.$confirm("确认删除？","提示",{
          confirmButtonText: "确认",
          cancelButtonText: "取消"
        })
        this.loading = true;
        if (row.id) {
          await destroy({
            id: row.id
          })
          await this.getList();
        } else {
          this.tableData.splice(this.tableData.findIndex(i => i._X_ROW_KEY === row._X_ROW_KEY),1)
        }
        this.loading = false;
      } catch (err) {
        this.loading = false;
      }
    },
  },
  computed: {
    isActiveStatus () {
      return function (row) {
        if (this.$refs['table']) {
          return  this.$refs['table'].isEditByRow(row)
        }
      }
    }
  },
  created() {
    this.getList()
  }
}
</script>

<style scoped lang="scss">
.total {
  color: #666;
  text-align: right;
  line-height: 3;
}
::v-deep .el-tag + .el-tag {
  margin-left: 4px;
}
</style>
