<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-left">
      <div class="NCC-common-title">
        <h2>{{$t('common.organization')}}</h2>
        <span class="options">
          <el-tooltip content="组织架构图" placement="top">
            <el-link icon="el-icon-menu" :underline="false" @click="showDiagram" />
          </el-tooltip>
        </span>
      </div>
      <el-scrollbar class="NCC-common-el-tree-scrollbar">
        <el-tree ref="treeBox" v-loading="treeLoading" :data="treeData"
          :element-loading-text="$t('common.loadingText')" :props="defaultProps" default-expand-all
          highlight-current :expand-on-click-node="false" node-key="id"
          @node-click="handleNodeClick" class="NCC-common-el-tree">
          <span class="custom-tree-node" slot-scope="{ data, node }">
            <i :class="data.icon" />
            <span class="text">{{node.label}}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>
    <div class="NCC-common-layout-center NCC-flex-main">
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item :label="$t('common.keyWord')">
              <el-input v-model="params.keyword" :placeholder="$t('common.enterKeyword')"
                clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="门店">
              <el-select v-model="params.mdid" placeholder="请选择门店" clearable filterable style="width: 100%">
                <el-option
                  v-for="item in storeOptions"
                  :key="item.id"
                  :label="item.fullName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="岗位">
              <el-select v-model="params.gw" placeholder="请选择岗位" clearable style="width: 100%">
                <el-option
                  v-for="opt in userGwOptions"
                  :key="opt.value"
                  :label="opt.label"
                  :value="opt.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="启用状态">
              <el-select v-model="params.enabledMark" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="正常" :value="1" />
                <el-option label="停用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">
                {{$t('common.search')}}</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">{{$t('common.reset')}}
              </el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="NCC-common-layout-main NCC-flex-main">
        <div class="NCC-common-head">
          <div class="user-batch-head">
            <topOpts @add="handleAddEdit()">
              <el-button type="primary" plain size="small" icon="el-icon-location-outline" :disabled="!multipleSelection.length" @click="openBatchPunchStores">
                批量可打卡门店
              </el-button>
              <el-button type="primary" plain size="small" icon="el-icon-date" :disabled="!multipleSelection.length" @click="openBatchRestGroup">
                批量应休分组
              </el-button>
            </topOpts>
          </div>
          <div class="NCC-common-head-right">
            <el-tooltip effect="dark" :content="$t('common.refresh')" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false"
                @click="reset()" />
            </el-tooltip>
            <screenfull />
          </div>
        </div>
        <NCC-table
          ref="userTable"
          v-loading="listLoading"
          :data="tableData"
          row-key="id"
          hasC
          :selectable="rowSelectable"
          @selection-change="onSelectionChange"
        >
          <el-table-column prop="account" label="账号" width="160" />
          <el-table-column prop="realName" label="姓名"  />
          <el-table-column label="性别" width="50" >
            <template slot-scope="scope" sortable>
              <span>{{ scope.row.gender ==1 ? '男': ( scope.row.gender == 2 ? '女' : '保密') }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="mobilePhone" label="手机" width="160" />
          <el-table-column prop="punchAllowedStoreSummary" label="可打卡门店" min-width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.punchAllowedStoreSummary || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="attendanceRestGroupName" label="应休分组" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.attendanceRestGroupName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="入职时间" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.entryDate ? ncc.dateFormat(scope.row.entryDate, 'YYYY-MM-DD') : '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="组织" />
          <el-table-column prop="gwfl" label="岗位分类" width="90" />
          <el-table-column label="门店" width="180">
            <template slot-scope="scope" sortable>
              <span>{{ getmdname(scope.row.mdid) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="gw" label="职位" width="100" />
          <el-table-column prop="roleName" label="角色"  width="160"/>
          <el-table-column prop="fyft" label="费用分摊" width="100" >
            <template slot-scope="scope">
              <el-tag :type="scope.row.fyft === '是' ? 'success' : 'info'" disable-transitions>
                {{scope.row.fyft || '否'}}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creatorTime" label="创建时间" :formatter="ncc.tableDateFormat" width="160"/>
          <el-table-column prop="sortCode" label="排序" width="70"  />
          <el-table-column label="状态" width="70" >
            <template slot-scope="scope">
              <el-tag :type="scope.row.enabledMark == 1 ? 'success' : 'danger'" disable-transitions>
                {{scope.row.enabledMark==1?'正常':'停用'}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <tableOpts
                :has-del="!isAdministratorUser(scope.row)"
                @edit="handleAddEdit(scope.row.id)"
                @del="handleDel(scope.row.id)"
              >
                <el-dropdown hide-on-click>
                  <span class="el-dropdown-link">
                    <el-button size="mini" type="text">
                      {{$t('common.moreBtn')}}<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      @click.native="handleResetPwd(scope.row.id, scope.row.account)">
                      {{$t('user.resetPassword')}}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </tableOpts>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination :total="total" :page.sync="params.currentPage" :limit.sync="params.pageSize"
          @pagination="initData" />
      </div>
    </div>
    <Form v-show="formVisible" ref="Form" @close="removeForm" />
    <Diagram v-if="diagramVisible" ref="Diagram" @close="diagramVisible = false" />
    <ResetPwdForm v-if="resetFormVisible" ref="ResetPwdForm" @refreshDataList="initData" />
    <UserBatchPunchStoresDialog ref="BatchPunchDialog" @success="onBatchAttendanceSuccess" />
    <UserBatchRestGroupDialog ref="BatchRestDialog" @success="onBatchAttendanceSuccess" />
  </div>
</template>
<script>
import {
  getDepartmentSelector
} from '@/api/permission/department'
import {
  getUserList,
  updateUserState,
  delUser
} from '@/api/permission/user'
import {
  getStoreSelector
} from '@/api/extend/store'
import { USER_GW_OPTIONS } from './user-gw-options'
import Form from './Form'
import Diagram from './Diagram'
import ResetPwdForm from './ResetPassword'
import UserBatchPunchStoresDialog from './user-batch-punch-stores-dialog'
import UserBatchRestGroupDialog from './user-batch-rest-group-dialog'

export default {
  name: 'permission-user',
  components: {
    Form,
    Diagram,
    ResetPwdForm,
    UserBatchPunchStoresDialog,
    UserBatchRestGroupDialog
  },
  data() {
    return {
      userGwOptions: USER_GW_OPTIONS,
      keyword: '',
      treeData: [],
      tableData: [],
      treeLoading: false,
      listLoading: true,
      storeOptions: [],
      params: {
        organizeId: '',
        keyword: '',
        mdid: '',
        gw: '',
        enabledMark: '',
        currentPage: 1,
        pageSize: 20
      },
      defaultProps: {
        children: 'children',
        label: 'fullName'
      },
      total: 0,
      type: '',
      formVisible: false,
      diagramVisible: false,
      resetFormVisible: false,
      authorizeFormVisible: false,
      multipleSelection: []
    }
  },
  created() {
    this.getOrganizeList()
    this.getStoreList()
  },
  methods: {
    rowSelectable(row) {
      return !this.isAdministratorUser(row)
    },
    /** 列表接口 isAdministrator：1 表示系统管理员（不可删、批量不选） */
    isAdministratorUser(row) {
      if (!row) return false
      const a = row.isAdministrator
      return a === 1 || a === true || a === '1'
    },
    onSelectionChange(val) {
      this.multipleSelection = val || []
    },
    openBatchPunchStores() {
      const ids = (this.multipleSelection || []).map(r => r.id).filter(Boolean)
      if (!ids.length) {
        this.$message.warning('请先勾选用户')
        return
      }
      this.$refs.BatchPunchDialog.open(ids)
    },
    openBatchRestGroup() {
      const ids = (this.multipleSelection || []).map(r => r.id).filter(Boolean)
      if (!ids.length) {
        this.$message.warning('请先勾选用户')
        return
      }
      this.$refs.BatchRestDialog.open(ids)
    },
    onBatchAttendanceSuccess() {
      const t = this.$refs.userTable
      if (t && t.$refs && t.$refs.NCCTable) {
        t.$refs.NCCTable.clearSelection()
      }
      this.multipleSelection = []
      this.initData()
    },
    getmdname(id) {
      if (!id) {
        return '无'
      }
      const store = this.storeOptions.find(item => item.id === id)
      return store ? store.fullName : '无'
    },
    showDiagram() {
      this.diagramVisible = true
      this.$nextTick(() => {
        this.$refs.Diagram.init()
      })
    },
    search() {
      this.params.currentPage = 1
      this.params.pageSize = 20
      this.params.sort = 'desc'
      this.initData()
    },
    reset() {
      this.params.keyword = ''
      this.params.mdid = ''
      this.params.gw = ''
      this.params.enabledMark = ''
      this.search()
    },
    getStoreList() {
      getStoreSelector().then(res => {
        if (res.data && res.data.list) {
          this.storeOptions = res.data.list
        } else if (res.data && Array.isArray(res.data)) {
          this.storeOptions = res.data
        }
      }).catch(() => {
        this.storeOptions = []
      })
    },
    getOrganizeList() {
      this.treeLoading = true
      getDepartmentSelector().then(res => {
        this.treeData = res.data.list
        this.treeLoading = false
        this.initData()
      }).catch(() => {
        this.treeLoading = false
      })
    },
    initData() {
      this.listLoading = true
      getUserList(this.params).then(res => {
        this.tableData = res.data.list
        this.total = res.data.pagination.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleNodeClick(data) {
      if (this.params.organizeId === data.id) return
      this.params.organizeId = data.id
      this.type = data.type
      this.reset()
    },
    handleAddEdit(id) {
      this.formVisible = true
      this.$nextTick(() => {
        this.$refs.Form.init(id, this.type === 'department' ? this.params.organizeId : '')
      })
    },
    removeForm(isRefresh) {
      this.formVisible = false
      if (isRefresh) {
        this.keyword = ''
        this.initData()
      }
    },
    removeAuthorizeForm(isRefresh) {
      this.authorizeFormVisible = false
      if (isRefresh) {
        this.keyword = ''
        this.initData()
      }
    },
    handleUpdateState(row) {
      const txt = row.enabledMark ? '禁用' : '开启'
      this.$confirm(`您确定要${txt}当前用户吗, 是否继续?`, '提示', {
        type: 'warning'
      }).then(() => {
        updateUserState(row.id).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            duration: 1000,
            onClose: () => {
              row.enabledMark = row.enabledMark ? 0 : 1
            }
          })
        })
      }).catch(() => { })
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        type: 'warning'
      }).then(() => {
        delUser(id).then(res => {
          this.$message({
            type: 'success',
            message: res.msg,
            duration: 1500,
            onClose: () => {
              this.initData()
            }
          })
        })
      }).catch(() => { })

    },
    handleResetPwd(id, account) {
      this.resetFormVisible = true
      this.$nextTick(() => {
        this.$refs.ResetPwdForm.init(id, account)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.user-batch-head {
  ::v-deep .ncc-opts {
    display: inline-flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
  }
}
</style>
