<template>
  <div class="detail_contain">
    <p class="now_page_title">
      {{
        $route.name == "organizationuser"
          ? "权限管理  /  组织管理  /  组织详情  /"
          : "权限管理  /  用户管理  /"
      }}
      <span>{{
        $route.name == "organizationuser"
          ? "用户管理"
          : $route.name == "usersadd"
          ? "新增用户"
          : "用户详情"
      }}</span>
    </p>
    <div class="info_contain">
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="0px"
      >
        <el-form-item prop="account">
          <p class="formname">用户账号：</p>
          <el-input
            v-model="form.account"
            :disabled="tranform_flag(edit_flag)"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="password"
          :class="{ shortpass: edit_flag }"
        >
          <p class="formname">登录密码：</p>
          <el-input
            v-model="form.password"
            :disabled="tranform_flag(edit_flag)"
          ></el-input>
          <div
            v-if="edit_flag"
            class="fixpass"
            @click="change_pass()"
          >
            修改密码
          </div>
        </el-form-item>
        <el-form-item prop="nickname">
          <p class="formname">昵称：</p>
          <el-input v-model="form.nickname"></el-input>
        </el-form-item>
        <el-form-item prop="type">
          <p class="formname">用户类型：</p>
          <el-select
            v-model="form.type"
            placeholder="请选择"
            @change="change_type()"
          >
            <el-option
              v-for="item in typeoptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="systemname"
          v-if="form.type !== 1"
        >
          <p class="formname">业务系统名称：</p>
          <el-input v-model="form.systemname"></el-input>
        </el-form-item>
        <el-form-item
          prop="domain"
          v-if="form.type == 3 || form.type == 4"
        >
          <p class="formname">域名：</p>
          <el-input v-model="form.domain"></el-input>
        </el-form-item>
        <el-form-item
          prop="ip"
          v-if="form.type == 3 || form.type == 4"
        >
          <p class="formname">IP白名单：</p>
          <!-- <el-input v-model="form.ip"></el-input> -->
          <div style="width:1022px;min-height:60px;border:1px solid #dcdfe6;border-radius:4px;padding:5px;">
            <el-tag
              v-if="form.ip.length"
              :key="tag"
              v-for="tag in form.ip"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput"
            >新增</el-button>
          </div>
        </el-form-item>
        <el-form-item prop="contact">
          <p class="formname">联系人：</p>
          <el-input v-model="form.contact"></el-input>
        </el-form-item>
        <el-form-item prop="phone">
          <p class="formname">手机号码：</p>
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item prop="email">
          <p class="formname">邮箱：</p>
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item
          prop="origin"
          v-if="form.type !== 1"
        >
          <p class="formname">用户组织机构：</p>
          <el-select
            v-model="form.origin"
            placeholder="请选择"
          >
            <el-option
              v-for="item in originoptions"
              :key="item.value + 100"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="able">
          <p class="formname">是否禁用：</p>
          <el-select
            v-model="form.able"
            placeholder="请选择"
          >
            <el-option
              v-for="item in ableoptions"
              :key="item.value + 200"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="desc">
          <p class="formname">描述：</p>
          <el-input
            type="textarea"
            v-model="form.desc"
          ></el-input>
        </el-form-item>

        <el-form-item prop="person">
          <p class="formname">登记人：</p>
          <el-input
            v-model="form.person"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item prop="date">
          <p class="formname">登记日期：</p>
          <el-input
            v-model="form.date"
            disabled
          ></el-input>
        </el-form-item>

        <el-form-item class="apaas_button">
          <el-button
            @click="resetForm('form')"
            class="left"
            v-if="$route.name == 'usersadd'"
          >重置</el-button>
          <el-button
            type="primary"
            v-if="now_user==2"
            @click="onSubmit('form')"
            class="right"
          >保存</el-button>
          <el-button
            class="right"
            @click="backPage"
          >取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import uploadFile from "@/components/general/upload_file";
