<template>
  <div class="template_content">
    <!-- 搜索 -->
    <div class="search_box">
      <a-form layout="inline">
        <a-form-item label="查询条件：">
          <a-input v-model="searchPage.username" placeholder="用户名" allowClear></a-input>
        </a-form-item>
        <a-form-item>
          <a-button icon="search" type="primary" @click="handleSubmit">查询</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!-- 主体内容 -->
    <div class="content_box">
      <!-- 表格操作 -->
      <div class="table_top">
        <a-button
          icon="plus"
          type="primary"
          class="btn_right_margin"
          @click="showModal('')"
        >添加</a-button>
      </div>
      <a-table
        :columns="columns"
        :dataSource="data"
        :loading="loading"
        :pagination="pagination"
        bordered
        size="small"
        @change="handleTableChange"
        rowKey="id"
      >
        <!-- 角色 -->
        <span slot="roleList" slot-scope="roleList">
          <a-tag v-for="role in roleList" :key="role.roleId" color="purple">{{role.name}}</a-tag>
        </span>
        <!-- 状态 -->
        <span slot="statusFlag" slot-scope="status">
          <a-tag
            :key="status"
            :color="status == 'ENABLE'?'#108ee9':'#f50'"
          >{{status == 'ENABLE'?"启用":"禁用"}}</a-tag>
        </span>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            icon="edit"
            type="link"
            size="small"
            @click="showModal(record)"
          >修改</a-button>
          <a-button
            icon="delete"
            type="link"
            @click="deleteRow({record})"
          >删除</a-button>
        </template>
      </a-table>
    </div>
    <!-- 弹窗 -->
    <a-modal :title="modalTitle" v-model="modalVisible" :footer="null">
      <a-form :form="modalForm" @submit="modalHandleSubmit">
        <a-form-item label="用户名" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="['username', { rules: [{ required: true, message: '用户名不能为空' }] }]"
            placeholder="请输入用户名"
            :disabled="modalType == 'edit'"
          />
        </a-form-item>
        <a-form-item v-if="modalType == 'add'" label="密码" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input-password
            v-decorator="['password', { rules: [{ required: true, message: '密码不能为空' }] }]"
            placeholder="请输入密码"
          />
        </a-form-item>
        <a-form-item label="昵称" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-input
            v-decorator="['nickName']"
            placeholder="请输入昵称"
          />
        </a-form-item>
        
        <a-form-item label="角色" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-select
            v-decorator="[
          'roleIdList',
          { rules: [{ required: true, message: '角色不能为空'}] },
        ]"
            placeholder="请选择角色"
            mode="multiple"
          >
            <a-select-option
              v-for="item in roleList"
              :key="item.id"
              :value="item.id"
            >{{item.name}}</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
          <a-select
            v-decorator="['status']"
          >
            <a-select-option value="ENABLE">启用</a-select-option>
            <a-select-option value="DISABLE">禁用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :wrapper-col="{ span: 19, offset: 5 }">
          <a-button type="primary" html-type="submit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script>
// 导入接口
import { addObj, delObj, fetchList, getObj, putObj } from "@/api/admin/user";
import { getRoleList } from "@/api/admin/role";
import { fetchTree } from "@/api/admin/dept";
import { disposereq,timestampToTime } from "@/utils/util";
let columns = [
  {
    title: "用户名",
    dataIndex: "username",
    align: "center"
  },
  {
    title: "昵称",
    dataIndex: "nickName",
    align: "center"
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    width: '100px',
    scopedSlots: { customRender: "statusFlag" }
  },
  {
    title: "角色",
    dataIndex: "roleIdList",
    align: "center",
    scopedSlots: { customRender: "roleList" }
  },
  
  {
    title: "创建时间",
    dataIndex: "createTime",
    align: "center",
    width: '180px',
    customRender: (text,record) => {
      return timestampToTime(text);
    }
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "action" },
    align: "center",
    width: '180px'
  }
];

