<template>
  <div class="jp-common-layout page">
    <div class="jp-common-layout-left">
      <div class="jp-common-title">
        <el-input
          placeholder="组织机构:请输入关键字过滤"
          size="small"
          clearable
          v-model="filterText">
        </el-input>
      </div>
      <div class="jp-common-el-tree-scrollbar el-scrollbar">
        <div class="el-scrollbar__wrap">
          <div class="el-scrollbar__view">
            <el-tree
              class="filter-tree jp-common-el-tree"
              :render-content="renderContent"
              :data="officeTreeData"
              :props="{
                    value: 'id',             // ID字段名
                    label: 'name',         // 显示名称
                    children: 'children'    // 子级字段名
                  }"
              node-key="id"
              default-expand-all
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              highlight-current
              @node-click="handleNodeClick"
              ref="officeTree">
            </el-tree>
          </div>
        </div>
      </div>
    </div>
    <div class="jp-common-layout-center jp-flex-main">
      <el-form size="small" :inline="true" class="query-form" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
        <!-- 搜索框-->
        <el-form-item label="姓名" prop="name">
          <el-input size="small" v-model="searchForm.name" placeholder="姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="mobile">
          <el-input size="small" v-model="searchForm.mobile" placeholder="电话号码" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showHideItem" label="证件号" prop="idCard">
          <el-input size="small" v-model="searchForm.idCard" placeholder="证件号" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="showHideItem" label="部门" prop="officeSelect">
          <SelectTree
            ref="officeTree"
            :props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"
            size="small"
            :url="`/sys/office/treeData?type=2`"
            :value="searchForm.officeSelect"
            :clearable="true"
            :accordion="true"
            @getValue="(value) => {searchForm.officeSelect=value}"/>
        </el-form-item>
        <el-form-item v-if="showHideItem" label="岗位" prop="postSelect">
          <el-select v-model="searchForm.postSelect" size="small" filterable @change="$forceUpdate()" style="width:100%" placeholder="岗位" clearable>
            <el-option
              v-for="item in postList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="showHideItem" label="入职日期" prop="dates">
          <el-date-picker
            style=""
            placement="bottom-start"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="searchForm.dates"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="default" @click="showHide" size="small" :icon="showHideIcon">{{showHideName}}</el-button>
          <el-button type="primary" @click="refreshList()" size="small" icon="el-icon-search">查询</el-button>
          <el-button @click="resetSearch()" size="small" icon="el-icon-refresh-right">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="bg-white top">
        <vxe-toolbar :refresh="{query: refreshList}" import export custom>
          <template #buttons>
            <el-button v-if="hasPermission('roster:base:add')" type="primary" size="small" icon="el-icon-plus" @click="add()">新建</el-button>
            <el-button v-if="hasPermission('roster:base:del')" type="danger"   size="small" icon="el-icon-delete" @click="del()" :disabled="$refs.rosterTable && $refs.rosterTable.getCheckboxRecords().length === 0" plain>删除</el-button>
            <el-button v-if="hasPermission('roster:base:import')" size="small"  @click="template()" plain>模板下载</el-button>
            <el-button v-if="showButton" type="primary" size="small" icon="el-icon-arrow-down" @click="showTabs()" plain>展示分类</el-button>
            <el-button v-if="disableButton" type="primary" size="small" icon="el-icon-arrow-up" @click="disableTabs()" plain>收起分类</el-button>
          </template>
        </vxe-toolbar>
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane :key="index" v-for="(item,index) in workerTypeList" :label="item.label" :name="item.label" :value="item.value"></el-tab-pane>
        </el-tabs>
        <div style="height: calc(100% - 140px);">
          <vxe-table
            border="inner"
            auto-resize
            resizable
            height="auto"
            :loading="loading"
            size="small"
            ref="rosterTable"
            show-header-overflow
            show-overflow
            highlight-hover-row
            :menu-config="{}"
            :print-config="{}"
            :export-config="{
                    remote: true,
                    filename: `花名册数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: `花名册数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
            @sort-change="sortChangeHandle"
            :sort-config="{remote:true}"
            :data="dataList"
            :import-config="{
                    importMethod: importMethod,
                    types: ['xls', 'xlsx'],
                    remote: true
                    }"
            :checkbox-config="{}">
            <vxe-column type="seq" width="60" title="序号"></vxe-column>
            <vxe-column type="checkbox"  width="40px"></vxe-column>
            <vxe-column title="姓名" field="name" min-width="150px" align="center">
              <template slot-scope="scope">
                <el-link  type="primary" :underline="false" v-if="hasPermission('roster:base:view')"  @click="view(scope.row)">{{scope.row.name}}</el-link>
                <span v-else>{{scope.row.name}}</span>
              </template>
            </vxe-column>
            <vxe-column min-width="150px"  title="电话号码" field="mobile" align="center"> </vxe-column>
            <vxe-column min-width="150px"  title="证件号" field="idCard" align="center"> </vxe-column>
            <vxe-column min-width="150px"  title="人员类型" field="personType" align="center">
              <template slot-scope="scope">
                <span> {{$dictUtils.getDictLabel("roster_person_type", scope.row.personType)}} </span>
              </template>
            </vxe-column>
            <vxe-column min-width="150px"  title="员工类型" field="workerType" align="center">
              <template slot-scope="scope">
                <span> {{$dictUtils.getDictLabel("worker_type", scope.row.workerType)}} </span>
              </template>
            </vxe-column>
            <vxe-column min-width="150px"  title="部门" field="officeName" align="center"> </vxe-column>
            <vxe-column min-width="150px"  title="岗位" field="postNames" align="center"> </vxe-column>
            <vxe-column min-width="150px"  title="入职日期" field="onboardingDate" align="center">
              <template slot-scope="scope">
                {{ commonJS.isEmpty(scope.row.onboardingDate) ? '' : moment(scope.row.onboardingDate).format('YYYY-MM-DD')}}
              </template>
            </vxe-column>

            <vxe-column title="操作" width="120px" fixed="right" align="center">
              <template  slot-scope="scope">
                <!--              <el-button v-if="hasPermission('roster:base:view')" type="text" icon="el-icon-view" size="small" @click="view(scope.row)">查看</el-button>-->
                <el-button v-if="hasPermission('roster:base:edit')" type="text"  size="small" @click="edit(scope.row)">修改</el-button>
                <el-button v-if="hasPermission('roster:base:del')" type="text"   size="small" @click="del(scope.row.id)">删除</el-button>
              </template>
            </vxe-column>
          </vxe-table>
          <vxe-pager
            background
            size="small"
            :current-page="tablePage.currentPage"
            :page-size="tablePage.pageSize"
            :total="tablePage.total"
            :page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
            :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
            @page-change="currentChangeHandle">
          </vxe-pager>
        </div>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <component is="RosterForm"  ref="rosterForm" @refreshDataList="refreshList"></component>
    </div>
  </div>
