<template>
  <div class="common-box">
    <!--条件-->
    <el-form :model="listQuery" ref="queryForm" :inline="true">
      <el-form-item label="用户编码">
        <el-input
          v-model="listQuery.loginId"
          placeholder="请输入用户编码"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名称">
        <el-input
          v-model="listQuery.userName"
          placeholder="请输入用户名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="联系方式">
        <el-input
          v-model="listQuery.coninfo"
          placeholder="请输入联系方式"
        ></el-input>
      </el-form-item>
      <el-form-item label="所属机构">
        <el-select
          v-model="listQuery.orgnId"
          placeholder="搜索所属机构"
          filterable
          remote
          :remote-method="remoteMethod"
          :loading="loadingsearch"
        >
          <el-option
            v-for="item in orgData"
            :key="item.orgId"
            :label="item.orgName"
            :value="item.orgId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getData('search')">查询 </el-button>
        <el-button @click="reset()">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          class="lake-Blue"
          type="primary"
          icon="el-icon-plus"
          @click="handleAddOrEdit(0, null, 'create')"
          >新增
        </el-button>
      </el-form-item>
    </el-form>
    <!--列表-->
    <div>
      <el-table
        v-loading="listLoading"
        element-loading-text="加载中"
        :data="list"
        fit
        stripe
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column label="用户编码" prop="loginId" />
        <el-table-column label="用户名称" prop="userName" />
        <el-table-column label="联系方式" width="120" prop="coninfo" />
        <el-table-column label="年龄" width="80" prop="age" />
        <el-table-column label="性别" width="80" prop="gend" />
        <el-table-column label="创建时间" width="140" prop="crteTime" />
        <el-table-column label="修改时间" width="140" prop="lstUpdTime" />
        <el-table-column label="说明" prop="dscr" />

        <el-table-column fixed="right" label="操作" width="250">
          <template
            slot-scope="scope"
            v-if="scope.row.loginId !== 'super-admin'"
          >
            <el-button
              icon="el-icon-edit"
              style="color: #52c8cc"
              type="text"
              @click="handleAddOrEdit(scope.$index, scope.row, 'update')"
              >编辑</el-button
            >
            <el-button
              icon="el-icon-delete"
              style="color: #ce4745"
              type="text"
              @click="handleDelete(scope.row, 'deleted')"
              >删除</el-button
            >
            <el-dropdown
              @command="(command) => handleCommand(command, scope.row)"
            >
              <span class="el-dropdown-link">
                <el-button
                  icon="el-icon-d-arrow-right"
                  style="color: #505152; margin-left: 10px"
                  type="text"
                  >更多
                </el-button>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="setRole">
                  <i class="el-icon-setting el-icon--left"></i>设置角色
                </el-dropdown-item>
                <el-dropdown-item command="resetPass" divided
                  ><i class="el-icon-refresh-right el-icon--left"></i>重置密码
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-->
    <yl-pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getData"
    />

    <!--添加/修改-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="420px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="80px"
        style="width: 370px; margin-left: 10px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model.trim="temp.userName" />
        </el-form-item>
        <el-form-item label="所属机构" prop="orgId">
          <el-input
            disabled
            v-model.trim="orgName"
            style="width: 210px; margin-right: 3px"
          />
          <el-button type="primary" icon="el-icon-plus" @click="chooseOrg"
            >选择</el-button
          >
        </el-form-item>
        <el-form-item label="联系方式" prop="coninfo">
          <el-input v-model.trim="temp.coninfo" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="temp.age"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="temp.gend">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="说明">
          <el-input type="textarea" v-model.trim="temp.dscr" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitData()">确认</el-button>
      </div>
    </el-dialog>

    <!--用户id，密码对话框-->
    <el-dialog
      title="提示"
      :visible.sync="passFormVisible"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-alert
        title="请保存用户编码和密码,方便后续进行登录！！！"
        type="warning"
        show-icon
        style="margin-bottom: 20px"
      >
      </el-alert>
      <el-descriptions class="margin-top" title="" :column="1" border>
        <el-descriptions-item>
          <template slot="label"> 用户名称 </template>
          {{ passData.userName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template slot="label"> 用户编码 </template>
          {{ passData.loginId }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template slot="label"> 密码 </template>
          {{ passData.pwd }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="passFormVisible = false"
          >关闭</el-button
        >
      </div>
    </el-dialog>

    <!--设置角色对话框-->
    <el-dialog
      title="设置角色"
      :visible.sync="roleFormVisible"
      width="610px"
      :close-on-click-modal="false"
    >
      <el-transfer
        filterable
        :filter-method="filterMethod"
        filter-placeholder="请输入角色名称"
        v-model="roles"
        :data="newRoleList"
        :titles="['可选角色', '已选角色']"
      >
      </el-transfer>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click="setRole()">确认</el-button>
      </div>
    </el-dialog>

    <!--选择机构-->
    <el-dialog
      v-if="dialogOrgFormVisible"
      title="选择机构"
      :visible.sync="dialogOrgFormVisible"
      width="1000px"
      :close-on-click-modal="false"
    >
      <organization
        @orgClose="orgClose"
        @orgSubmit="orgSubmit"
        :orgRadio="temp.orgId"
      ></organization>
    </el-dialog>
  </div>
</template>

<script>
import {
  setUser,
  resetPass,
  getUserData,
  getOrganData,
  getRoleData,
  setUserRole
} from "@/api/system/users";
import ylPagination from "@/components/yl-pagination";
import Organization from "@/views/page/system/users/components/organization";

export default {
  components: {
    ylPagination,
    Organization
  },

  watch: {},

  data() {
    return {
      // 回显机构名称
      orgName: "",
      // 选择机构对话框
      dialogOrgFormVisible: false,
      // 当前用户id
      currentUserId: "",
      // 角色列表
      roleList: [],
      newRoleList: [],
      // 选中的角色
      roles: [],
      filterMethod(query, item) {
        return item.label.indexOf(query) > -1;
      },
      // 打开角色设置对话框
      roleFormVisible: false,
      // 机构列表
      organList: [],
      // 打开用户id,密码对话框
      passFormVisible: false,
      // 用户id,密码
      passData: {},
      list: [], //列表
      total: 0, //分页
      listLoading: false,
      listQuery: {
        //条件查询
        userName: "",
        current: 1,
        size: 10,
        loginId: "",
        orgnId: "",
        coninfo: ""
      },
      searchForm: {
        current: 1,
        size: 10,
        orgName: "",
        orgId: ""
      },
      orgData: [],
      loadingsearch: false,
      rolesValue: [],
      dialogFormVisible: false, //是否对话框
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      temp: {
        //表单
        age: ""
      },
      dialogRoleFormVisible: false, //角色对话框
      tempRole: {},
      rules: {
        userName: [
          {
            required: true,
            message: "用户名称不能为空",
            trigger: "blur"
          },
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur"
          }
        ],
        orgId: [
          {
            required: true,
            message: "请选择所属机构",
            trigger: "change"
          }
        ],
        age: [
          {
            required: false,
            message: "年龄不能为空",
            trigger: "blur"
          },
          {
            pattern: /^(?:[1-9][0-9]?|1[01][0-9]|120)$/,
            message: "请输入正确的格式",
            trigger: "blur"
          }
        ],
        coninfo: [
          {
            required: true,
            message: "联系方式不能为空",
            trigger: "blur"
          },
          {
            pattern: /^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8\d|9\d)\d{8}$/,
            message: "请输入正确的格式",
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getData();
  },
  methods: {
    // 更多
    handleCommand(command, row) {
      if (command == "setRole") {
        this.setRoleBox(row);
      } else if (command == "resetPass") {
        this.editPass(row);
      }
    },

    // 选择机构
    chooseOrg() {
      this.dialogOrgFormVisible = true;
    },

    // 关闭机构对话框
    orgClose() {
      this.dialogOrgFormVisible = false;
    },

    // 获取到选中的机构
    orgSubmit(orgRadio, orgName) {
      this.temp.orgId = orgRadio;
      this.orgName = orgName;
      this.dialogOrgFormVisible = false;
    },

    // 获取机构列表
    getOrgaList(orgId) {
      if (orgId) {
        getOrganData({ orgId: orgId }).then((response) => {
          this.organList = response.data.records;
          if (this.organList.length > 0) {
            this.orgName = this.organList[0].orgName;
          } else {
            this.orgName = this.temp.orgId;
          }
        });
      }
    },

    // 重置密码
    editPass(row) {
      this.$confirm("确认重置密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let data = { id: row.id };
        resetPass(data).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.passData = {
            loginId: row.loginId,
            pwd: response.data,
            userName: row.userName
          };
          this.passFormVisible = true;
        });
      });
    },

    // 打开设置角色对话框
    setRoleBox(row) {
      this.currentUserId = row.userId;
      this.roles = [];
      getRoleData({ userId: row.userId, current: 1, size: 1000 }).then(
        (response) => {
          this.roleList = response.data.records;
          this.newRoleList = [];
          this.roleList.forEach((item, index) => {
            this.newRoleList.push({
              label: item.roleName,
              key: item.roleId
            });
            if (item.cho == "0") {
              this.roles.push(item.roleId);
            }
          });
          this.roleFormVisible = true;
        }
      );
    },

    // 去重
    duplicateRemoval(tempArr) {
      for (let i = 0; i < tempArr.length; i++) {
        for (let j = i + 1; j < tempArr.length; j++) {
          if (tempArr[i].roleId == tempArr[j].roleId) {
            tempArr.splice(j, 1);
            j--;
          }
        }
      }
      return tempArr;
    },

    // 设置角色
    setRole() {
      this.$confirm("确认提交", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let newRoles = [];
        this.roles.forEach((item, index) => {
          newRoles.push({ roleId: item, userId: this.currentUserId });
        });
        let newData = this.duplicateRemoval(newRoles);

        setUserRole(newData).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          this.roleFormVisible = false;
        });
      });
    },

    // 重置页面
    reset() {
      this.listQuery.loginId = "";
      this.listQuery.userName = "";
      this.listQuery.coninfo = "";
      this.listQuery.orgnId = "";
      this.getData();
    },
    // 查询所属机构
    remoteMethod(val) {
      this.loadingsearch = true;
      this.searchForm.orgName = val;
      getOrganData(this.searchForm)
        .then((response) => {
          this.orgData = response.data.records;
          this.loadingsearch = false;
        })
        .catch((err) => {});
    },
    //获取列表数据
    getData(type) {
      if (type == "search") {
        this.listQuery.current = 1;
      }
      this.listLoading = true;
      getUserData(this.listQuery)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    //提交表单数据
    commitData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(() => {
            setUser(this.temp).then((response) => {
              this.$message({
                message: "操作成功",
                type: "success"
              });
              this.dialogFormVisible = false;
              if (this.dialogStatus === "create") {
                this.passData = {
                  loginId: response.data.loginId,
                  pwd: response.data.pwd,
                  userName: this.temp.userName
                };
                this.passFormVisible = true;
              }
              this.getData();
            });
          });
        }
      });
    },

    // 打开添加/修改对话框
    handleAddOrEdit(index, row, type) {
      this.orgName = "";
      this.temp.orgId = "";
      //修改对话框
      if (type === "update") {
        this.temp = {
          id: row.id,
          userName: row.userName,
          orgId: row.orgId,
          age: row.age,
          gend: row.gend,
          coninfo: row.coninfo,
          dscr: row.dscr,
          type: "updt"
        };
        this.getOrgaList(row.orgId);
      } else {
        this.temp = {
          id: "",
          userName: "",
          orgId: "",
          age: "",
          gend: "",
          coninfo: "",
          dscr: "",
          type: "add"
        };
      }
      this.dialogStatus = type;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    //删除
    handleDelete(row, status) {
      this.$confirm("确认删除", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.temp = {
          id: row.id,
          userName: row.userName,
          orgId: row.orgId,
          age: row.age,
          gend: row.gend,
          coninfo: row.coninfo,
          dscr: row.dscr,
          type: "del"
        };
        setUser(this.temp).then((response) => {
          this.$message({
            message: "操作成功",
            type: "success"
          });
          //  解决element el-pagination分页最后一页数据清空了页码显示正确，但是列表为空
          const totalPage = Math.ceil((this.total - 1) / this.listQuery.size);
          const currentPage =
            this.listQuery.current > totalPage
              ? totalPage
              : this.listQuery.current;
          this.listQuery.current = currentPage < 1 ? 1 : currentPage;

          this.getData();
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-transfer-panel__body {
  height: 520px;
}
::v-deep .el-transfer-panel__list.is-filterable {
  height: 100%;
}
</style>
