<template>
  <div class="client-account-set ">
    <div class="part-box-top">
      <Button type="success" icon="md-add" @click="toAdd">新增</Button>
    </div>
    <div class="part-box">
      <table class="table">
        <tr>
          <th>序号</th>
          <th>角色</th>
          <th>账号</th>
          <th>操作</th>
        </tr>
        <tr v-for="(user, index) in users" :key="index">
          <td style="width: 60px;">{{ index + 1 }}</td>
          <td>{{ user.roleName }}</td>
          <td style="width: 200px;">
            <Input v-model="user.loginName" clearable></Input>
          </td>
          <td>
            <Button
              size="small"
              type="primary"
              :disabled="!user.id"
              @click="toSave(user)"
              >重置</Button
            >
            <Button size="small" type="primary" @click="toSave(user)"
              >保存</Button
            >
            <Button size="small" type="error" @click="toDelete(index)"
              >删除</Button
            >
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
import {
  inspectionUserPageList,
  deleteInspectionUser,
  uploadInspectionUser
} from "@/api";

const initModalForm = {
  id: "",
  roleName: "纪检",
  loginName: "",
  password: ""
};

export default {
  name: "client-account-set",
  data() {
    return {
      workId: this.$route.params.workId,
      users: [],
      curUser: {}
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      const datas = {
        workId: this.workId
      };
      const data = await inspectionUserPageList(datas);

      this.users = data.map(item => {
        return {
          id: item.id,
          loginName: item.loginName,
          password: item.password,
          roleName: "纪检"
        };
      });

      if (!this.users.length) this.toAdd();
    },
    toAdd() {
      this.users.push({ ...initModalForm });
    },
    async toSave(row) {
      if (!row.loginName.match(new RegExp(`^[a-zA-Z0-9_]{3,20}$`))) {
        this.$Message.error(
          "当前账号名只能由数字、字母和下划线组成，长度3-20个字符"
        );
        return;
      }
      await uploadInspectionUser({
        id: row.id,
        loginName: row.loginName,
        password: "123456"
      });
      this.$Message.success("保存成功！");
      this.getList();
    },
    toDelete(index) {
      const row = this.users[index];
      if (!row.id) {
        this.users.splice(index, 1);
        return;
      }
      this.$Modal.confirm({
        title: "删除警告",
        content: "确定要删除当前账号吗？",
        onOk: () => {
          this.toDel(row.id);
        }
      });
    },
    async toDel(id) {
      await deleteInspectionUser(id);
      this.$Message.success("删除成功！");
      this.getList();
    }
  }
};
</script>
