<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--侧边部门数据-->
      <el-col :xs="9" :sm="6" :md="5" :lg="4" :xl="4">
        <div class="head-container">
          <el-input
            v-model="departmentName"
            clearable
            size="small"
            placeholder="输入部门名称搜索"
            prefix-icon="el-icon-search"
            class="filter-item"
            @input="getDeptDatas"
          />
        </div>
        <el-tree
          :data="deptDatas"
          :load="getDeptDatas"
          :props="defaultProps"
          :expand-on-click-node="false"
          lazy
          @node-click="handleNodeClick"
        />
      </el-col>
      <el-col :xs="15" :sm="18" :md="19" :lg="20" :xl="20">
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.userName"
              clearable
              size="small"
              placeholder="输入用户名搜索"
              style="width: 200px"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <date-range-picker v-model="query.baseCreateTime" class="date-item" />
            <el-select
              v-model="query.userStatus"
              clearable
              size="small"
              placeholder="状态"
              class="filter-item"
              style="width: 120px"
              @change="crud.toQuery"
            >
              <el-option
                v-for="item in statuses.userStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog
          append-to-body
          :close-on-click-modal="false"
          :before-close="crud.cancelCU"
          :visible.sync="crudCU"
          :title="crud.status.title"
          width="570px"
        >
          <el-form
            ref="form"
            :inline="true"
            :model="form"
            :rules="rules"
            size="small"
            label-width="66px"
          >
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" />
            </el-form-item>
            <el-form-item label="姓名" prop="realName">
              <el-input v-model="form.realName" />
            </el-form-item>
            <el-form-item label="部门" prop="departmentId">
              <treeselect
                v-model="form.departmentId"
                filterable
                :options="depts"
                :load-options="loadDepts"
                style="width: 178px"
                placeholder="选择部门"
              />
            </el-form-item>
            <el-form-item label="岗位" prop="jobs">
              <el-select
                v-model="form.positionIds"
                filterable
                style="width: 178px"
                multiple
                placeholder="请选择"
              >
                <el-option
                  v-for="item in jobs"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-switch
                v-model="form.userStatus"
                active-color="#409EFF"
                inactive-color="#E8E8E8"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
            <el-form-item label="类别">
              <el-radio-group v-model="form.isSystem">
                <el-radio :label="1">系统用户</el-radio>
                <el-radio :label="0">普通用户</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item
              v-if="form.isSystem == 0"
              style="margin-bottom: 0"
              label="角色"
              prop="roles"
            >
              <el-select v-model="form.roleIds" style="width: 437px" multiple placeholder="请选择">
                <el-option
                  v-for="item in roles"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU"
              >确认</el-button
            >
          </div>
        </el-dialog>
        <el-table
          ref="table"
          v-loading="crud.loading"
          :data="crud.data"
          style="width: 100%"
          @selection-change="crud.selectionChangeHandler"
        >
          <el-table-column :selectable="checkboxT" type="selection" width="55" align="center" />
          <el-table-column
            v-for="item in userTableOptions"
            :key="item.prop"
            :label="item.label"
            :prop="item.prop"
            :width="item.width"
            :align="item.align"
            :fixed="item.fixed"
            :sortable="item.sortable"
          >
            <template slot-scope="scope">
              <el-switch
                v-if="item.prop == 'userStatus'"
                v-model="scope.row.userStatus"
                active-color="#409EFF"
                inactive-color="#F56C6C"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(scope.row, scope.row.userStatus)"
              />
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkPer(['admin', 'user:edit', 'user:del'])"
            label="操作"
            width="125"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation :data="scope.row" :permission="permission" />
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import permission from '@/directive/permission'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
// import { crudOperation, rrOperation, udOperation, pagination } from '@crud'
import crudComps from '@crud'
import DateRangePicker from '@/components/DateRangePicker'
import crudUser from '@/api/system/user'
import { getDepts, getDeptsTree } from '@/api/system/dept'
import { getJobList } from '@/api/system/job'
import { getRoleList } from '@/api/system/role'

import { userTableOptions } from '../tableConfig'
import { mapGetters } from 'vuex'
import { validPhone } from '@/utils/validate'
import { getStatusOptions } from '@/api/options'
// vue-treeselect
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'

