<template>
  <div class="app-container">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form label-width="140px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <el-form-item label="姓名：" prop="username">
        <el-input v-model.trim="dataForm.username" placeholder="请输入姓名" class="input-width" minlength="2" maxlength="20" clearable></el-input>
      </el-form-item>

      <el-form-item v-if="!id" label="密码：" prop="password">
        <el-input v-model.trim="dataForm.password" placeholder="请输入密码" class="input-width" minlength="8" maxlength="20" clearable></el-input>
      </el-form-item>

      <el-form-item label="角色：" prop="roles">
        <el-select multiple v-model="dataForm.roles" placeholder="请选择角色" class="input-width" clearable>
          <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="avatar" class="h50">
        <upload v-model="dataForm.avatar" :width="60" :height="60" tips="上传图片" stsUrl="/v1/file/sts" accept="image/jpeg,image/gif,image/png"></upload>
      </el-form-item>

      <el-form-item label="地区：" prop="region" class="h50">
        <el-cascader
            class="input-width"
            v-model="dataForm.region"
            placeholder="请选择地区"
            :options="cityTree"
            filterable
            clearable
            :filter-method="regionFilter"
            :props="{ label:'name', value:'name', expandTrigger: 'hover' }">
          <template slot-scope="{ node, data }">
            <span>{{ data.name }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>

      <el-form-item label="昵称：" prop="nickname">
        <el-input v-model.trim="dataForm.nickname" placeholder="请输入昵称" class="input-width" clearable></el-input>
      </el-form-item>

      <el-form-item label="性别：" prop="gender">
        <el-select v-model="dataForm.gender" placeholder="请选择性别" class="input-width" clearable>
          <el-option v-for="item in genderList" :value="item.id" :key="item.id" :label="item.label"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="生日：" prop="birthday" :rules="[{validator: validateNotEmpty, errorMessage: '生日不能为空', required: dataForm.birthdayRemind}]">
        <el-date-picker :default-value="new Date(new Date().getFullYear()-15,new Date().getMonth())" v-model="dataForm.birthday" placeholder="请选择生日" value-format="timestamp" class="input-width" type="date"></el-date-picker>
        <el-checkbox v-model="dataForm.birthdayRemind" label="开启生日提醒" class="ml20"></el-checkbox>
      </el-form-item>

      <el-form-item label="民族：" prop="ethnic">
        <el-select v-model="dataForm.ethnic" placeholder="请输入民族" :remote-method="queryEthnic" filterable remote>
          <el-option
              v-for="item in ethnicList"
              :key="item"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="身高：" prop="height">
        <el-input class="input-width" placeholder="请输入身高" v-model.trim="dataForm.height" maxlength="3" oninput="value=value.replace(/[^\d]/g,'')">
          <template slot="append">cm</template>
        </el-input>
      </el-form-item>

      <el-form-item label="兴趣、爱好：" prop="hobby">
        <el-checkbox-group v-model="dataForm.hobby">
          <el-checkbox v-for="item in hobbyList" :label="item" :key="item">{{ item }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="简介：" prop="brief">
        <el-input v-model.trim="dataForm.brief" class="input-width" type="textarea" maxlength="1000" :autosize="{ minRows: 2}" show-word-limit></el-input>
      </el-form-item>

      <el-form-item
          v-for="(experience, index) in dataForm.experience"
          :key="index"
          :label="`经历`+(index+1)+`：`"
          :prop="'experience.'+index"
          :rules="{ required: index!==dataForm.experience.length-1, validator: validateStrNotEmpty, message: '经历不能为空', trigger: 'blur'}">
        <div class="flex align-center">
          <el-input v-model.trim="dataForm.experience[index]" class="input-width" type="textarea" :autosize="{ minRows: 1}" show-word-limit></el-input>
          <el-link v-if="index===dataForm.experience.length-1" type="primary" @click.prevent="addExperience" icon="el-icon-plus"  class="ml10">添加</el-link>
          <el-link v-else type="danger" @click.prevent="removeExperience(experience)" icon="el-icon-delete"  class="ml10">删除</el-link>
        </div>
      </el-form-item>
    </el-form>

    <page-footer showConfirm @confirm="onConfirm" @cancel="onCancel" width="800px"></page-footer>
  </div>
</template>

<script>

import {validateNotEmpty, validatePasswordReg, validateUsername} from "@/utils/validate";
import Upload from "@/components/Upload";

export default {
  name: "SystemUserEdit",
  components: {Upload},
  watch: {},

  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 用户id
        username: undefined, // 用户名
        roles: [], // 用户角色
        nickname: undefined, // 昵称
        password: undefined, // 登录密码
        avatar: undefined, // 头像
        region: undefined, // 地区
        province: undefined, // 省
        city: undefined, // 市
        area: undefined, // 区
        gender: undefined, // 性别 1:男 2:女
        birthday: undefined, // 生日
        birthdayRemind: undefined, // 生日提醒
        ethnic: undefined, // 民族
        height: undefined, // 身高
        hobby: [], // 兴趣、爱好 数组
        brief: undefined, // 个人简介 数组
        experience: [''], // 经历
      },

      dataRules: {
        'username': [{validator: validateUsername, length: 2, required: true, trigger: 'blur'}],
        'password': [{validator: validatePasswordReg, length: 6, required: true, trigger: 'blur'}],
        'roles': [{validator: validateNotEmpty, errorMessage: "角色不能为空", required: true, trigger: 'change'}],
        'ethnic': [{validator: validateNotEmpty, errorMessage: "民族不能为空", required: true, trigger: 'change'}],
        'brief': [{validator: validateNotEmpty, errorMessage: "个人简介不能为空", required: true, trigger: 'change'}],
      },

      roles: undefined, // 角色列表
      ethnicList: undefined, // 民族列表
      cityTree: undefined, // 城市数据
      genderList: [{id: 0, label: "保密"}, {id: 1, label: "男"}, {id: 2, label: "女"}],
      hobbyList: ["看电影", "听音乐", "篮球", "羽毛球"],
    }
  },

  mounted() {
    this.initData();
    if (this.id) {
      this.getDetail(this.id);
    }
  },

  methods: {
    validateNotEmpty,
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      // 加载角色列表
      this.$axios.get("/v1/system/user/list/role", undefined, false).then(data => {
        this.roles = data;
      });
      // 加载地区列表
      this.$axios.get("/v1/system/region/tree", undefined, false).then((data) => {
        // 去除叶子节点的空子节点
        this.cityTree = JSON.parse(JSON.stringify(data).replace(/"children":\[]/g, "\"no\":0"))[0].children;
      })
    },

    // 取消
    onCancel() {
      this.$router.back();
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          let dataForm = JSON.parse(JSON.stringify(this.dataForm));
          dataForm.hobby = dataForm.hobby.join(',');
          dataForm.province = dataForm.region[0];
          dataForm.city = dataForm.region[1];
          dataForm.area = dataForm.region[2];
          dataForm.experience = dataForm.experience.filter(item => item.trim() !== '').join(',');
          if (this.id) { // 更新
            this.$axios.put("/v1/system/user/update", dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("SystemUserUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post("/v1/system/user/add", dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("SystemUserAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(userId) {
      this.$axios.get(`/v1/system/user/query/${userId}`).then(data => {
        data.hobby = data.hobby.split(',').filter(item => item !== '');
        data.region = data.area || data.city || data.province;
        data.experience = data.experience.split(',').filter(item => item.trim() !== '');
        // 添加默认经历输入框
        if (!data.experience.length) {
          data.experience = [''];
        }
        data.roles = data.roles.map(item => item.id);
        this.dataForm = data;
      });
    },

    // 民族搜索
    queryEthnic(query) {
      if (query && query.trim().length) {
        this.$axios.get("/v1/system/ethnic/list", {params: {name: query, size: 56, order: '+id'}}, false).then((data) => {
          this.ethnicList = data.list.map(item => item.name);
        })
      }
    },

    regionFilter(node, keyword) {
      if (!!~node.text.indexOf(keyword) || !!~node.text.toUpperCase().indexOf(keyword.toUpperCase())) {
        return true
      }

      node.data.keyword = keyword.replaceAll(' ', '').toLowerCase();
      let array = [];
      this.getPinyin(node, array);
      for (let i = 0; i < array.length; i++) {
        // if(this.havePinyin(node.data.keyword , array[i])){
        if (array[i].search(node.data.keyword) >= 0) {
          return true;
        }
      }

      let name = array.reverse().join('').replaceAll(' ', '');
      return name.search(node.data.keyword) >= 0;

    },

    havePinyin(keyword, pinyin) {
      let j = 0;
      for (let i = 0; i < keyword.length; i++) {
        let result = false;
        for (; j < pinyin.length; j++) {
          if (keyword[i] === pinyin[j]) {
            result = true;
            j++;
            break;
          }
        }
        if (!result) {
          return false;
        }
      }
      return true;
    },

    getPinyin(node, array) {
      array.push(node.data.pinyinShort.toLowerCase());
      if (node.parent) {
        this.getPinyin(node.parent, array)
      }
    },

    // 新增经历
    addExperience() {
      this.dataForm.experience.push('');
    },

    // 删除经历
    removeExperience(experience) {
      this.dataForm.experience.remove(experience);
      this.$refs['dataForm'].clearValidate('experience.' + (this.dataForm.experience.length - 1));
    }
  },

}
</script>

<style scoped lang="scss">
.app-container {
  .input-width {
    width: 500px;
  }
}
</style>
