<template>
	<splitpanes class="default-theme">
		<pane size="20">
			<el-container class="jp-container">
				<el-header class="m-p-13-15">
					<el-input
						placeholder="请输入关键字过滤"
						clearable
						v-model="filterText"
					>
					</el-input>
				</el-header>
				<el-main class="nopadding">
					<el-tree
						class="filter-tree"
						: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"
					>
						<template #default="{ node, data }">
							<span class="custom-tree-node el-tree-node__label">
								<span class="label">
									<el-icon class="m-r-5">
										<qiye
											v-if="data.type === '1'"
											:style="{
												color:
													$TOOL.data.get(
														'IS_PRIMARY_TENANT'
													) &&
													data.tenantDTO &&
													$utils.getTenantColorById(
														data.tenantDTO.id
													),
											}"
										></qiye>
										<bumen
											v-else
											:style="{
												color:
													$TOOL.data.get(
														'IS_PRIMARY_TENANT'
													) &&
													data.tenantDTO &&
													$utils.getTenantColorById(
														data.tenantDTO.id
													),
											}"
										></bumen>
									</el-icon>
									{{ node.label }}
								</span>
							</span>
						</template>
					</el-tree>
				</el-main>
			</el-container>
		</pane>
		<pane size="80">
			<el-container class="jp-container">
				<el-header v-if="searchVisible">
					<div class="left-panel">
						<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="practiceOffice">-->