const defaultForm = {
  id: '',
  userName: '',
  realName: '',
  gender: 1,
  isSystem: 0,
  userStatus: 1,
  roleIds: [],
  positionIds: [],
  departmentId: null,
  loginCount: 0,
  isOnline: 0,
  firstVisit: '',
  previousVisit: '',
  lastVisit: '',
  remark: '',
}
export default {
  name: 'user',
  directives: { permission },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  components: {
    ...crudComps,
    DateRangePicker,
    Treeselect,
  },
  cruds() {
    return CRUD({
      title: '用户',
      url: 'system/user/getPageListJson',
      crudMethod: { ...crudUser },
    })
  },
  // dicts: ['UserStatus'],
  data() {
    return {
      departmentName: '', //左侧部门树形图搜索条件
      depts: [],
      deptDatas: [],
      jobs: [],
      roles: [],
      defaultProps: {
        // tree组件懒加载默认参数
        children: 'children',
        label: 'departmentName',
        isLeaf: 'leaf',
      },
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del'],
      },
      userTableOptions,
      rules: {
        userName: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
        realName: [
          {
            required: true,
            message: '请输入用户姓名',
            trigger: 'blur',
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur',
          },
        ],
      },
      statuses: {
        userStatus: [],
      },
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    crudCU() {
      return this.crud.status.cu > 0
    },
  },
  created() {
    this.crud.msg.add = '新增成功，默认密码：123456'
    this.getStatusOptions()
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.departmentId) {
        this.getDeptsTree(form.departmentId)
      } else {
        this.getDepts()
      }
      this.getRoleList()
      this.getJobList()
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (!crud.form.departmentId) {
        this.$message({
          message: '部门不能为空',
          type: 'warning',
        })
        return false
      } else if (crud.form.positionIds.length === 0) {
        this.$message({
          message: '岗位不能为空',
          type: 'warning',
        })
        return false
      } else if (crud.form.roleIds.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning',
        })
        return false
      }
      return true
    },
    // 获取左侧部门数据
    getDeptDatas(node, resolve) {
      const sort = 'id,desc'
      const params = { sort: [sort], id: '0' }
      if (typeof node !== 'object') {
        if (node) {
          params['name'] = node
        }
      } else if (node.level !== 0) {
        params['id'] = node.data.id
      }
      setTimeout(() => {
        getDepts(params).then((res) => {
          if (resolve) {
            resolve(res.data.content)
          } else {
            this.deptDatas = res.data.content
            // this.deptDatas.forEach(item => {
            //     item.name = item.label
            // })
          }
        })
      }, 100)
    },
    // 获取弹窗内部门数据
    getDepts() {
      getDepts({ id: '0' }).then((res) => {
        this.depts = res.data.content.map((obj) => {
          if (obj.hasChildren) {
            obj.children = null
          }
          return obj
        })
      })
    },
    //编辑时获取弹窗内部门数据
    getDeptsTree(deptId) {
      getDeptsTree({ id: '0' }).then((res) => {
        const data = res.data.content
        this.buildDepts(data)
        this.depts = data
      })
    },
    // 构建部门树组件数据
    buildDepts(depts) {
      depts.forEach((data) => {
        // if (!data.hasChildren) {
        //   delete data.children
        // }
        if (data.children) {
          this.buildDepts(data.children)
        }
        // if (data.hasChildren && !data.children) {
        //   data.children = null
        // }
      })
    },
    // 异步加载部门树数据
    loadDepts({ action, parentNode, callback }) {
      if (action === LOAD_CHILDREN_OPTIONS) {
        getDepts({ id: parentNode.id }).then((res) => {
          parentNode.children = res.data.content.map(function (obj) {
            if (obj.hasChildren) {
              obj.children = null
            }
            return obj
          })
          setTimeout(() => {
            callback()
          }, 200)
        })
      }
    },
    // 切换部门
    handleNodeClick(data) {
      if (data.parentId == 0) {
        this.query.departmentId = ''
      } else {
        this.query.departmentId = data.id
      }
      this.crud.toQuery()
    },
    checkboxT(row, rowIndex) {
      return true
      // return row.id !== this.userInfo.id
    },
    // 改变状态
    changeStatus(data, val) {
      this.$confirm(
        '此操作将 "' + this.dict.label.UserStatus[val] + '" ' + data.userName + ', 是否继续？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          crudUser
            .edit(data)
            .then((res) => {
              this.crud.notify(
                this.dict.label.UserStatus[val] + '成功',
                CRUD.NOTIFICATION_TYPE.SUCCESS
              )
            })
            .catch(() => {
              data.userStatus = data.userStatus == 0 ? 1 : 0
            })
        })
        .catch(() => {
          data.userStatus = data.userStatus == 0 ? 1 : 0
          // data.userStatus = !data.userStatus
        })
    },

    // 获取弹窗内角色数据
    getRoleList() {
      getRoleList()
        .then((res) => {
          this.roles = res.data.content
        })
        .catch(() => {})
    },
    // 获取弹窗内岗位数据
    getJobList() {
      getJobList()
        .then((res) => {
          this.jobs = res.data.content
        })
        .catch(() => {})
    },
    // 获取状态
    getStatusOptions() {
      Object.keys(this.statuses).forEach(async (key) => {
        try {
          let res = await getStatusOptions(key)
          if (res.code === 20000) this.statuses[key] = res.data.content
        } catch (error) {
          console.log(error)
        }
      })
    },
  },
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,
::v-deep .vue-treeselect__placeholder,
::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
</style>