import { getRole, formatDateTime_date } from "@/utils/common";
import { mapGetters, mapState } from "vuex";
export default {
  props: {},
  components: {
    uploadFile,
  },
  data() {
    var check_phone = (rule, value, callback) => {
      var phone_ruler = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      setTimeout(() => {
        if (!phone_ruler.test(value)) {
          callback(new Error("请输入正确电话号码"));
        } else {
          callback();
        }
      });
    };
    var check_email = (rule, value, callback) => {
      var email_ruler =
        /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      setTimeout(() => {
        if (value && !email_ruler.test(value)) {
          callback(new Error("请输入正确邮箱地址"));
        } else {
          callback();
        }
      });
    };
    var checkip = (rule, value, callback) => {
      var reg =
        /(((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3});/g;
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error("请使用;隔开ip地址"));
        } else {
          callback();
        }
      }, 1000);
    };
    var user_name_pass = (rule, value, callback) => {
      var reg = /^[a-zA-Z0-9|\-|_|\.]+$/;
      setTimeout(() => {
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("只支持字母、数字、-、_、."));
        }
      }, 100);
    };
    return {
      form: {
        account: "",
        password: "",
        nickname: "",
        type: "",
        systemname: "",
        contact: "",
        phone: "",
        email: "",
        origin: "",
        able: "",
        desc: "",
        person: "",
        date: "",
        ip: [],
        domain: "",
      },
      dynamicTags: ["标签一", "标签二", "标签三"],
      inputVisible: false,
      inputValue: "",
      ip_arr: [],
      now_user: 0, //0：普通用户，1：组织管理员，2：超级管理员
      typeoptions: [
        {
          label: "普通用户",
          value: 3,
        },
        {
          label: "组织管理员",
          value: 2,
        },
        {
          label: "超级管理员",
          value: 1,
        },
        {
          label: "开发者",
          value: 4,
        },
      ],
      originoptions: [],
      ableoptions: [
        {
          label: "是",
          value: 0,
        },
        {
          label: "否",
          value: 1,
        },
      ],
      origin_arr: [],
      rules: {
        account: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { max: 16, message: "长度请不大于16个字符", trigger: "blur" },
          { min: 3, message: "长度请不小于3个字符", trigger: "blur" },
          { validator: user_name_pass, trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { max: 20, message: "长度应小于20个字符", trigger: "blur" },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          { max: 8, message: "长度应小于8个字符", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择用户类型", trigger: "change" },
        ],
        systemname: [
          { required: true, message: "请输入系统名称", trigger: "blur" },
          { max: 16, message: "长度应小于16个字符", trigger: "blur" },
        ],
        contact: [
          { required: true, message: "请输入联系人", trigger: "blur" },
          { max: 6, message: "长度应小于6个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入电话号码", trigger: "blur" },
          { validator: check_phone, trigger: "blur" },
        ],
        email: [
          // { required: true, message: "请输入邮箱地址", trigger: "blur" },
          { validator: check_email, trigger: "blur" },
        ],
        able: [
          { required: true, message: "请选择是否禁用", trigger: "change" },
        ],
        desc: [
          // { required: true, message: "请输入描述", trigger: "blur" },
          { max: 500, message: "长度小于500个字符", trigger: "blur" },
        ],
        origin: [
          { required: true, message: "请选择组织机构", trigger: "change" },
        ],
        domain: [{ required: true, message: "请输入域名", trigger: "blur" }],
        ip: [{ required: true, message: "请输入ip地址", trigger: "blur" }],
      },
      edit_flag: 0,
      baseinfo: {},
    };
  },
  computed: {
    ...mapGetters(["level"]),
    ...mapState(["userInfo"]),
  },
  created() {
    this.get_now_user();
    this.getOriginArr();
    this.get_now_page();
    if (this.userInfo) {
      this.now_user = this.level;
    } else {
      this.getCurrentUser();
    }
  },
  mounted() {},
  methods: {
    getCurrentUser() {
      this.$api.user.getNowUser().then(({ data }) => {
        if (data.success == 1) {
          this.$store.commit("userInfofun", data.data);
          this.now_user = this.level;
          console.log(this.level);
        } else {
          console.log(data.errMsg);
        }
      });
    },
    change_type() {
      // this.form.systemname = "";
      // this.form.domain = "";
      // this.form.ip = [];
      // this.form.origin = "";
    },
    handleClose(tag) {
      this.form.ip.splice(this.form.ip.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.ip.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    get_now_page() {
      console.log(this.$route);
      if (this.$route.path.indexOf("add") !== -1) {
        this.edit_flag = 0;
      }
      if (this.$route.path.indexOf("edit") !== -1) {
        this.edit_flag = 1;
        this.get_user();
      }
      if (this.$route.path.indexOf("detail") !== -1) {
        this.edit_flag = 2;
        this.get_user();
      }
    },
    tranform_flag(val) {
      return val ? true : false;
    },
    change_pass() {
      this.$http
        .put(`/apaas/backmgt/user/initalPasswd/${this.$route.params.id}`)
        .then((response) => {
          console.log(response);
          if (response.data.success) {
            this.$message.success("修改成默认密码成功 默认密码：123456");
          } else {
            this.$message.error("修改密码失败");
          }
        })
        .catch((response) => {
          this.$message.error("修改密码失败");
        });
    },
    get_user() {
      this.$http
        .get(`/apaas/backmgt/user/detail/${this.$route.params.id}`)
        .then((response) => {
          console.log(response);
          if (response.data.success) {
            let data = response.data.data;
            this.form = {
              account: data.user_id,
              password: "******",
              nickname: data.user_name,
              type: data.is_admin,
              systemname: data.system_name,
              contact: data.link_man,
              phone: data.phone + "",
              email: data.email,
              origin: data.department_id,
              able: data.state,
              desc: data.description,
              person: data.create_user,
              date: data.create_date,
              ip: data.ip_whitelist,
              domain: data.domain_name,
            };
          } else {
            this.$message.error("获取数据失败");
          }
        })
        .catch((response) => {
          this.$message.error("获取数据失败");
        });
    },
    transform_func(arr) {
      var temp = "";
      arr.forEach((e) => {
        temp = temp + e + ";";
      });
      return temp;
    },
    getOriginArr() {
      this.originoptions = [];
      this.$http
        .get("/apaas/backmgt/department/list")
        .then((response) => {
          if (response.data.success) {
            let data = response.data.data;
            // this.originoptions = data
            data.forEach((e) => {
              this.originoptions.push({
                label: e.department_name,
                value: e.department_id,
              });
            });
          } else {
            // this.$message.error("获取组织失败");
          }
        })
        .catch(function (response) {
          // this.$message.error("获取组织失败");
        });
    },
    removepic() {
      this.$refs.servicepic.handleRemove();
    },
    backPage() {
      this.$router.back(-1);
    },
    add_user() {
      // this.form.systemname = "";
      // this.form.domain = "";
      // this.form.ip = [];
      // this.form.origin = "";
      var temp = {
        user_id: this.form.account, // 用户名
        password: this.form.password,
        user_name: this.form.nickname, // 昵称
        system_name: this.form.type >= 2 ? this.form.systemname : "", //系统名称
        phone: this.form.phone + "", // 电话号
        email: this.form.email, // 邮箱
        department_id: this.form.type >= 2 ? this.form.origin : "", // 组织id
        is_admin: this.form.type,
        state: this.form.able, // 用户状态，1——启用，0 禁用
        domain_name: this.form.type >= 3 ? this.form.domain : "", //
        ip_whitelist: this.form.type >= 3 ? this.form.ip : [], //
        description: this.form.desc, //描述
        link_man: this.form.contact,
      };
      this.$http
        .post(`/apaas/backmgt/user/add`, temp)
        .then((response) => {
          console.log(response);
          if (response.data.success) {
            this.backPage();
            this.$message.success("新增成功");
          } else {
            this.$message.error(response.data.errMsg);
          }
        })
        .catch((response) => {
          this.$message.error(response.data.errMsg);
        });
    },
    set_user() {
      var temp = {
        user_id: this.form.account, // 用户名
        user_name: this.form.nickname, // 昵称
        system_name: this.form.type >= 2 ? this.form.systemname : "", //系统名称
        phone: this.form.phone + "", // 电话号
        email: this.form.email, // 邮箱
        department_id: this.form.type >= 2 ? this.form.origin : "", // 组织id
        is_admin: this.form.type,
        state: this.form.able, // 用户状态，1——启用，0 禁用
        domain_name: this.form.type >= 3 ? this.form.domain : "", //
        ip_whitelist:
          this.form.type >= 3
            ? this.form.ip && this.form.ip.length
              ? this.form.ip
              : []
            : [], //
        description: this.form.desc, //描述
        link_man: this.form.contact,
      };
      this.$http
        .put(`/apaas/backmgt/user/put`, temp)
        .then((response) => {
          if (response.data.success) {
            this.backPage();
            this.$message.success("修改成功");
          } else {
            this.$message.error(response.data.errMsg);
          }
        })
        .catch((response) => {
          this.$message.error(response.data.errMsg);
        });
    },
    check_user() {
      return this.$http.get(
        `/apaas/backmgt/user/checkUserId?user_id=${this.form.account}`
      );
    },
    onSubmit(formName) {
      console.log("submit!");
      this.$refs[formName].validate((valid, err) => {
        if (valid) {
          if (this.edit_flag == 0) {
            this.check_user().then((res) => {
              console.log(res);
              if (res.data.success) {
                this.add_user();
              } else {
                this.$message.error(res.data.errMsg);
              }
            });
          } else {
            this.set_user();
          }
        } else {
          console.log(err);
          console.log("error submit!!");
          return false;
        }
      });
    },
    check_account() {},
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.form = {
        ...this.form,
        ...this.baseinfo,
      };
    },
    get_now_user() {
      this.$api.user.getNowUser().then(({ data }) => {
        if (data.success == 1) {
          this.baseinfo = {
            person: data.data.user_id,
            date: formatDateTime_date(new Date()),
          };
          this.form = {
            ...this.form,
            ...this.baseinfo,
          };
        } else {
          console.log(data.errMsg);
        }
      });
    },
  },
};
</script>

