<template>
  <div>
    <el-dialog
      :visible.sync="dialog"
      title="部门配置"
      append-to-body
      width="800px"
      :close-on-click-modal="false"
    >
      <el-button @click="showAddDialog()" :style="{marginBottom: '20px'}" size="mini" type="primary">添加</el-button>
      <el-table
        :data="tableData"
        size="mini"
        border
        style="width: 100%">
        <el-table-column
          prop="deptName"
          label="部门名称">
        </el-table-column>
        <el-table-column
          prop="userName"
          label="展业名称">
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态">
          <template slot-scope="scope">
            {{ scope.row.status === 1 ? '启用' : '禁用'}}
          </template>
        </el-table-column>
        <el-table-column
          prop="roleList"
          label="用户角色">
          <template slot-scope="scope">
            {{ scope.row.roleList.map(item=>item.name).join(',') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="showAddDialog(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :visible.sync="addDialog"
      :title="addDialogTitle"
      append-to-body
      width="500px"
      :close-on-click-modal="false"
      :before-close="resetForm"
    >
      <el-form size="mini" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="ruleForm.deptId" placeholder="请选择部门" :style="{width: '100%'}" filterable :disabled="!!ruleForm.userId">
            <el-option v-for="(item,index) in deptList" :key="index" :label="item.name" :value="item.id"></el-option>
            <el-option v-if="addDialogTitle === '修改部门'" :label="ruleForm.deptName" :value="ruleForm.deptId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="展业名称" prop="userName">
          <el-input v-model="ruleForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="roleIds">
          <treeselect
            v-model="ruleForm.roleIds"
            style="width: 100%"
            :multiple="true"
            :normalizer="normalizer"
            :options="roles"
            placeholder="选择用户角色"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="ruleForm.status" active-text="启用" inactive-text="禁用" :active-value="1" :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listUserDept, saveUserDept, updateUserDept } from "@/api/user"
import { getDept } from "@/api/common" 
import { getAll } from '@/api/role'
export default {
  components: { Treeselect },
  data() {
    return {
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children && node.children.length > 0 ? node.children : 0
        }
      },
      dialog: false,
      addDialog: false,
      addDialogTitle: '添加部门',
      tableData: [],
      loginId: '',
      ruleForm: {
        deptId: '',
        userName: '',
        loginId: '',
        roleIds: [],
        status: 1,
        userId: ''
      },
      rules: {
        deptId: { required: true, message: '请选择部门', trigger: 'blur' },
        userName: { required: true, message: '请输入展业名称', trigger: 'blur' },
        roleIds: { required: true, message: '请选择用户角色', trigger: 'blur' },
        status: { required: true, message: '请选择状态', trigger: 'blur' },
      },
      deptList: [],
      roles: []
    }
  },
  watch: {
    dialog(value) {
      if(value) {
        this.getRoles()
        this.listUserDept()
      }
    }
  },
  methods: {
    async listUserDept() {
      let ret = await listUserDept({loginId: this.loginId})
      if(ret && ret.code === 0) {
        this.tableData = ret.data
        this.getDept()
      }
    },
    async getDept() {
      let ret = await getDept()
      if(ret && ret.code === 0) {
        let userDeptIds = this.tableData.map(item=>item.deptId)
        this.deptList = ret.data.filter(item=>!userDeptIds.includes(item.id) )
      }
    },
    getRoles() {
      getAll({ current: 1, size: 10000 })
        .then(res => {
          console.log(res)
          this.roles = res.data.list.filter(item => item.id !== 2)
        })
        .catch(err => {
          console.log(err.response.data.message)
        })
    },
    submitForm(formName) {
      this.$refs[formName].validate(async(valid) => {
        if (valid) {
          const fn = this.ruleForm.userId ? updateUserDept : saveUserDept
          let ret = await fn(this.ruleForm)
          if(ret && ret.code === 0){
            this.$message({
              message:  this.ruleForm.userId ? "修改成功" : "添加成功",
              type: 'success',
            });
            this.addDialog = false
            this.listUserDept()
            this.$emit('callback')
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.addDialog = false
    },
    showAddDialog(row) {
      this.addDialog = true
      if(row) {
        Object.assign(this.ruleForm,row)
        this.ruleForm.roleIds = this.ruleForm.roleList.map(item=>item.id)
        this.addDialogTitle = '修改部门'
      } else {
        this.ruleForm = {
          deptId: '',
          userName: '',
          userId: '',
          loginId: this.loginId,
          roleIds: [],
          status: 1
        }
        this.addDialogTitle = '添加部门'
      }
    }
  },
}
</script>