</template>

<script>
  import RosterService from '@/api/roster/RosterService'
  import RosterForm from './RosterForm'
  import PostService from '@/api/sys/PostService'
  import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import OfficeService from '@/api/sys/OfficeService'
  export default {
    data () {
      return {
        showHideItem: false,
        showHideIcon: 'el-icon-arrow-down',
        showHideName: '展示',
        searchForm: {
          name: '',
          idCard: '',
          mobile: '',
          officeSelect: '',
          postSelect: '',
          dates: [],
          companyId: '',
          officeId: ''
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPag1e: 1,
          pageSize: 10,
          orders: []
        },
        loading: false,
        activeName: 'working',
        workerTypeList: [],
        activeValue: '',
        showButton: false,
        disableButton: true,
        personType: '',
        postList: [],
        filterText: '',
        officeTreeData: []
      }
    },
    rosterService: null,
    postService: null,
    officeService: null,
    created () {
      this.rosterService = new RosterService()
      this.postService = new PostService()
      this.officeService = new OfficeService()
      this.addTabs()
      this.queryAllPost()
    },
    components: {
      RosterForm,
      SelectTree
    },
    activated () {
      this.refreshTree()
      this.queryAllPost()
      this.refreshList()
    },
    watch: {
      filterText (val) {
        this.$refs.officeTree.filter(val)
      }
    },
    methods: {
      handleNodeClick (data) {
        if (data.type === '1') {
          this.searchForm.companyId = data.id
          this.searchForm.officeId = ''
        } else {
          this.searchForm.companyId = ''
          this.searchForm.officeId = data.id
        }
        this.refreshList()
      },
      filterNode (value, data) {
        if (!value) return true
        return data.name.indexOf(value) !== -1
      },
      refreshTree () {
        this.officeService.treeData().then(({data}) => {
          this.officeTreeData = data
        })
      },
      renderContent (h, { node, data, store }) {
        return (
          <span class="custom-tree-node">
                {
                  data.type === '1' ? <i class="fa fa-sitemap"></i> : <i class="fa fa-users"></i>
                }
            <span class="text">{node.label}</span>
              </span>
        )
      },
      showHide () {
        if (this.showHideItem === false) {
          this.showHideItem = true
          this.showHideIcon = 'el-icon-arrow-up'
          this.showHideName = '隐藏'
        } else {
          this.showHideItem = false
          this.showHideIcon = 'el-icon-arrow-down'
          this.showHideName = '展示'
        }
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
        this.activeName = '全部'
        this.rosterService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          'workerType': this.activeValue,
          'personType': this.personType,
          ...this.searchForm
        }).then(({data}) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.loading = false
        })
      },
      // 当前页
      currentChangeHandle ({ currentPage, pageSize }) {
        this.tablePage.currentPage = currentPage
        this.tablePage.pageSize = pageSize
        this.refreshList()
      },
      // 排序
      sortChangeHandle (column) {
        this.tablePage.orders = []
        if (column.order != null) {
          this.tablePage.orders.push({column: this.$utils.toLine(column.property), asc: column.order === 'asc'})
        }
        this.refreshList()
      },
      // 新增
      add () {
        this.$refs.rosterForm.init('add', '')
      },
      // 修改
      edit (row) {
        row.id = row.id || this.$refs.rosterTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
        this.$refs.rosterForm.init('edit', row.id, row.personType)
      },
      // 查看
      view (row) {
        this.$refs.rosterForm.init('view', row.id, row.personType)
      },
      // 删除
      del (id) {
        let ids = id || this.$refs.rosterTable.getCheckboxRecords().map(item => {
          return item.id
        }).join(',')
        this.$confirm(`删除花名册数据时会将关联的用户数据同时删除，确定删除所选项吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.loading = true
          this.rosterService.delete(ids).then(({data}) => {
            this.$message.success(data)
            this.refreshList()
            this.loading = false
          })
        })
      },
      resetSearch () {
        this.filterText = ''
        this.searchForm.companyId = ''
        this.searchForm.officeId = ''
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      handleClick (tab) {
        const val = tab.$attrs.value
        if (val === '0') {
          this.activeValue = ''
          this.personType = ''
        } else if (val === '7') {
          this.activeValue = ''
          this.personType = '2'
          this.searchForm.companyId = ''
          this.searchForm.officeId = ''
        } else {
          this.activeValue = val
          this.personType = '1'
        }
        this.refreshList()
      },
      addTabs () {
        this.workerTypeList = []
        this.workerTypeList.push({'label': '全部', 'value': '0'})
        this.$dictUtils.getDictList('worker_type').forEach(item => {
          this.workerTypeList.push(item)
        })
        this.workerTypeList.push({'label': '游客', 'value': '7'})
      },
      showTabs () {
        this.addTabs()
        this.showButton = false
        this.disableButton = true
      },
      disableTabs () {
        this.workerTypeList = []
        this.showButton = true
        this.disableButton = false
      },
      // 模板下载
      template () {
        this.rosterService.template().then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res.data, '花名册导入模板')
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      },
      // 自定义服务端导入
      importMethod ({ file }) {
        // 处理表单
        const formBody = new FormData()
        formBody.append('file', file)
        this.loading = true
        this.rosterService.importExcel(formBody).then(result => {
          this.loading = false
          this.refreshList()
          this.$message.success(result.data)
        }).catch(() => {
          this.refreshList()
          this.loading = false
        })
      },
      queryAllPost () {  //  查询所有岗位
        this.postService.list({current: 1, size: -1}).then(({data}) => {
          this.postList = data.records
        })
      },
      // 自定义服务端导出
      exportMethod ({ options }) {
        // 传给服务端的参数
        const params = {
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm,
          filename: options.filename,
          sheetName: options.sheetName,
          isHeader: options.isHeader,
          original: options.original,
          mode: options.mode,
          selectIds: options.mode === 'selected' ? options.data.map(item => item.id) : [],
          exportFields: options.columns.map(column => column.property)
        }
        return this.rosterService.exportFile(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res.data, options.filename)
        }).catch(function (err) {
          if (err.response) {
            console.log(err.response)
          }
        })
      }
    }
  }
</script>
