<template>
  <div style="width:100%;min-height:40vh;padding:10px 23px; z-index:10;background: rgba(0, 9, 34, 0.6);">
    <el-form ref="form" size="mini" :model="addForm" :rules="rules" label-width="120px">
      <el-form-item label="人员姓名: " prop="name">
        <el-input v-model="addForm.name" style="width:100%;"></el-input>
      </el-form-item>

      <el-form-item label="账号/手机号: " prop="account">
        <el-input v-model="addForm.account" style="width:100%;"></el-input>
      </el-form-item>

      <!-- <el-form-item label="单位名称: " prop="unitName">
        <el-input v-model="addForm.unitName" style="width:300px ;"></el-input>
      </el-form-item> -->

      <el-form-item label="人员性别: " prop="sex">
        <el-radio-group v-model="addForm.sex">
          <el-radio :label="0">男</el-radio>
          <el-radio :label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item label="角色: " prop="userRole">
        <el-radio-group v-model="addForm.userRole">
          <el-radio :label="2">护林员</el-radio>
          <el-radio :label="1">管理员</el-radio>
        </el-radio-group>
      </el-form-item> -->


      <el-form-item :label="'所属机构'">
        <treeselect :options="orgsTree" :default-expand-level="3" :multiple="true" :flat="true" :open-on-click="true"
          :open-on-focus="true" :clear-on-select="true" v-model="selectOrgs" style="z-index: 2026;">
        </treeselect>
      </el-form-item>

      <el-form-item label="打卡时间" prop="time">
        <p v-for="(item,index) in timeslot" :key="index" style="position:relative;">
        <el-time-picker
            is-range
            v-model="timeslot[index]"
            range-separator="-"
            value-format="HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            style="width:100%;margin-bottom:5px;"
            size="mini"
            @change="timeslotChange"
            >
        </el-time-picker>
        <i class="el-icon el-icon-circle-close remove-timesolt" @click="remvoeTime(index)"></i>
        </p>
        <el-button type="primary" round icon="el-icon-plus" @click="addTimeSlot">添加打卡时间</el-button>
      </el-form-item>


      <el-form-item style="margin-top: 0px;">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="submitForm('form')" v-if="detailInfo.length == 0">保存</el-button>
        <el-button type="primary" @click="createForm('form')" v-else>编辑</el-button>
      </el-form-item>

    </el-form>
  </div>
