<template>
  <div class="myOranization">
    <el-card>
      <div class="oranizationInfo">
        <span>机构名称:{{ orgList.orgname }}</span>
        <span>联系人:{{ orgList.contactor }}</span>
        <span>联系人电话:{{ orgList.contactor_phone }}</span>
        <span>地址:{{ orgList.address }}</span>
        <span>主营业务描述:{{ orgList.main_business }}</span>
      </div>
    </el-card>

    <el-card>
      <div class="main-content" style="margin-top: 8px;display:flex;">
        <el-select v-model="searchValue" filterable placeholder="请选择账户" @change="selectSearch" @input="input"
                   clearable size="small">
          <el-option v-for="item in tableData" :key="item.id" :label="item.username" :value="item.id">
          </el-option>
        </el-select>
        <el-button type="success" class="myButton" size="small" style="margin-left: 15px" @click="addNewUser('form')">
          添加新用户
        </el-button>
      </div>
    </el-card>

    <el-card class="table">
      <el-table :data="tableData" style="width: 100%" height="450" border>
        <el-table-column align="center" prop="username" label="用户名称" min-width="150px"></el-table-column>
        <el-table-column align="center" prop="address" label="地址" min-width="200px"></el-table-column>
        <el-table-column align="center" prop="mobile" label="手机号" min-width="130px"></el-table-column>
        <el-table-column align="center" prop="email" label="邮箱" min-width="150px"></el-table-column>
        <el-table-column align="center" prop="" label="用户状态" min-width="110px">
          <template slot-scope="scope">
            {{ getResult(scope.row.user_status) }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态操作">
          <template slot-scope="scope">
            <!-- <el-button size="small" type="danger" @click="outOfService(scope.row)" :disabled="scope.row.user_status==1||scope.row.user_status==2">停用</el-button> -->
            <!-- <el-button size="small" type="success" @click="recover(scope.row)" :disabled="scope.row.user_status==0||scope.row.user_status==2">恢复</el-button> -->
            <el-button size="small" type="warning" @click="signOut(scope.row)" :disabled="scope.row.user_status==2">
              注销
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="260px">
          <template slot-scope="scope">
            <el-button size="small" type="success" @click="addRole(scope.row)"
                       :disabled="scope.row.user_status==1||scope.row.user_status==2" class="addBtn">添加角色
            </el-button>
            <el-button size="small" type="primary" @click="editNewUser(scope.row)"
                       :disabled="scope.row.user_status==1||scope.row.user_status==2">编辑
            </el-button>
            <!-- <el-button size="small" type="danger" @click="delNewUser(scope.row)" :disabled="scope.row.user_status==1||scope.row.user_status==2">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑用户 -->
    <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" :visible.sync="dialogVisible" width="30%" class="myDialog"
               :append-to-body="true" custom-class="addPeople">
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">
        <el-form-item label="用户名称:" prop="username" v-if="!isEdit">
          <el-input v-model="form.username"/>
        </el-form-item>
        <el-form-item label="昵称:" prop="nick_name">
          <el-input v-model="form.nick_name"/>
        </el-form-item>
        <el-form-item label="密码:" prop="password" v-if="!isEdit">
          <el-input v-model="form.password" placeholder="请输入密码" show-password/>
        </el-form-item>
        <el-form-item label="确认密码:" prop="confirmPassword" v-if="!isEdit">
          <el-input v-model="form.confirmPassword" placeholder="请输入确认密码" show-password/>
        </el-form-item>
        <el-form-item label="地址:" prop="address">
          <el-input v-model="form.address"/>
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="form.mobile"/>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="form.email"/>
        </el-form-item>
        <el-form-item>
          <el-button size="small" type="primary" @click="onSubmit('form')">确 定</el-button>
          <el-button size="small" @click="handleClose('form')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加角色 -->

    <el-dialog :title="'请为' + this.titleName + '添加角色'" :visible.sync="isShow" width="30%"
               :before-close="addRolehandleClose" class="myDialog2" :append-to-body="true" custom-class="addJueSe">
      <div class="roleList">
        <Tree :tree-data="treeData" ref="tree" node-key="id" id="roleTree" :default-props="defaultProps"
              :showCheckbox="true"></Tree>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancel()">取 消</el-button>
        <el-button size="small" type="primary" @click="roleSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Tree from "@/components/TreeControl/index.vue";

import {
  myOrganizationAPI,
  addUserroleAPI,
  addUserAPI,
  editUserAPI,
  delUserAPI,
  getuserrolesAPI, getOrgroleAPI
} from "@/api/superAdministrator/management";


export default {
  components: {
    Tree,
  },
  data() {
    return {
      dialogVisible: false,
      isEdit: false,
      isShow: false,
      searchValue: '',
      rules: {
        username: [{required: true, message: "请输入用户名称", trigger: "blur"}],
        password: [{required: true, message: "请输入密码", trigger: "blur"}],
        confirmPassword: [{required: true, message: "请再次输入密码", trigger: "blur"}],
        address: [{required: true, message: "请输入地址", trigger: "blur"}],
        nick_name: [{required: true, message: "请输入昵称", trigger: "blur"}],
        mobile: [{pattern: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: "请输入有效的手机号"},
          {required: true, trigger: "blur", message: "请输入手机号"}],
        email: [{pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/, message: "请输入有效的邮箱"},
          {required: true, trigger: "blur", message: "请输入邮箱"}],
      },
      treeData: [],
      tableData: [],
      id: sessionStorage.getItem("userId"),
      user_id: "",
      treeNodeId: "",
      org_type: "",
      orgid: "",
      form: {
        username: "",

        password: "",
        confirmPassword: "",
        address: "",
        mobile: "",
        org_type: "",
        email: "",
        nick_name: "",
      },
      orgList: {
        orgname: "",
        contactor: "",
        contactor_phone: "",
        address: "",
        main_business: "",
      },
      userid: "",
      defaultProps: {
        children: "children",
        label: "role",
      },
      treeNode: null,
      titleName: "",
      isDisabled: false,
      name: "管理员",
    };
  },
  created() {
    this.myOrganization();
  },
  methods: {
    input(e) {
      this.myOrganization(e)
    },
    selectSearch(e) {
    },

    outOfService(row) {//停用
      this.$confirm("确定停用此账户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          editUserAPI({id: row.id, user_status: 1}).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "停用成功",
                type: "success",
              });
              this.myOrganization();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消停用",
          });
        });
    },
    recover(row) {//恢复
      this.$confirm("确定恢复此账户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          editUserAPI({id: row.id, user_status: 0}).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "恢复成功",
                type: "success",
              });
              this.myOrganization();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消恢复",
          });
        });
    },
    signOut(row) {
      this.$confirm("一经注销,不可恢复,确定注销此账户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          editUserAPI({id: row.id, user_status: 2}).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "注销成功",
                type: "success",
              });
              this.myOrganization();
            } else {
              this.$message({
                message: res.msg,
                type: "error",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消注销",
          });
        });
    },
    myOrganization(uid) {
      let params = {
        id: this.id
      }
      if (uid) {
        params.uid = uid;
      }
      myOrganizationAPI(params).then((res) => {
        if (res.status == true && res.dada.length > 0) {
          if (res.users.length == 1) {
            this.isDisabled = true;
          }
          this.orgList.orgname = res.dada[0].orgname;
          this.orgList.contactor = res.dada[0].contactor;
          this.orgList.contactor_phone = res.dada[0].contactor_phone;
          this.orgList.address = res.dada[0].address;
          this.orgList.main_business = res.dada[0].main_business;
          this.orgList.id = res.dada[0].id;
          this.org_type = res.dada[0].org_type;
          this.orgid = res.dada[0].id;
          this.tableData = res.users.map((item) => {
            let myOrganizations = {
              username: item.username,
              password: item.password,
              address: item.address,
              mobile: item.mobile,
              email: item.email,
              user_status: item.user_status,
              id: item.id,
              nick_name: item.nick_name
            };
            return myOrganizations;
          });
        }

        // console.log(this.tableData);
        // console.log(res);
      });
    },
    handleClose(formName) {
      this.dialogVisible = false;
      this.$refs.form.resetFields();
    },

    addRole(row) {
      this.isShow = true;
      this.userid = row.id;
      this.titleName = row.username;
      getOrgroleAPI({org_type: this.org_type}).then((res) => {    //获取org_type一样的全部角色
        this.treeData = res.data;
      });
      this.getuserroles();
    },
    roleSubmit() {//点击确定添加角色
      this.isShow = false;
      const roleIds = this.$refs.tree.getCheckedKeys();
      let params = {
        userid: this.userid,
        roleid: JSON.stringify(roleIds),
      };
      addUserroleAPI(params).then((res) => {//添加角色
        // console.log(res);
        if (res.status == true) {
          this.getuserroles();
          this.$message({
            message: "角色添加成功",
            type: "success",
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    getuserroles() {//获取此用户已拥有的所有角色
      getuserrolesAPI({userid: this.userid}).then((res) => {
        if (res) {
          this.treeNode = res.data.map((item) => {
            if (item.roleid.role == "管理员") {
              this.treeNodeId = item.roleid.id;
            }
            return {
              create_at: item.create_at,
              del_flg: item.del_flg,
              id: item.roleid.id,
              org_type: this.org_type,
              role: item.roleid,
            };
          });
          if (this.isDisabled) {
            this.treeData.forEach((item, index) => {
              if (item.id == this.treeNodeId) {
                this.treeData[index].disabled = true;
              } else {
                this.treeData[index].disabled = false;
              }
            });
          }
          this.$refs.tree.setCheckedNodes(this.treeNode);
        }
      });
    },
    addRolehandleClose() {
      this.isShow = false;
    },
    addNewUser(row) {
      this.dialogVisible = true;
      this.isEdit = false;
      this.$nextTick(() => {
        this.$refs.form.resetFields();
      })
    },
    editNewUser(row) {

      this.dialogVisible = true;
      this.isEdit = true;
      this.form = JSON.parse(JSON.stringify(row));
      this.form.password = "";
      this.user_id = row.id;
    },
    delNewUser(row) {// 删除账户
      this.$confirm("确定删除此账户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delUserAPI({id: row.id}).then((res) => {
            if (res.status == true) {
              this.$message({
                message: "用户删除成功",
                type: "success",
              });
              this.myOrganization();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    onSubmit(formName) {// 添加新用户&&编辑新用户
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (!this.isEdit) {// 添加
            if (this.form.password == this.form.confirmPassword) {
              let params = {
                username: this.form.username,
                password: this.form.password,
                email: this.form.email,
                nick_name: this.form.nick_name,
                address: this.form.address,
                mobile: this.form.mobile,
                org_type: this.org_type,
                orgid: this.orgid,
              };
              if (window.location.href.includes('kaiyuancloud') && window.location.href.includes('domain_name') || !window.location.href.includes('kaiyuancloud')) {
                params.user_reseller = "1"
              }
              addUserAPI(params).then((res) => {
                if (res.status == true) {
                  this.myOrganization();
                  this.$message({
                    message: "用户添加成功",
                    type: "success",
                  });
                  alert('添加成功,请为此用户添加角色')
                  this.$refs.form.resetFields();
                  this.dialogVisible = false;
                } else {
                  this.$message({
                    message: res.msg,
                    type: 'error'
                  })
                }
              });
            } else {
              this.$message({
                message: "确认密码与输入密码不一致",
                type: "error",
              });
            }
          } else { // 编辑
            let params = {
              // username: this.form.username,
              email: this.form.email,
              address: this.form.address,
              mobile: this.form.mobile,
              org_type: this.org_type,
              id: this.user_id,
              nick_name: this.form.nick_name,
            };
            //密码为空的时候为保留原密码,不做更改666
            if (this.form.password != "") {
              params.password = this.form.password;
            }
            editUserAPI(params).then((res) => {
              if (res.status == true) {
                this.myOrganization();
                this.$message({
                  message: "用户编辑成功",
                  type: "success",
                });
                this.dialogVisible = false;
              } else {
                this.$message({
                  message: res.msg,
                  type: 'error'
                })
              }
            });
          }
        } else {
          this.$message({
            message: "用户编辑失败",
            type: "error",
          });
          return false;
        }
      });
    },
    cancel() {
      this.isShow = false;
      // this.$refs.form.resetFields();
    },
    getFormData(object) {
      //转换参数为formdata格式
      const formData = new FormData();
      Object.keys(object).forEach((key) => {
        const value = object[key];
        if (Array.isArray(value)) {
          value.forEach((subValue, i) => {
            formData.append(key + `[${i}]`, subValue);
          });
        } else {
          formData.append(key, object[key]);
        }
      });
      return formData;
    },
    getResult(data) {
      switch (data) {
        case '0':
          return "正常";
        case '1':
          return "停用";
        case '2':
          return "注销";
      }
    },
  },
};
</script>

<style lang="scss" scope>
.myOranization {
  height: 81vh;

  .oranizationInfo {
    // height: 2rem;
    color: #a1aca5;
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    font-size: 18px;
  }

  .table {
    height: 70%;
    margin-top: 8px;
    overflow-y: auto;
  }

  .myButton {
    //margin-left: 85%;
  }
}

.addBtn {
  //width: 50%;
}

.main-content {
  display: flex;
  justify-content: space-between;
}

</style>
<style>
@media screen and (max-width: 760px) {
  .addPeople {
    //border:10px solid red;
    width: 100vw !important;
  }

  .addJueSe {
    width: 80vw !important;
  }
}
</style>
