<template>
  <div class="app-container">
    <el-row type="flex" justify="space-between" ref="listQueryContainer" class="query-container">
      <el-col>
        <el-form :inline="true" style="flex-wrap: wrap" :model="listQuery" ref="listQuery" @submit.native.prevent @keyup.enter.native="onSubmit">
          <el-form-item label="角色" prop="roleId">
            <el-select v-model="listQuery.roleId" placeholder="请选择" clearable @clear="listQuery.roleId=undefined" @change="onFilterChange">
              <el-option v-for="item in roles" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="用户名" prop="username">
            <el-input v-model.trim="listQuery.username" maxlength="16" placeholder="请输入用户名" clearable @clear="listQuery.username=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="昵称" prop="nickname">
            <el-input v-model.trim="listQuery.nickname" maxlength="16" placeholder="请输入昵称" clearable @clear="listQuery.nickname=undefined" @keyup.enter.native="onFilterChange">
              <i slot="suffix" class="el-input__icon el-icon-search" @click="onFilterChange"></i>
            </el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-select v-model="listQuery.gender" placeholder="请选择" clearable @clear="listQuery.gender=undefined" @change="onFilterChange">
              <el-option v-for="item in genderList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="是否禁用" prop="disabled">
            <el-select v-model="listQuery.disabled" placeholder="请选择" clearable @clear="listQuery.disabled=undefined" @change="onFilterChange">
              <el-option v-for="item in disableStatusList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="生日提醒" prop="birthdayRemind">
            <el-select v-model="listQuery.birthdayRemind" placeholder="请选择" clearable @clear="listQuery.birthdayRemind=undefined" @change="onFilterChange">
              <el-option v-for="item in birthdayRemindStatusList" :key="item.id" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间范围" prop="createTimeRange">
            <el-date-picker
                v-model="listQuery.createTimeRange"
                value-format="timestamp"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>

          <el-form-item label="生日范围" prop="birthdayRange">
            <el-date-picker
                v-model="listQuery.birthdayRange"
                value-format="timestamp"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
                @change="onFilterChange">
            </el-date-picker>
          </el-form-item>

          <el-form-item label-width="0">
            <el-button @click="onFilterChange" type="primary">查询</el-button>
            <el-button @click="resetFields" plain type="primary">重置</el-button>
            <el-button @click="onExport" plain type="primary">导出</el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <form-clear :shrinkable="shrinkable" @clear="resetFields" @change="onExpansion"/>
    </el-row>

    <el-row>
      <el-button @click="onAdd" type="primary">添加</el-button>
      <el-button v-if="!editing" @click="onBatchDelete" plain type="primary">批量删除</el-button>
      <el-button v-if="editing" @click="onDeleteSelect" type="danger" :disabled="!(selectIds&&selectIds.length)">删除</el-button>
      <el-button v-if="editing" @click="onCancel" plain>取消</el-button>
    </el-row>

    <el-table :data="list" border stripe highlight-current-row ref="table" class="mt10" @sort-change="onSortChange" @selection-change="onTableSelectionChange" @row-click="onRowClick">
      <el-table-column v-if="editing" type="selection" width="55" fixed></el-table-column>
      <el-table-column type="index" :index="indexCompute" label="序号" align="center" fixed="left" width="60px"/>
      <el-table-column prop="username" label="用户名" sortable="custom" align="center" show-overflow-tooltip min-width="100px"/>
      <el-table-column prop="nickname" label="昵称" sortable="custom" align="center" show-overflow-tooltip min-width="100px"/>
      <el-table-column prop="roles" label="角色" align="center" min-width="200px">
         <template v-slot="scope">{{ scope.row.roles.map(item => item.name).join('、') }}</template>
      </el-table-column>

      <el-table-column prop="gender" label="性别" sortable="custom" align="center" width="80px">
         <template v-slot="scope">{{ genderList.find(item => item.id === Number(scope.row.gender)).label }}</template>
      </el-table-column>

      <el-table-column prop="avatar" label="头像" sortable="custom" align="center" width="80px">
         <template v-slot="scope">
          <el-avatar icon="el-icon-user-solid" :src="scope.row.avatar" fit="cover"></el-avatar>
        </template>
      </el-table-column>

      <el-table-column prop="disabled" label="是否禁用" sortable="custom" align="center" width="120px">
         <template v-slot="scope">
          <el-switch v-model="scope.row.disabled" @click.native.stop @change="onChangeEnabled(scope.row, scope.row.disabled)"></el-switch>
        </template>
      </el-table-column>

      <el-table-column prop="birthday" label="生日" sortable="custom" align="center" width="120px">
         <template v-slot="scope">
          <text-label align="left" :type="scope.row.birthdayRemind?'primary':''">{{ scope.row.birthday | dateFormat("yyyy-MM-dd") }} <i v-if="scope.row.birthdayRemind" class="el-icon-bell"></i></text-label>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" sortable="custom" align="center" width="160px">
         <template v-slot="scope">{{ scope.row.createTime | dateFormat }}</template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="160px">
         <template v-slot="scope">
          <el-link type="primary" icon="el-icon-edit" @click="onUpdate(scope.row)">编辑</el-link>
          <el-link type="danger" icon="el-icon-delete" @click="onDelete(scope.row)" class="ml20">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination :total="total" :page.sync="listQuery.page" :size.sync="listQuery.size" @change="onPageChange"/>

    <el-dialog title="导出" :visible.sync="exportVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="600px">
      <el-progress :text-inside="true" :stroke-width="24" :percentage="exportProgress" status="success"></el-progress>
      <el-button slot="footer" @click="onCancelExport">取 消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {dateFormat} from "@/utils/dateUtil"