export default {
  data() {
    return {
      username: "",
      loading: true,
      searchPage: {
        pageIndex: 1,
        pageSize: 10,
        username: ""
      },
      columns: columns,
      data: [],
      pagination: {
        showQuickJumper: true,
        showSizeChanger: true
      },
      modalVisible: false,
      modalTitle: '添加',
      modalType: '',
      modalForm: this.$form.createForm(this, { name: "coordinated" }),
      parameters: {
        username: "",
        password: "",
        role: [],
        status: "ENABLE"
      },
      roleList: "",
      rowData: {},
      fieldNames: { label: "name", value: "id", children: "children" }
    };
  },
  // 创建完毕
  created() {
    this.getList(this.searchPage);
    this.getRoleList();
  },
  // 即将更新渲染
  beforeUpdate() {
    
  },
  methods: {
    // 获取用户
    getList(pageData) {
      fetchList(pageData)
        .then(res => {
          // console.log(res);
          this.loading = false;
          if (res.code === 200) {
            this.data = res.data;
            const pager = { ...this.pagination };
            pager.current = pageData.pageIndex;
            pager.total = res.count;
            this.pagination = pager;
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          // console.log(err);
          disposereq(this, err);
        });
    },
    // 获取角色
    getRoleList() {
      getRoleList()
        .then(res => {
          // console.log(res);
          this.loading = false;
          if (res.resp_code == 200) {
            this.roleList = res.datas;
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          disposereq(this, err);
        });
    },
    // 表格数据变化触发事件
    handleTableChange(pagination, filters, sorter) {
      const searchPage = { ...this.searchPage };
      searchPage.pageIndex = pagination.current;
      searchPage.pageSize = pagination.pageSize;
      this.loading = true;
      this.getList(searchPage);
    },
    // 搜索事件
    handleSubmit() {
      const searchPage = { ...this.searchPage };
      this.loading = true;
      this.getList(searchPage);
    },
    // 显示对话框
    showModal(row) {
      this.modalVisible = true;
      // 判断添加或者编辑
      if (row == "") {
        this.modalTitle = '添加';
        this.modalType = "add";
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            username: "",
            password: "",
            nickName: "",
            roleIdList: [],
            status: "ENABLE"
          });
        });
      } else {
        console.log(row);
        this.modalTitle = '编辑';
        this.modalType = "edit";
        // 获取角色liebiao
        let role = [];
        for (let i = 0; i < row.roleIdList.length; i++) {
          role.push(row.roleIdList[i].id);
        }
        this.$nextTick(() => {
          this.modalForm.setFieldsValue({
            username: row.username,
            nickName: row.nickName,
            roleIdList: role,
            status: row.status
          });
          this.rowData = row;
        });
      }
    },
    // 删除行数据
    deleteRow(row) {
      delObj([row.record.id])
        .then(res => {
          this.loading = false;
          if (res.resp_code == 200) {
            this.$message.success('删除成功');
            const searchPage = { ...this.searchPage };
            this.loading = true;
            this.getList(searchPage);
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch(err => {
          disposereq(this, err);
        });
    },
    // 对话框
    modalHandleSubmit(e) {
      e.preventDefault();
      this.modalForm.validateFields((err, values) => {
        if (!err && this.modalType == "add") {
          // console.log(values);
          addObj(values)
            .then(res => {
              if (res.resp_code == 200) {
                this.modalVisible = false;
                this.$message.success('保存成功');
                const searchPage = { ...this.searchPage };
                this.loading = true;
                this.getList(searchPage);
              } else {
                this.$message.info(res.resp_msg);
              }
            })
            .catch(err => {
              this.$message.info(err);
            });
        } else if (!err && this.modalType == "edit") {
          this.rowData.username = values.username;
          this.rowData.nickName = values.nickName;
          this.rowData.roleIdList = values.roleIdList;
          this.rowData.status = values.status;
          // console.log(this.rowData);
          putObj(this.rowData)
            .then(res => {
              if (res.resp_code == 200) {
                this.modalVisible = false;
                this.$message.success('保存成功');
                const searchPage = { ...this.searchPage };
                this.loading = true;
                this.getList(searchPage);
              } else {
                this.$message.info(res.resp_msg);
              }
            })
            .catch(err => {
              this.$message.info(err);
            });
        }
      });
    }
  }
};
</script>
<style>
.search_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}
.template_content {
  background-color: #f0f2f5;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.content_box {
  width: 100%;
  background-color: #fff;
  margin-top: 10px;
  padding: 14px;
}
.table_top {
  padding-bottom: 14px;
}
.btn_margin {
  margin: 0px 5px;
}
.btn_right_margin {
  margin-right: 10px;
}
</style>