<template>
  <el-dialog class="dialog"
             :visible.sync="dialogVisible"
             center
             :title="data?'编辑':'添加'"
             append-to-body
             :before-close="onBeforeClose"
             @close="onClose"
             width="600px">
    <el-form label-width="120px" ref="dataForm" :model="dataForm" :rules="dataRules">
      <!-- 普通输入-->
      <el-form-item label="姓名：" prop="username">
        <el-input class="input-width" v-model="dataForm.username"></el-input>
      </el-form-item>

      <!-- 上传图片 -->
      <el-form-item label="头像：" prop="avatar">
        <upload v-model="dataForm.avatar" :width="160" :height="160" tips="上传图片" accept="image/jpeg,image/gif,image/png"></upload>
      </el-form-item>

      <!-- 单选按钮 -->
      <el-form-item label="性别：" prop="gender">
        <el-radio-group v-model="dataForm.gender">
          <el-radio v-for="item in genderList" :key="item.id" :label="item.id">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 日期、动态条件校验； checkbox值为1、2 -->
      <el-form-item label="生日：" prop="birthday" :rules="[{validator: validateNotEmpty, errorMessage: '生日不能为空', required: Number(dataForm.birthdayRemind)===1}]">
        <el-date-picker v-model="dataForm.birthday" class="input-width" type="date" placeholder="请选择生日"></el-date-picker>
        <checkbox v-model="dataForm.birthdayRemind" label="开启生日提醒" class="ml20"></checkbox>
      </el-form-item>

      <!-- 下拉、单选 -->
      <el-form-item label="民族：" prop="ethnic">
        <el-select v-model="dataForm.ethnic" class="input-width" filterable value-key="id" placeholder="请选择民族">
          <el-option
              v-for="item in ethnicList"
              :key="item.id"
              :label="item.name"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>

      <!-- 整数输入-->
      <el-form-item label="身高：" prop="height">
        <el-input class="input-width" 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" :key="item.id" :label="item.id">{{ item.label }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 文本域 textarea-->
      <el-form-item label="个人简介：" prop="brief">
        <el-input v-model="dataForm.brief"
                  style="width: 400px"
                  type="textarea"
                  maxlength="200"
                  show-word-limit
                  :autosize="{ minRows: 4}"></el-input>
      </el-form-item>

      <!-- 自动补全-->
      <!--      <el-form-item label="民族：" prop="ethnic">-->
      <!--        <el-autocomplete-->
      <!--            class="input-width"-->
      <!--            v-model="dataForm.ethnic"-->
      <!--            :fetch-suggestions="queryEthnic"-->
      <!--            placeholder="请输入民族"-->
      <!--            :trigger-on-focus="true"-->
      <!--            @change="onUserChange"-->
      <!--            @select="onUserSelect">-->
      <!--        </el-autocomplete>-->
      <!--      </el-form-item>-->

      <!-- 下拉、多选-->

      <!-- 下拉、远程搜索、单选-->
      <!--      <el-form-item label="民族：" prop="ethnic">-->
      <!--        <el-select-->
      <!--            v-model="dataForm.executors"-->
      <!--            filterable-->
      <!--            remote-->
      <!--            multiple-->
      <!--            value-key="ethnicId"-->
      <!--            placeholder="请输入民族"-->
      <!--            :remote-method="remoteMethod">-->
      <!--          <el-option-->
      <!--              v-for="item in ethnicList"-->
      <!--              :key="item.ethnicId"-->
      <!--              :label="item.ethnicName"-->
      <!--              :value="item">-->
      <!--          </el-option>-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->


      <!-- 循环动态校验 -->
      <el-form-item label="经历：" prop="type">
        <!--        <el-select v-model="dataForm.gender" class="input-width">-->
        <!--          <el-option label="男" :value="1"></el-option>-->
        <!--          <el-option label="女" :value="2"></el-option>-->
        <!--        </el-select>-->
      </el-form-item>


      <!--完善用户、前端日志、表格、移动端整合 TODO-->

    </el-form>

    <div slot="footer">
      <el-button type="primary" @click="onConfirm">确 认</el-button>
      <el-button @click="onCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";
import Checkbox from "@/components/Checkbox";
import Upload from "@/components/Upload";


