<template>
  <el-dialog
    :title="!dataForm.userId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="600px">
    <el-form 
      :model="dataForm" 
      :rules="dataRule" 
      ref="dataForm" 
      @keyup.enter.native="dataFormSubmit()" 
      label-width="80px" 
      size="mini"
      style="margin-left: 20px;width: 500px">
      <el-form-item label="姓名" prop="username">
        <el-input v-model="dataForm.username"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select 
          v-model="dataForm.sex"
          style="width: 100%">
          <el-option
            v-for="item in gender"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="出生日期" prop="birthday">
        <el-date-picker
          v-model="dataForm.birthday"
          type="date" 
          value-format="yyyy-MM-dd" 
          placeholder="选择建立日期"
          style="width: 100%">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="dataForm.mobile"></el-input>
      </el-form-item>
      <el-form-item v-if="!dataForm.userId" label="密码" prop="password">
        <el-input v-model="dataForm.password"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="dataForm.email"></el-input>
      </el-form-item>
      <el-form-item label="牧场" prop="farmId">
        <el-select 
          v-model="dataForm.farmId"
          style="width: 100%">
          <el-option
            v-for="(item, index) in pastures"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="departmentCode">
        <el-select 
          v-model="dataForm.departmentCode"
          style="width: 100%">
          <el-option
            v-for="(item, index) in departments"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="jobCode">
        <el-select 
          v-model="dataForm.jobCode"
          style="width: 100%">
          <el-option
            v-for="(item, index) in jobs"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleIdList">
        <el-checkbox-group v-model="dataForm.roleIdList">
          <el-checkbox v-for="(role, index) in roleList" :key="index" :label="role.roleId">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="0">禁用</el-radio>
          <el-radio :label="1">正常</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="住址" prop="address">
        <el-input v-model="dataForm.address"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input v-model="dataForm.remarks"></el-input>
      </el-form-item>
      <!-- <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="dataForm.roleName" placeholder="角色名称"></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="dataForm.remark" placeholder="备注"></el-input>
      </el-form-item>
      <el-form-item size="mini" label="授权">
        <el-tree
          :data="menuList"
          :props="menuListTreeProps"
          node-key="menuId"
          ref="menuListTree"
          :default-expand-all="true"
          show-checkbox>
        </el-tree>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="visible = false">关闭</el-button>
      <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // import { treeDataTranslate } from '@/utils'
  import { isEmail, isMobile } from '@/utils/validate'
  export default {
    data () {
      var validateEmail = (rule, value, callback) => {
        // if (!isEmail(value)) {
        //   callback(new Error('邮箱格式错误'))
        // } else {
        //   callback()
        // }
        if (value === '') {
          callback()
        } else if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        // menuList: [],
        // menuListTreeProps: {
        //   label: 'name',
        //   children: 'children'
        // },
        dataForm: {
          userId: 0,
          password: '',
          username: '',
          sex: '',
          birthday: '',
          mobile: '',
          email: '',
          farmId: '',
          departmentCode: '',
          jobCode: '',
          address: '',
          remarks: '',
          roleIdList: [],
          status: 1
        },
        dataRule: {
          username: [
            { required: true, message: '姓名不能为空', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            { min: 1, max: 20, message: '长度在 1 到 20 个字符之间', trigger: ['blur', 'change'] }
          ],
          sex: [
            { required: true, message: '性别不能为空', trigger: 'blur' }
          ],
          birthday: [
            // { required: true, message: '出生日期不能为空', trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '手机号码不能为空', trigger: 'blur' },
            { validator: validateMobile, trigger: 'blur' }
          ],
          email: [
            // { required: true, message: '邮箱不能为空', trigger: 'blur' },
            { validator: validateEmail, trigger: 'blur' }
          ],
          farmId: [
            // { required: true, message: '牧场不能为空', trigger: 'blur' }
          ],
          departmentCode: [
            // { required: true, message: '部门不能为空', trigger: 'blur' }
          ],
          jobCode: [
            // { required: true, message: '岗位不能为空', trigger: 'blur' }
          ],
          address: [
            // { required: true, message: '住址不能为空', trigger: 'blur' }
          ],
          roleIdList: [
            // { required: true, message: '角色不能为空', trigger: 'blur' }
          ],
          status: [
            // { required: true, message: '状态不能为空', trigger: 'blur' }
          ]
        },
        tempKey: -666666, // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
        gender: [
          {
            value: 1,
            label: '男'
          },
          {
            value: 2,
            label: '女'
          }
        ],
        pastures: [], // 牧场select
        departments: [], // 部门select
        jobs: [], // 岗位select
        roleList: []
      }
    },
    methods: {
      // resetForm () {
      //   this.dataForm.username = ''
      //   this.dataForm.sex = ''
      //   this.dataForm.birthday = ''
      //   this.dataForm.mobile = ''
      //   this.dataForm.email = ''
      //   this.dataForm.farmId = ''
      //   this.dataForm.departmentCode = ''
      //   this.dataForm.jobCode = ''
      //   this.dataForm.address = ''
      //   this.dataForm.remarks = ''
      //   this.dataForm.roleIdList = []
      //   this.dataForm.status = ''
      // },
      init (userId) {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
        // 在role.vue调用该方法
        this.dataForm.userId = userId || undefined
        this.$http({
          url: this.$http.adornUrl("/management/farm/findAll"),
          method: "post"
        }).then(async({ data }) => {
          // 牧场select
          data.all.forEach(pasture => {
            let item = {
              value: pasture.id,
              label: pasture.name
            }
            this.pastures.push(item)
          })
          // 部门select
          let departments = []
          let departmentR = await this.$http({
            url: this.$http.adornUrl("/sys/department/findAll"),
            method: "get"
          })
          departmentR.data.departmentList && (departments = departmentR.data.departmentList)
          departments.forEach(department => {
            let item = {
              value: department.departmentCode,
              label: department.departmentName
            }
            this.departments.push(item)
          })
          // 岗位select
          let jobs = []
          let jobR = await this.$http({
            url: this.$http.adornUrl("/sys/job/findAll"),
            method: "get"
          })
          jobR.data.jobList && (jobs = jobR.data.jobList)
          jobs.forEach(job => {
            let item = {
              value: job.jobCode,
              label: job.jobName
            }
            this.jobs.push(item)
          })
          // 获取status
          let roleR = await this.$http({
            url: this.$http.adornUrl('/sys/role/select'),
            method: 'get',
            params: this.$http.adornParams()
          })
          this.roleList = roleR.data && roleR.data.code === 0 ? roleR.data.list : []
          // 获取form的修改的东西
          if (!this.dataForm.userId) {
            return;
          }
          let formR = await this.$http({
            url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.userId}`),
            method: 'get',
            params: this.$http.adornParams()
          })
          // 修改操作：form表单完整
          console.log(formR.data.user);
          this.dataForm.username = formR.data.user.username
          this.dataForm.sex = formR.data.user.sex
          this.dataForm.birthday = formR.data.user.birthday
          this.dataForm.mobile = formR.data.user.mobile
          this.dataForm.email = formR.data.user.email
          this.dataForm.farmId = formR.data.user.farmId
          this.dataForm.departmentCode = formR.data.user.departmentCode
          this.dataForm.jobCode = formR.data.user.jobCode
          this.dataForm.address = formR.data.user.address
          this.dataForm.remarks = formR.data.user.remarks
          this.dataForm.roleIdList = formR.data.user.roleIdList
          this.dataForm.status = formR.data.user.status
          // this.

          // if (this.dataForm.id) {
          //   this.$http({
          //     url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
          //     method: 'get',
          //     params: this.$http.adornParams()
          //   }).then(({data}) => {
          //     if (data && data.code === 0) {
          //       // this.dataForm.roleName = data.role.roleName
          //       // this.dataForm.remark = data.role.remark
          //       // var idx = data.role.menuIdList.indexOf(this.tempKey)
          //       // if (idx !== -1) {
          //       //   data.role.menuIdList.splice(idx, data.role.menuIdList.length - idx)
          //       // }
          //       // this.$refs.menuListTree.setCheckedKeys(data.role.menuIdList)
          //       console.log(data);
          //     }
          //   })
          // }
        })
        // this.$http({
        //   url: this.$http.adornUrl('/sys/menu/list'),
        //   method: 'get',
        //   params: this.$http.adornParams()
        // }).then(({data}) => {
        //   this.menuList = treeDataTranslate(data, 'menuId')
        // }).then(() => {
        //   this.visible = true
        //   this.$nextTick(() => {
        //     this.$refs['dataForm'].resetFields()
        //     this.$refs.menuListTree.setCheckedKeys([])
        //   })
        // }).then(() => {
        //   if (this.dataForm.id) {
        //     this.$http({
        //       url: this.$http.adornUrl(`/sys/role/info/${this.dataForm.id}`),
        //       method: 'get',
        //       params: this.$http.adornParams()
        //     }).then(({data}) => {
        //       if (data && data.code === 0) {
        //         this.dataForm.roleName = data.role.roleName
        //         this.dataForm.remark = data.role.remark
        //         var idx = data.role.menuIdList.indexOf(this.tempKey)
        //         if (idx !== -1) {
        //           data.role.menuIdList.splice(idx, data.role.menuIdList.length - idx)
        //         }
        //         this.$refs.menuListTree.setCheckedKeys(data.role.menuIdList)
        //       }
        //     })
        //   }
        // })
      },
      // 表单提交
      dataFormSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          console.log(valid);
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/sys/user/${!this.dataForm.userId ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'userId': this.dataForm.userId || undefined,
                'username': this.dataForm.username,
                'password': this.dataForm.password,
                'sex': this.dataForm.sex,
                'birthday': this.dataForm.birthday,
                'mobile': this.dataForm.mobile,
                'email': this.dataForm.email,
                'farmId': this.dataForm.farmId,
                'departmentCode': this.dataForm.departmentCode,
                'jobCode': this.dataForm.jobCode,
                'roleIdList': this.dataForm.roleIdList,
                'status': this.dataForm.status,
                'address': this.dataForm.address,
                'remarks': this.dataForm.remarks
                // 'remark': this.dataForm.remark,
                // 'menuIdList': [].concat(this.$refs.menuListTree.getCheckedKeys(), [this.tempKey], this.$refs.menuListTree.getHalfCheckedKeys())
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.visible = false
                this.$emit('refreshDataList')
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  // onClose: () => {
                  //   this.visible = false
                  //   this.$emit('refreshDataList')
                  // }
                })
                // this.resetForm()
                this.visible = false
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