<!--								<SelectTree-->
<!--									ref="officeTree"-->
<!--									:props="{-->
<!--                value: 'id',             // ID字段名-->
<!--                label: 'name',         // 显示名称-->
<!--                children: 'children'    // 子级字段名-->
<!--              }"-->
<!--									:url="`/system-server/sys/office/treeData?type=2`"-->
<!--									:value="searchForm.practiceOffice"-->
<!--									:clearable="true"-->
<!--									:accordion="true"-->
<!--									size="default"-->
<!--									@getValue="(value,label) => {searchForm.practiceOffice=value}"/>-->
<!--							</el-form-item>-->
							<el-form-item label="实习时间" prop="createDates">
								<el-date-picker
									style = "width: 300px"
									placement="bottom-start"
									format="YYYY-MM-DD"
									value-format="YYYY-MM-DD"
									v-model="searchForm.createDates"
									type="datetimerange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期">
								</el-date-picker>
							</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 v-if="showHideItem" label="性别" prop="sex">
								<el-select v-model="searchForm.sex" placeholder="请选择" style="width:100%;" clearable>
									<el-option
										v-for="item in $dictUtils.getDictList('sex')"
										:key="item.value"
										:label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item v-if="showHideItem" label="身份证号码" prop="idCard">
								<el-input v-model="searchForm.idCard" placeholder="请输入身份证号码" clearable></el-input>
							</el-form-item>
							<el-form-item v-if="showHideItem" label="就读/毕业院校" prop="graduatedFrom">
								<el-input v-model="searchForm.graduatedFrom" placeholder="请输入就读/毕业院校" clearable></el-input>
							</el-form-item>
							<el-form-item v-if="showHideItem" label="专业" prop="speciality">
								<el-input v-model="searchForm.speciality" placeholder="请输入专业" clearable></el-input>
							</el-form-item>
							<!--<el-form-item v-if="showHideItem" label="QQ号/微信号" prop="qqNum">
								<el-input v-model="searchForm.qqNum" placeholder="请输入QQ号/微信号" clearable></el-input>
							</el-form-item>-->
							<el-form-item v-if="showHideItem" label="实习单位名称" prop="practiceUnitName">
								<el-input v-model="searchForm.practiceUnitName" placeholder="请输入实习单位名称" clearable></el-input>
							</el-form-item>
							<el-form-item v-if="showHideItem" label="项目经理" prop="projectManager">
								<UserSelect2 :limit='1' :modelValue="searchForm.projectManager" @update:modelValue='(value, label) => {searchForm.projectManager = value}'></UserSelect2>
							</el-form-item>
						</el-form>
					</div>
					<div class="right-panel">
						<el-button type="default" @click="showHide" :icon="showHideIcon">{{showHideName}}</el-button>
						<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
						<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
					</div>
				</el-header>
				<el-main class="nopadding page2">
					<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="add()">新建</el-button>
							</template>
							<template #tools>
								<vxe-button
									type="text"
									:title="
										searchVisible ? '收起检索' : '展开检索'
									"
									icon="vxe-icon-search"
									class="tool-btn"
									@click="searchVisible = !searchVisible"
								></vxe-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">
									<template #default="scope">
										{{$dictUtils.getDictLabel('sys_nation', scope.row.nation, '')}}
									</template>
								</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="160" align="center" title="所属公司" field="practiceUnitName"></vxe-column>
								<vxe-column min-width="160" align="center" title="所属部门" field="departmentName"></vxe-column>
								<vxe-column min-width="160" align="center" title="项目经理" field="projectManagerName"></vxe-column>
								<vxe-column min-width="160" align="center" title="实习开始时间" field="practiceStartDay"></vxe-column>
								<vxe-column min-width="160" align="center" title="实习结束时间" field="practiceCompleteDay"></vxe-column>
								<vxe-column min-width="160" align="center" title="实习状态" field="practiceStatus">
									<template #default="scope">
										{{$dictUtils.getDictLabel('practice_type', scope.row.practiceStatus, '')}}
									</template>
								</vxe-column>
								<vxe-column min-width="100" title="状态" fixed="right" align="center" field="type">
									<template #default="scope">
										<el-button @click="detail(scope.row)" :type="$dictUtils.getDictLabel('status_info', scope.row.type, '')" effect="dark" >{{$dictUtils.getDictLabel("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('register:edit')">-->
										<el-button v-if="hasPermission('register:edit') &&(
                      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="hasPermission('register:del') && (
                      scope.row.type === '5' || scope.row.type === '4' || scope.row.type === '3')" text type="primary" @click="del(scope.row.id)">删除</el-button>
										<!--              </div>-->
										<!--				<el-button v-if="hasPermission('reimburseRegister:edit') && scope.row.createById === $store.state.user.id && (scope.row.type === '1' || scope.row.type === '3' )" text type="primary"   @click="editForm(scope.row)">修改</el-button>-->
										<!--				<el-button v-if="hasPermission('reimburseRegister:edit') && scope.row.createById === $store.state.user.id && (scope.row.type === '2')" text type="primary"  @click="reback(scope.row)">撤回</el-button>-->
									</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>
				</el-main>
			</el-container>
		</pane>
	</splitpanes>
<!--  <div class="page">-->

	  <RegistrationEditForm ref="registrationEditForm" @refreshList="refreshList"></RegistrationEditForm>
<!--  </div>-->
</template>

<script>
	import { Splitpanes, Pane } from "splitpanes";
	import "splitpanes/dist/splitpanes.css";
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
  import registerService from '@/api/human/register/RegisterService'
  import processService from '@/api/flowable/ProcessService'
  import userService from '@/api/sys/UserService'
  import taskService from '@/api/flowable/TaskService'
  import RegistrationEditForm from './RegistrationEditForm'
  import pick from "lodash.pick";
	import UserSelect2 from '@/components/userSelect'
	import officeService from "@/api/sys/officeService";
  export default {
    data () {
      return {
		  showHideItem: false,
		  showHideIcon: 'el-icon-arrow-down',
		  showHideName: '展示',
        num: 0,
        searchForm: {
			name: '',
			practiceOffice: '',
			mobilePhone: '',
			sex:'',
			idCard:'',
			graduatedFrom:'',
			speciality:'',
			qqNum:'',
			practiceUnitName:'',
			projectManager:'',
			createDates: [],
			companyId:"",
        },
        dataList: [],
        tablePage: {
          total: 0,
          currentPage: 1,
          pageSize: 10,
          orders: []
        },
        tableKey: '',
        loading: false,
        processDefinitionAuditId: '',
        procDefAuditKey: '',
        isAdmin: false,
        create: '',
        haveProjectIds: '',
		  filterText: "",
		  officeTreeData: [],
		  searchVisible: true,
      }
    },
    created () {
    },
    components: {
		SelectTree,
		RegistrationEditForm,
		UserSelect2,
		Splitpanes,
		Pane,
    },
	  watch: {
		  filterText(val) {
			  this.$refs.officeTree.filter(val);
		  },
	  },
    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()
		this.refreshTree();
    },
    activated () {
      this.refreshList()
    },
    methods: {
		filterNode(value, data) {
			if (!value) return true;
			return data.name.indexOf(value) !== -1;
		},
		handleNodeClick(data) {
			if (data.type === "1") {
				this.searchForm.companyId = data.id;
				this.searchForm.practiceOffice = "";
			} else {
				this.searchForm.companyId = "";
				this.searchForm.practiceOffice = data.id;
			}
			this.refreshList();
		},
		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 = '展示'
			}
		},
      // 新增
      add () {
		  this.$refs.registrationEditForm.init('add', '')
      },
		// 查看
		view (id) {
			this.$refs.registrationEditForm.init('view', id)
		},
      // 修改
      edit (id) {
        id = id || this.$refs.clientTable.getCheckboxRecords().map(item => {
          return item.id
        })[0]
		  this.$refs.registrationEditForm.init('edit', id)
      },
      // 查询当前用户是否是管理员用户
      checkIsAdmin () {
        userService.is().then((data) => {
          this.isAdmin = data
        })
      },
		refreshTree() {
			officeService.treeData().then((data) => {
				this.officeTreeData = data;
			});
		},
      // 获取数据列表
      refreshList () {
        this.loading = true
		  registerService.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
          }
        })
      },
      // 当前页
      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.searchForm.practiceOffice = "";
		  this.searchForm.companyId = "";
		  this.filterText = "";
		  this.$refs.officeTree.setCurrentKey(null);
        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.procDefAuditKey,
					  status: 'startAndHold',
					  title: tabTitle,
					  formType: data.formType,
					  formUrl: data.formUrl,
					  formTitle: processTitle,
					  businessId: 'false',
					  isShow: false,
					  routePath: '/human/practice/register/RegistrationList'
				  }
			  })
		  })
      },
		editForm (row) {
			// 暂存修改
			let status = ''
			if (row.type === '1') {
				status = 'startAndHold'
			}
			// 撤回或者驳回修改
			if (row.type === '3') {
				status = 'startAndClose'
			} else if (row.status === '4') {
				status = 'reapplyFlag'
			}
			// 读取流程表单
			let tabTitle = `发起流程【实习登记】`
			let processTitle = `${this.userName} 在 ${this.moment(new Date()).format('YYYY-MM-DD HH:mm')} 发起了 [实习登记]`
			taskService.getTaskDef({ procDefId: this.processDefinitionAuditId,
				businessId: row.id,
				businessTable: 'human_resources_practice_registration',
				status: status
			}).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.procDefAuditKey,
						status: status,
						title: tabTitle,
						formType: data.formType,
						formUrl: data.formUrl,
						formTitle: processTitle,
						businessTable: 'human_resources_practice_registration',
						businessId: row.id,
						isShow: false,
						routePath: '/human/practice/register/RegistrationList'
					}
				})
			})
		},
		// 查看实习登记流程结果
		detail (row) {
			if (row.reviewStatus !== '0' && row.reviewStatus !== '1') {
				// 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 registerService.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
				registerService.remove(ids).then((data) => {
					this.$message.success(data)
					this.refreshList()
					this.loading = false
				})
			})
		},
		reback (row) {
			this.$confirm(`确定撤回流程吗?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				processService.revokeProcIns(row.procInsId).then((data) => {
					let param = {type: '3', id: row.id}
					registerService.updateStatusById(param)
					this.$message.success('回退成功')
					this.refreshList()
				})
			})
		},
    }
  }
</script>