export default {
  name: "dialogEdit",
  components: {Checkbox, Upload},
  props: {
    visible: {
      type: Boolean
    },
    data: {
      type: Object
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  data() {
    return {
      userName: undefined, // 用户名

      dataForm: {
        username: undefined, // 用户名
        avatar: undefined, // 头像
        gender: undefined, //性别
        birthday: undefined, // 生日
        birthdayRemind: 2, // 开启生日提醒 1是、2否
        ethnic: undefined, // 民族
        brief: undefined, // 简介
        hobby: [], // 兴趣、爱好
        height: undefined, // 身高
        skill: ["Java", "小程序"],
      },

      dataRules: {
        username: [{validator: validateNotEmpty, errorMessage: "用户名不能为空", required: true, trigger: 'blur'}],
        avatar: [{validator: validateNotEmpty, errorMessage: "用户头像不能为空", required: true, trigger: 'change'}],
        gender: [{validator: validateNotEmpty, errorMessage: "性别不能为空", required: true, trigger: 'change'}],
        ethnic: [{validator: validateNotEmpty, errorMessage: "民族不能为空", required: true, trigger: 'blur'}],
        brief: [{validator: validateNotEmpty, errorMessage: "个人简介不能为空", required: true, trigger: 'blur'}],
        userId: [{validator: validateNotEmpty, errorMessage: "用户不能为空，且需要选择已存在的用户", required: true, trigger: 'empty'}],
      },

      genderList: [{id: 1, label: "男"}, {id: 2, label: "女"}],
      hobbyList: [{id: 1, label: "看电影"}, {id: 2, label: "听音乐"}, {id: 3, label: "篮球"}, {id: 4, label: "羽毛球"}],
      ethnicList: [{id: 1, name: "汉族"}, {id: 2, name: "朝鲜族"}],

      skillList: [{name: 'Java', value: 1}, {name: 'C', value: 2}, {name: 'Web', value: 3},
        {name: '小程序', value: 4}, {name: 'Android', value: 5}, {name: '服务器', value: 6}],

      whetherList: [{id: "1", label: "是"}, {id: "2", label: "否"}],

      imageList: [
        "http://www.forestry.gov.cn/uploadfile/main/2013-6/image/2013-6-19-dbdb3e3f20b644ec959960e9d8308eda.jpg",
        "http://hbimg.b0.upaiyun.com/c9f62254a4a9651171d03c20872f8f745d6da05e1896e-XwHiqQ_fw658xxx",
        "http://hbimg.b0.upaiyun.com/90e6064710e188fa0b2002b81bd0b5843c2d820d37095-FZyRsE_fw658",
        "http://gss0.baidu.com/-vo3dSag_xI4khGko9WTAnF6hhy/zhidao/pic/item/9922720e0cf3d7ca3ec2f03ff01fbe096b63a947.jpg"
      ]
    }
  },

  mounted() {
    this.initData();
    if (this.data) {
      this.dataForm = {...this.data};
    }
  },

  methods: {
    validateNotEmpty,

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

    // 取消
    onCancel() {
      this.dialogVisible = false;
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.data) { // 更新
            this.$axios.put("/data/update", this.dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$emit("update");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post("/data/add", this.dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$emit("add");
              this.onCancel();
            });
          }
        }
      });
    },

    // 关闭前确认
    onBeforeClose(done) {
      if (this.$store.state.app.closeConfirmEnable) {
        this.$confirm("确认关闭？").then(() => done());
      } else {
        done();
      }
    },

    // 关闭
    onClose() {
      this.$emit("close");
    },

    // 根据名称搜索用户
    queryEthnic(keyword, cb) {
      this.$axios.get("/user/search", {params: {keywords: keyword}}).then((data) => {
        const list = data.map(item => {
          return {
            value: item.name, // 用于显示
            id: item.id,
          }
        });
        cb(list);
      })
    },

    onUserChange() {
      this.userId = undefined;
    },

    onUserSelect(user) {
      this.userName = user.value;
      this.dataForm.userId = user.id;
    },

    // 远程搜索民族
    remoteMethod(query) {
      if (query) {
        this.$axios.get("/auth/sysuser/list", {params: {keyword: query}}).then((data) => {
          this.ethnicist = data.list.map(item => {
            return {
              ethnicId: item.id,
              ethnicName: item.name
            }
          });
        })
      }
    }
  }
}
</script>

<style scoped lang="scss">
.input-width {
  width: 200px;
}

.image {
  height: 80px;
  margin-right: 14px;

  ::v-deep.image-slot {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    font-size: 40px;
  }
}
</style>