<style>
.info_contain .el-input__inner {
  background-color: #f7f8f9;
  width: 1022px;
}
.info_contain .shortpass .el-input__inner {
  background-color: #f7f8f9;
  width: 888px;
}
.info_contain .shortpass .el-input {
  width: 888px;
}
.info_contain .el-textarea__inner {
  background-color: #f7f8f9;
  width: 1022px;
}
.limitsd .timeslect .el-input__inner {
  width: 150px;
  border-radius: 0 8px 8px 0;
  background-color: rgba(15, 38, 131, 1);
  color: rgba(248, 249, 253, 1);
  border: 0;
}
.info_contain .el-input.is-disabled .el-input__inner {
  background-color: #e3e4e6;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.info_contain .input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.info_contain .input-new-tag .el-input__inner {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>

<style scoped>
.detail_contain {
  width: 100%;
  padding: 0 20px;
  height: calc(100% - 55px);
}
.info_contain {
  padding: 25px 20px;
  background-color: #fff;
  width: 100%;
  box-shadow: 0px 3px 6px 0px #f4f7fc;
  border-radius: 12px;
  min-height: calc(100% - 20px);
  margin-bottom: 20px;
  position: relative;
}
.now_page_title {
  margin: 15px 0;
  color: #898d9e;
}
.now_page_title span {
  color: #242c43;
}
.formname {
  color: #58617a;
}
.right {
  float: right;
  margin-left: 20px;
}
.left {
  float: left;
}
.removepic {
  display: inline-block;
  margin-top: -40px;
  float: left;
  margin-left: 180px;
  width: 76px;
  height: 32px;
  background-color: #495feb;
  border-radius: 8px;
  line-height: 32px;
  text-align: center;
  color: #e6ebfe;
  cursor: pointer;
}
.edit_change {
  width: 100%;
  border-bottom: 2px solid #f4f7fc;
  overflow: hidden;
}
.edit_change_box {
  width: 163px;
  height: 48px;
  line-height: 48px;
  background-color: #e3e5ef;
  border-radius: 8px;
  color: #8890a7;
  text-align: center;
  float: left;
  margin-right: 20px;
  font-weight: 600;
  margin-bottom: 25px;
  font-size: 16px;
  cursor: pointer;
}
.edit_change_box img {
  vertical-align: -3px;
  margin-right: 5px;
}
.safe_title {
  width: 100%;
  height: 65px;
  line-height: 65px;
  border-bottom: 2px solid #f4f7fc;
}
.safe_select {
  float: left;
  width: auto;
  margin-right: 40px;
  height: 65px;
  cursor: pointer;
}
.safe_box_select {
  padding: 30px 10px 10px 10px;
  width: 100%;
  height: 100%;
}
.openbgc {
  width: 56px;
  height: 23px;
  background-image: url("~@/assets/imgs/btn_on_hov.png");
  background-size: contain;
  cursor: pointer;
}
.formtitle {
  color: #58617a;
  margin: 15px 0;
}

.savebtn {
  position: absolute;
  right: 20px;
  bottom: 20px;
  width: 278px;
  overflow: hidden;
}
.btnsty {
  width: 124px;
  height: 44px;
  line-height: 44px;
  background-color: rgba(195, 202, 248, 0.5);
  border-radius: 8px;
  color: rgba(15, 38, 131, 1);
  text-align: center;
  float: left;
  margin-right: 30px;
  cursor: pointer;
}
.savebtn .btnsty:nth-last-of-type(1) {
  margin-right: 0px;
  background-color: rgba(15, 38, 131, 1);
  color: rgba(248, 249, 253, 1);
}
.limitsd {
  position: relative;
  width: 1022px;
}
.limitsd .timeslect {
  position: absolute;
  right: 0;
}
.fixpass {
  width: 124px;
  height: 44px;
  line-height: 44px;
  text-align: center;
  font-size: 16px;
  color: #fff;
  background-color: #495feb;
  border-radius: 8px;
  display: inline-block;
  margin-left: 5px;
  cursor: pointer;
}
</style>