export default {
  name: "SystemUser",
  data() {
    return {
      shrinkable: false, // 查询条件是否可以展开
      listQuery: { // 查询对象
        roleId: undefined, // 角色
        username: undefined, // 用户名
        nickname: undefined, // 昵称
        gender: undefined, // 性别
        disabled: undefined, // 是否禁用
        createTimeRange: [], // 创建时间
        createTimeStart: undefined,
        createTimeEnd: undefined,
        birthdayRange: [], // 生日
        birthdayStart: undefined,
        birthdayEnd: undefined,
        birthdayRemind: undefined, // 生日提醒
        order: undefined,
        page: 1,
        size: 10
      },

      roles: undefined, // 角色
      list: [], // 结果列表
      total: 0, // 总结果数量

      exportVisible: false, // 是否显示导出对话框
      exportData: [], // 导出数据
      exportPagination: { // 导出分页
        page: 1,
        size: 500,
      },
      exportProgress: 0, // 导出进度
      exportCancel: false, // 是否取消导出

      editing: false, // 表格编辑中

      selectIds: undefined, // 选中多条记录的id

      genderList: [{id: 0, label: "保密"}, {id: 1, label: "男"}, {id: 2, label: "女"}],
      disableStatusList: [{id: false, label: "启用"}, {id: true, label: "禁用"}],
      birthdayRemindStatusList: [{id: false, label: "否"}, {id: true, label: "是"}],
    }
  },

  watch: {
    'listQuery.createTimeRange'(value) {
      if (value) {
        this.listQuery.createTimeStart = value[0];
        this.listQuery.createTimeEnd = value[1];
      } else {
        this.listQuery.createTimeStart = undefined;
        this.listQuery.createTimeEnd = undefined;
      }
    },
    'listQuery.birthdayRange'(value) {
      if (value) {
        this.listQuery.birthdayStart = value[0];
        this.listQuery.birthdayEnd = value[1];
      } else {
        this.listQuery.birthdayStart = undefined;
        this.listQuery.birthdayEnd = undefined;
      }
    },
  },

  // 页面创建
  created() {
    this.initData();
    this.initEvent();
  },

  // 页面挂载
  mounted() {
    this.initView();
    this.initQuery();
    this.getList();
  },

  // keep-alive 显示界面时调用
  activated() {
    this.getRole()
    let roleId = this.$route.params.roleId && Number(this.$route.params.roleId)
    if (roleId) {
      this.listQuery.roleId = roleId;
      this.getList();
    }
  },

  // keep-alive 页面隐藏
  deactivated() {
  },

  methods: {
    // 初始化数据
    initData() {
    },

    // 初始化事件
    initEvent() {
      this.$eventBus.$on("SystemUserAdd", this.onAddComplete);
      this.$eventBus.$on("SystemUserUpdate", this.onUpdateComplete);
    },

    // 初始化查询条件
    initQuery() {
      if (this.$store.state.app.paramCache) {
        let query = this.$storage.getData(this.$options.name);
        if (Object.keys(query).length > 0) {
          this.listQuery = query;
          if (query.order) {
            this.$refs.table.sort(query.order.substring(1), query.order.substring(0, 1) === "+" ? "ascending" : "descending");
          } else {
            this.$refs.table.clearSort();
          }
        }
      }
    },

    // 初始化视图
    initView() {
      this.$nextTick(() => {
        this.shrinkable = this.$store.state.app.filterShrink && this.$refs['listQuery'].$el.offsetHeight > 51;
      })
    },

    // 展开/收起查询条件
    onExpansion(show) {
      this.$refs['listQueryContainer'].$el.style.height = show ? "auto" : "51px";
    },

    // 表格索引
    indexCompute(index) {
      return index + 1 + (this.listQuery.page - 1) * this.listQuery.size;
    },

    // 表单提交
    onSubmit() {
      this.onFilterChange();
    },

    // 表单清除
    resetFields() {
      this.$refs['listQuery'].resetFields();
      this.listQuery.order = undefined;
      this.$refs.table.clearSort();
      this.onFilterChange();
    },

    // 添加
    onAdd() {
      this.onCancel();
      this.$router.push({path: '/system/user/add'})
    },

    // 编辑
    onBatchDelete() {
      this.editing = true;
    },

    // 删除选中
    onDeleteSelect() {
      this.$confirm('此操作将永久删除选中的记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete("/v1/system/user/delete", {params: {ids: this.selectIds}}).then((data) => {
          if (this.list.length <= this.selectIds.length && this.listQuery.page > 1) {
            this.listQuery.page -= 1;
          }
          this.selectIds = undefined;
          if (data > 0) {
            this.$message.success("删除成功");
          } else {
            this.$message.warning("删除失败");
          }
          this.getList();
        });
      });
    },

    // 取消编辑
    onCancel() {
      this.$refs['table'].clearSelection();
      this.editing = false;
    },

    // 禁用改变状态
    onChangeEnabled(data, val) {
      this.$confirm('此操作将 ' + (val ? '禁用 ' : '启用 ') + data.name + '角色, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$axios.put("/v1/system/user/update/status", {id: data.id, disabled: data.disabled}).then(() => {
          this.$message.success("更新成功！");
        }).catch(() => {
          data.disabled = !data.disabled
        })
      }).catch(() => {
        data.disabled = !data.disabled
      })
    },

    // 添加完成
    onAddComplete() {
      this.onFilterChange();
    },

    // 更新
    onUpdate(item) {
      this.$router.push({path: '/system/user/edit', query: {id: item.id}});
    },

    // 更新完成
    onUpdateComplete() {
      this.getList();
    },

    // 删除
    onDelete(item) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$axios.delete(`/v1/system/user/delete/${item.id}`).then((data) => {
          if (this.list.length === 1 && this.listQuery.page > 1) {
            this.listQuery.page -= 1;
          }
          if (data > 0) {
            this.$message.success("删除成功");
          } else {
            this.$message.warning("删除失败");
          }
          this.getList();
        });
      });
    },

    // 数据选择
    onTableSelectionChange(val) {
      this.selectIds = val.map(item => item.id);
    },

    // 排序改变
    onSortChange({prop, order}) {
      if (order === "ascending") {
        this.listQuery.order = "+" + prop;
      } else if (order === "descending") {
        this.listQuery.order = "-" + prop;
      } else {
        this.listQuery.order = undefined;
      }
      this.onFilterChange();
    },

    // 行点击
    onRowClick(row, column, event) {
      this.$refs["table"].setCurrentRow(row);
      if (this.editing) {
        this.$refs["table"].toggleRowSelection(row);
      }
    },

    // 条件改变
    onFilterChange() {
      this.listQuery.page = 1;
      this.$nextTick(this.getList);
    },

    // 页码改变
    onPageChange() {
      this.getList();
    },

    // 加载角色列表
    getRole() {
      this.$axios.get("/v1/system/role/list/option", undefined, false).then(data => {
        this.roles = data;
      });
    },

    // 加载列表
    getList() {
      // 缓存参数
      if (this.$store.state.app.paramCache) {
        this.$storage.setData(this.$options.name, this.listQuery);
      }

      this.$axios.get("/v1/system/user/list", {params: this.listQuery}).then(data => {
        this.list = data.list;
        this.total = data.total;
        this.$refs["table"].doLayout();
      });
    },

    // 导出数据
    onExport() {
      if (this.total > 0) {
        this.exportPagination.page = 1;
        this.exportData = [];
        this.exportVisible = true;
        this.getExportData();
      }
    },

    // 取消导出
    onCancelExport() {
      this.exportVisible = false;
      this.exportCancel = true;
    },

    // 获取数据并导出
    getExportData() {
      if (!this.exportCancel) {
        this.$axios.get("/v1/system/user/list", {params: {...this.listQuery, ...this.exportPagination}}).then(data => {
          this.exportPagination.page++;
          this.exportData = this.exportData.concat(data.list);
          this.exportProgress = Math.round(this.exportData.length * 100 / this.total);
          if (this.exportData.length < this.total && data.list.length > 0) {
            this.getExportData();
          } else {
            this.exportVisible = false;

            let tHeader = ["序号",
              "用户名",
              "昵称",
              "头像",
              "省",
              "市",
              "区",
              "性别",
              "生日",
              "生日提醒",
              "民族",
              "身高",
              "兴趣、爱好",
              "个人简介",
              "经历",
              "是否禁用",
              "创建时间",
              "更新时间",
              "角色",
            ];
            let filterVal = ["index",
              "username",
              "nickname",
              "avatar",
              "province",
              "city",
              "area",
              "gender",
              "birthday",
              "birthdayRemind",
              "ethnic",
              "height",
              "hobby",
              "brief",
              "experience",
              "disabled",
              "createTime",
              "updateTime",
              "roles",
            ];
            let data = this.exportData.map((value, index) => filterVal.map((key) => {
              if (key === "index") {
                return index + 1;
              } else if (key === "gender") {
                return this.genderList.find(item => item.id === value[key]).label;
              } else if (key === "birthday") {
                return dateFormat("yyyy-MM-dd", value[key]);
              } else if (key === "birthdayRemind") {
                return value[key] ? '是' : '否';
              } else if (key === "disabled") {
                return this.birthdayRemindStatusList.find(item => item.id === value[key]).label;
              } else if (key === "createTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "updateTime") {
                return dateFormat("yyyy-MM-dd HH:mm:ss", value[key]);
              } else if (key === "roles") {
                return value[key].join('、');
              } else {
                return value[key];
              }
            }));
            import('@/utils/Export2Excel').then(excel => {
              excel.export_json_to_excel({
                header: tHeader, // 表头 必填
                data, // 具体数据 必填
                filename: '系统设置-用户信息列表', // 非必填
                autoWidth: true, // 非必填
                bookType: 'xlsx' // 非必填
              })
            })
          }
        });
      }
    }
  }
}
</script>

<style scoped lang="scss">
.app-container {
  .avatar {
    border-radius: 50%;
    width: 30px;
    height: 30px;
    cursor: pointer;

    ::v-deep .el-upload, .el-image {
      height: 100%;
    }
  }
}
</style>
