<template>
  <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
    <el-form :model="form" ref="form" :rules="rules" label-width="60px">
      <el-form-item label="账号 : " prop="mobile">
        <el-input v-model="form.mobile" placeholder="用户手机号"         maxlength="11"
                  :disabled="form.id !==  0"></el-input>
      </el-form-item>

      <el-form-item label="姓名 : " prop="name">
        <el-input v-model="form.name" placeholder="用户姓名"></el-input>
      </el-form-item>

      <el-form-item label="角色 : " prop="role_ids">
        <el-checkbox-group v-model="form.role_ids">
          <el-checkbox v-for="( item,index) in roles" :key="index" :label="item.id" :value="item.id">{{item.name}}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item label="职称 : ">
        <el-select v-model="form.user_type" placeholder="用户类型">
          <el-option
            v-for="item in user_types"
            :label="item.name"
            :value="item.index"
            :key="item.index"
          ></el-option>
        </el-select>

        <el-select v-model="form.user_title" placeholder="用户职称">
          <el-option
            v-for="item in user_titles"
            :label="item.name"
            :value="item.index"
            :key="item.index"
          ></el-option>
        </el-select>
      </el-form-item>


      <el-form-item label="科室:">
         <el-select v-model="form.department_id" placeholder="科室">
          <el-option
            v-for="item in departMent"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="职位 : ">
        <el-input v-model="form.user_title_name" placeholder="输入职位"></el-input>
      </el-form-item>

       

      <el-form-item label="介绍 : ">
        <Tinymce :height="400" menubar ref="editor" v-model="form.intro" :show_upload_img="false"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitAction">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import Tinymce from '@/components/Tinymce'
  import { addAdmin, getAddAdminInitData, getModifyAdminInitData, modifyAdmin } from '@/api/role/admin'
  import { getAllDePartmentList } from "@/api/project/project"
  export default {
    name: 'AdminInfoForm',
    components: {
      Tinymce
    },
    data() {
      var checkMobile = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('手机号不能为空'))
        }
        if (/^1\d{10}$/.test(value) == false) {
          return callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      var checkName = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('姓名不能为空'))
        } else {
          callback()
        }
      }
      return {
        admin_id: 0,
        dialogFormVisible: false,

        user_types: [
          { index: 2, name: '医生' },
          { index: 3, name: '护士' }
        ],
        user_titles: [
          { index: 1, name: '医士' },
          { index: 2, name: '医师' },
          { index: 3, name: '住院医师' },
          { index: 4, name: '主治医师' },
          { index: 5, name: '副主任医师' },
          { index: 6, name: '主任医师' },
          { index: 7, name: '护士' },
          { index: 8, name: '护师' },
          { index: 9, name: '主管护师' },
          { index: 10, name: '副主任护师' },
          { index: 11, name: '主任护师' },
          { index: 12, name: '运营专员' },
          { index: 13, name: '运营主管' }
        ],
        roles: [], // [{id, name, intro, status}]
        loading: true,
        qntoken: '',
        formTitle: '',
        isSubSuperAdmin:false,
        org:null,
        form: {
          role_ids: [],
          user_title_name: '',
          id: 0,
          mobile: '',
          name: '',
          user_type: '',
          user_title: '',
          role: '', // 其实应该是 int 类型
          intro: '',
          department:'',
          department_id:"",
        },
        departMent:[],
        rules: {
          mobile: [{ required: true, validator: checkMobile, trigger: 'blur' }],
          name: [{ required: true, validator: checkName, trigger: 'blur' }],
          role_ids: [
            { type: 'array', required: true, message: '请至少选择一个角色', trigger: 'change' }
          ]
        }
      }
    },
    methods: {
      open: function(adminId) {
        this.admin_id = adminId
        if (this.admin_id < 0) {
          this.$message.error('参数错误')
          this.loading = false
          return
        }
         // let localthis.$store.getters.xt_user.user.id
        let local_user_id = this.$store.getters.xt_user.user.id
        this.form.id = this.admin_id
        if (this.admin_id === 0) {
          let tempForm = {
            role_ids: [],
            user_title_name: '',
            id: 0,
            mobile: '',
            name: '',
            user_type: '',
            user_title: '',
            role: '', // 其实应该是 int 类型
            intro: ''
          }
          this.form = tempForm
          this.formTitle = '新增员工'
          this.form.user_type = this.user_types[0].index
          this.form.user_title = this.user_titles[0].index
          getAddAdminInitData()
            .then(rs => {
              this.loading = false
              var resp = rs.data
              
              if (resp.state === 1) {
                // this.roles.push(...resp.data.roles)
                this.roles = resp.data.roles
                this.qntoken = resp.data.qntoken

                this.isSubSuperAdmin = resp.data.isSubSuperAdmin
                this.org = resp.data.org

                //如果当前用户是子管理员则，则需要将子管理员角色去除，因为子管理员不能添加子管理员
                if(this.isSubSuperAdmin){
                  for (let i =0 ; i < this.roles.length; i++){
                    if(this.roles[i].is_system == 1 && this.roles[i].role_name == "子管理员"){
                      this.roles.splice(i, 1)
                      i--
                    }
                  }
                }

              } else {
                this.$message.error(resp.msg)
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error(err)
            })
        } else {
          this.formTitle = '编辑用户'
          getModifyAdminInitData(this.form.id)
            .then(rs => {
              this.loading = false
              var resp = rs.data
              if (resp.state === 1) {
                this.roles = []
                this.roles.push(...resp.data.roles)
                this.qntoken = resp.data.qntoken
                var org = resp.data.org


                var admin = resp.data.admin
                this.form.name = admin.user_name
                this.form.mobile = admin.admin.mobile
                this.form.user_type = admin.user_type
                if(admin.user_type == 1){

                  this.form.user_type = ""
                }
                this.form.user_title = admin.user_title
                this.form.role = admin.role_ids
                this.form.department_id = admin.department_id
                this.form.role_ids = []
                for (let i = 0; i < this.form.role.split(",").length; i++) {
                  if (this.form.role.split(',')[i].length > 0) {
                    this.form.role_ids.push(parseInt(this.form.role.split(',')[i]))
                  }
                }

                this.form.intro = admin.intro
                this.form.user_title_name = admin.user_title_name

                this.isSubSuperAdmin = resp.data.isSubSuperAdmin
                this.org = resp.data.org

                //如果当前用户是超级管理员而且编辑自己的信息

                if(!this.isSubSuperAdmin) {
                  if (this.form.id == org.creator) {
                    for (let i = 0; i < this.roles.length; i++) {
                      if (this.roles[i].is_system == 1 && this.roles[i].name == "子管理员") {
                        this.roles.splice(i, 1)
                        i--
                      }
                    }
                  }
                }else{
                  for (let i = 0; i < this.roles.length; i++) {
                    if (this.roles[i].is_system == 1 && this.roles[i].name == "子管理员") {
                      this.roles.splice(i, 1)
                      i--
                    }
                  }

                }

              } else {
                this.$message.error('该用户不存在')
              }
            })
            .catch(err => {
              this.loading = false
              this.$message.error('该用户不存在')
            })
        }

        this.dialogFormVisible = true
      },
      submitAction: function() {   
       console.log("第是",this.form.department_id)  
        var department = ""
        for(let i=0;i<this.departMent.length;i++){
          if(this.form.department_id == this.departMent[i].id){
              department = this.departMent[i].name
          }
        }
        this.form.department = department
        
        if (this.admin_id < 0) {
          return
        }
        this.$refs.form.validate(valid => {
          if (valid) {
            if(this.form.user_type == "" || this.form.user_type == 0 ){
              this.$message.error("职称不能为空")
              return
            }

            this.loading = true
            console.log("id-----",this.form.id)
            if (this.form.id === 0) {
              this.form.role = this.form.role_ids.join(',')
              addAdmin(
                this.form.mobile,
                this.form.name,
                this.form.user_type,
                this.form.user_title,
                this.form.role,
                this.form.intro,
                this.form.user_title_name,
                this.form.department,
                this.form.department_id,
              ).then(rs => {
                  this.loading = false
                  var resp = rs.data
                  if (resp.state === 1) {
                    this.$store.dispatch('DidChangeAdmins')
                    var _this = this
                    setTimeout(() => {
                      _this.$store.dispatch('RecoverAdminsChangeState')
                    }, 500)
                    this.dialogFormVisible = false
                  } else {
                    this.$message.error(resp.msg)
                  }
                })
                .catch(err => {
                  this.loading = false
                  this.$message.error(err)
                })
            } else {
              this.form.role = this.form.role_ids.join(',')
             
               var department = ""
               for(let i=0;i<this.departMent.length;i++){
                if(this.form.department_id == this.departMent[i].id){
                    department = this.departMent[i].name
                }
              }
              this.form.department = department
           
             
              modifyAdmin(this.form.id,this.form.name,this.form.user_type,this.form.user_title,this.form.role,this.form.intro, this.form.user_title_name,this.form.sort,this.form.department,this.form.department_id).then(rs => {
                  this.loading = false
                  var resp = rs.data
                  if (resp.state === 1) {
                    this.$store.dispatch('DidChangeAdmins')
                    var _this = this
                    setTimeout(() => {
                      _this.$store.dispatch('RecoverAdminsChangeState')
                    }, 500)

                    this.dialogFormVisible = false
                  } else {
                    this.$message.error(resp.msg)
                  }
                })
                .catch(err => {
                  this.loading = false
                  this.$message.error(err)
                })
            }
          } else {
            return false
          }
        })
      },

      getlist(){
        getAllDePartmentList().then(response=>{
         if(response.data.state == 1){
           var department =   response.data.data.departMent
           console.log("department2222",department)
           this.departMent = department
         
         }
        })
      }
    },

    created(){
        //获取所有科室
       this.getlist()
    }
  }
</script>