</template>
<script>
  import { encode } from '../../../../utils/base64';
  import { listToTreeSelect } from '@/utils'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import { postMethodCommon, getMethodCommon } from '../../../../api/common';
  import { validateMobile, validID, validateStock } from './validate.js'
  import form from '../../../../store/modules/form';
  let BASE_IMAGE_URL = process.env.VUE_APP_BASE_IMG_URL;
  // let BASE_IMAGE_URL = BASE_IMAGE_API_URL;
  export default {
    name: "AddForm",
    props: ['detailInfo'],
    components: {
      Treeselect,
    },
    data() {
      return {
        BASE_IMAGE_URL: BASE_IMAGE_URL,
        addForm: {
          userRole:2,
          password:null,
          identity:0,
          unitName:null,
          timeSlot:[],
        },
        rules: {
          name: [
            { required: true, message: '姓名不能为空', trigger: 'blur' },
          ],
          phone: [
            { required: true, message: '电话不能为空', trigger: 'blur' },
            { validator: validateMobile.bind(this), trigger: 'blur' }
          ],
          gender: [
            { required: true, message: '性别不能为空', trigger: 'blur' },
          ],
        },
        dialogFormVisible: false,
        orgsTree: [], // 用户可访问到的所有机构组成的树
        selectRoles: [], // 用户分配的角色
        selectRoleNames: '',
        timeslot:[],
      }
    },
    created() {
      if (this.detailInfo.length == 1) {
        // this.addForm = this.detailInfo[0];
        this.getDetail()
      } else {
        
      }
    },
    computed: {
      selectOrgs: {
        get: function () {
          if (this.detailInfo.length == 1) {
            return this.addForm.areaId
          } else {
            return []
          }
        },
        set: function (v) {
          var _this = this
          _this.addForm.areaId = v
        }
      }
    },
    mounted() {
      let _this = this;
      var querys = {
        regionName: localStorage.getItem("areaENName")
      }
      getMethodCommon("/Grid/LoadAllGrid", querys).then(res => {
        console.log("data", res.data);
        if (res.code == 200) {
          var list = res.data
          var arr = this.traverse(list)
          console.log("orgssssss",arr)
          _this.orgsTree = arr;
        }
      })
    },
    methods: {
      timeslotChange(e){
        console.log(e);
      },
      remvoeTime(index){
        this.timeslot.splice(index,1);
      },
      addTimeSlot(){
        this.timeslot.push(["",""]);
      },
      getDetail() {
        getMethodCommon("/FireCodeApp/GetForestryUserById?id=" + this.detailInfo[0].Id, {}).then(res => {
          if (res.code == 200) {
            let detail  = {...res.data[0]};
            this.addForm.id = detail.Id;
            this.addForm.name = detail.Name;
            this.addForm.account = detail.Account;
            this.addForm.sex = detail.Sex;
            this.addForm.userRole = detail.UserRole;
            this.addForm.areaId = detail.areaId;
            
            // if(this.addForm.areaId){
            //   var areaId = this.addForm.areaId.split(',')
            //   this.addForm.areaId = turnNum(areaId)
            // }
            // var turnNum = function (nums) {
            //   return nums.map(Number);
            // }
          }
        })
      },
      traverse(arr) {
        if (arr && arr.length > 0) {
         
          var list = []
          arr.forEach(childelement => {
            list.push({
              id: childelement.id,
              label: childelement.areaName,
              parentId: childelement.pId || null,
              children: this.traverse(childelement.child)
            })
          });
          return list
        }
      },
      submitForm() {
        var _this = this
        this.$refs['form'].validate((valid) => {
          if (valid) {

            _this.addForm.password = _this.addForm.account;

            // 添加
            this.addForm.timeSlot = [];
            this.timeslot.forEach((item,index)=>{
              if(item[0] != "" && item[1] != ""){
                this.addForm.timeSlot.push({timeSlot:item[0]+"-"+item[1]});
              }
            })

            postMethodCommon("/FireCodeApp/Register", _this.addForm).then(response => {
                if (response.code == 200) {
                  // 上传shp
                  this.$emit("addSuccess");
                  this.$message({
                    type: "success",
                    message: "添加成功"
                  })
                }
              })

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      createForm() {
        var _this = this
        this.$refs['form'].validate((valid) => {
          if (valid) {

            // delete this.addForm.zrclist
            postMethodCommon("/FireCodeApp/EditForestryUser ", _this.addForm).then(response => {
              if (response.code == 200) {
                // 上传shp
                this.$emit("addSuccess");
                this.$message({
                  type: "success",
                  message: "编辑成功"
                })
              }
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      close() {
        this.$emit("close");
      }
    }
  }
</script>
<style scoped>
  ::v-deep .vue-treeselect__control {
    background: rgba(0, 9, 34, 0.6);
  }

  ::v-deep .el-form-item__label {
    color: #fff;
  }

  ::v-deep .el-radio {
    color: #fff;

  }

  .service-type-btn {
    width: 100%;
    height: 180px;
    text-align: center;
    margin-top: 100px;
  }

  ::v-deep .el-input__inner {
    background: rgba(0, 9, 34, 1);
    color: #fff;
    height: 36px;
  }
::v-deep .el-range-editor--mini .el-range-input{
    background:none;
    color:#fff;
}

.remove-timesolt{
  margin-left:12px;font-size:22px;margin-top:0px;
  position:absolute;
  right:-32px;
  top:8px;
}

.remove-timesolt:hover{
  cursor:pointer;
  color:#fff;
}
</style>