<template>
  <div class="page">
    <el-form :inline="true" class="query-form m-b-10" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
      <!-- 搜索框-->
		<el-form-item label="姓名" prop="name">
			<el-input v-model="searchForm.name" placeholder="请输入姓名" clearable></el-input>
		</el-form-item>
		<el-form-item label="所属部门" prop="department">
			<SelectTree
				ref="officeTree"
				:props="{
                value: 'id',             // ID字段名
                label: 'name',         // 显示名称
                children: 'children'    // 子级字段名
              }"
				:url="`/system-server/sys/office/treeData?type=2`"
				:value="searchForm.department"
				:clearable="true"
				:accordion="true"
				size="default"
				@getValue="(value,label) => {searchForm.department=value}"/>
		</el-form-item>
		<el-form-item label="联系电话" prop="mobilePhone">
			<el-input v-model="searchForm.mobilePhone" placeholder="请输入联系电话" clearable></el-input>
		</el-form-item>

      <el-form-item>
        <el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
        <el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="jp-table top" style="">
      <vxe-toolbar :refresh="{query: refreshList}" ref="toolbarRef" export custom>
        <template #buttons>
          <el-button type="primary" icon="el-icon-plus" @click="start()">新建</el-button>
        </template>
      </vxe-toolbar>
      <div style="height: calc(100% - 90px)">
        <vxe-table
          border="inner"
          auto-resize
          resizable
          height="auto"
          :loading="loading"
          ref="clientTable"
          show-header-overflow
          show-overflow
          highlight-hover-row
          :print-config="{}"
          :export-config="{
                    remote: true,
                    filename: `入职登记信息${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: '入职登记信息',
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
          :menu-config="{}"
          @sort-change="sortChangeHandle"
          :sort-config="{remote:true}"
          :data="dataList"
          :checkbox-config="{}">
          <vxe-column type="seq" width="60" title="序号"></vxe-column>
          <vxe-column min-width="160" align="center" title="姓名" field="name">
			  <template #default="scope">
				  <el-link  type="primary" :underline="false" @click="view(scope.row.id)">{{scope.row.name}}</el-link>
			  </template>
		  </vxe-column>
          <vxe-column min-width="160" align="center" title="政治面貌" field="politicalOutlook">
			  <template #default="scope">
				  {{$dictUtils.getDictLabel('political_outlook', scope.row.politicalOutlook, '')}}
			  </template>
		  </vxe-column>
          <vxe-column min-width="160" align="center" title="民族" field="nation"></vxe-column>
          <vxe-column min-width="160" align="center" title="所属部门" field="departmentName"></vxe-column>
          <vxe-column min-width="160" align="center" title="联系电话" field="mobilePhone"></vxe-column>
          <vxe-column min-width="160" align="center" title="毕业院校" field="graduatedFrom"></vxe-column>
			<vxe-column min-width="100" title="状态" fixed="right" align="center" field="type">
				<template #default="scope">
					<el-button v-if="scope.row.processType === '1'" @click="detail(scope.row)" :type="$dictUtils.getDictLabel('status_info', scope.row.type, '')" effect="dark" >{{$dictUtils.getDictLabel("status", scope.row.type, '未开始')}} </el-button>
					<el-button v-else @click="detail(scope.row)" :type="$dictUtils.getDictLabel('human_status_info', scope.row.type, '')" effect="dark" >{{$dictUtils.getDictLabel("human_status", scope.row.type, '未开始')}} </el-button>
				</template>
			</vxe-column>

          <vxe-column title="操作" width="200px" fixed="right" align="center">
            <template  #default="scope">
              <div v-if="hasPermission('enrollmentRegistration:edit')">
                <el-button v-if="
                      scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3'" text type="primary" @click="edit(scope.row.id)">修改</el-button>
                <el-button v-if="
                      scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3'" text type="primary" @click="del(scope.row.id)">删除</el-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          background
          :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>
	  <EnrollmentRegistrationEditForm ref="enrollmentRegistrationEditForm" @refreshDataList="refreshList"></EnrollmentRegistrationEditForm>
  </div>
</template>

<script>
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
	import EnrollmentRegistrationEditForm from './EnrollmentRegistrationEditForm'
  import enrollmentRegistrationService from '@/api/human/enrollment/EnrollmentRegistrationService'
  import processService from '@/api/flowable/ProcessService'
  import userService from '@/api/sys/UserService'
  import taskService from '@/api/flowable/TaskService'
  import pick from "lodash.pick";
  export default {
    data () {
      return {
        num: 0,
        searchForm: {
          name: '',
			mobilePhone: '',
			department: '',
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        tableKey: '',
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
		processDefinitionAuditId2: '',
        procDefAuditKey2: '',
        isAdmin: false,
        create: '',
        haveProjectIds: ''
      }
    },
    created () {
    },
    components: {
		SelectTree,
		EnrollmentRegistrationEditForm,
    },
    computed: {
      userName () {
        return this.$store.state.user.name
      },
      user () {
        this.createName = this.$store.state.user.name
        return this.$store.state.user
      }
    },
    mounted () {
		this.$nextTick(() => {
			//将表格和工具栏进行关联
			const $table = this.$refs.clientTable;
			const $toolbar = this.$refs.toolbarRef;
			$table.connect($toolbar);
		})
      this.refreshList()
    },
    activated () {
      this.refreshList()
    },
    methods: {
      // 新增
      add () {
      },
		// 查看
		view (id) {
			this.$refs.enrollmentRegistrationEditForm.init('view', id)
		},
      // 修改
      edit (id) {
        id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
		  this.$refs.enrollmentRegistrationEditForm.init('edit', id)
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
      // 获取数据列表
      refreshList () {
        this.loading = true
		  enrollmentRegistrationService.list({
          'current': this.tablePage.currentPage,
          'size': this.tablePage.pageSize,
          'orders': this.tablePage.orders,
          ...this.searchForm
        }).then((data) => {
          this.dataList = data.records
          this.tablePage.total = data.total
          this.tableKey = Math.random()
          this.loading = false
        })
        this.checkIsAdmin()
        processService.getByName('员工入职').then((data) => {
          if (!this.commonJS.isEmpty(data.id)) {
            this.processDefinitionAuditId = data.id
            this.procDefAuditKey = data.key
          }
        })
		  processService.getByName('完善个人信息').then((data) => {
			  if (!this.commonJS.isEmpty(data.id)) {
				  this.processDefinitionAuditId2 = data.id
				  this.procDefAuditKey2 = data.key
			  }
		  })
      },
      // 当前页
      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()
      },
      resetSearch () {
        this.$refs.searchForm.resetFields()
        this.refreshList()
      },
      start () {
		  // 读取流程表单
		  let tabTitle = `发起流程【员工入职】`
		  let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [员工入职]`
		  taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
			  status: 'startAndHold'}).then((data) => {
			  this.$router.push({
				  path: '/flowable/task/TaskForm',
				  query: {
					  ...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
					  procDefId: this.processDefinitionAuditId,
					  procDefKey: this.procDefKey,
					  status: 'startAndHold',
					  title: tabTitle,
					  formType: data.formType,
					  formUrl: data.formUrl,
					  formTitle: processTitle,
					  businessId: 'false',
					  isShow: false,
					  routePath: '/human/enrollment/registration/EnrollmentRegistrationList'
				  }
			  })
		  })
      },
		// 查看员工入职流程结果
		detail (row) {
			if (row.reviewStatus !== '0' && row.reviewStatus !== '1') {

				if (this.commonJS.isNotEmpty(row.processType) && row.processType == '1') {
					//信息完善流程
					taskService.getTaskDef({
						procInsId: row.procInsId,
						procDefId: this.processDefinitionAuditId2
					}).then((data) => {
						this.$router.push({
							path: '/flowable/task/TaskFormDetail',
							query: {
								...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
								isShow: 'false',
								readOnly: true,
								title: '个人信息完善' + '流程详情',
								formTitle: '个人信息完善' + '流程详情',
								businessId: row.id,
								status: 'reback'
							}
						})
					})
				} else {
					// eslint-disable-next-line eqeqeq
					taskService.getTaskDef({
						procInsId: row.procInsId,
						procDefId: this.processDefinitionAuditId
					}).then((data) => {
						this.$router.push({
							path: '/flowable/task/TaskFormDetail',
							query: {
								...pick(data, 'formType', 'formUrl', 'procDefKey', 'taskDefKey', 'procInsId', 'procDefId', 'taskId', 'status', 'title'),
								isShow: 'false',
								readOnly: true,
								title: '员工入职' + '流程详情',
								formTitle: '员工入职' + '流程详情',
								businessId: row.id,
								status: 'reback'
							}
						})
					})
				}


			}
		},
      // 自定义服务端导出
      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.map(item => item.id) : [],
          exportFields: options.columns.map(column => column.property)
        }
        return enrollmentRegistrationService.exportExcel(params).then((res) => {
          // 将二进制流文件写入excel表，以下为重要步骤
          this.$utils.downloadExcel(res, options.filename)
        }).catch(function (err) {
          if (err.response) {
            // console.log(err.response)
          }
        })
      },
		// 删除
		del (id) {
			let ids = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
				return item.id
			}).join(',')
			this.$confirm(`确定删除所选项吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.loading = true
				enrollmentRegistrationService.remove(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
			})
		},
    }
  }
</script>
