<template>
	<div class="page">
		<el-form :inline="true"  v-if="searchVisible" class="query-form m-b-10" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
			<!-- 搜索框-->
			<el-form-item  label="申请人" prop="createById">
				<UserSelectSignatory style="width: 100%" ref="userSelect2" :limit="1"
									 :readonly="true" :modelValue="searchForm.createById"
									 @update:modelValue='(value) => {searchForm.createById = value}'></UserSelectSignatory>			</el-form-item>
			<el-form-item   prop="officeId" label="申请人部门">
				<SelectTree
					ref="officeTree"
					:props="{
                  value: 'id',             // ID字段名
                  label: 'name',         // 显示名称
                  children: 'children'    // 子级字段名
                }"

					:url="`/system-server/sys/office/treeData?type=2`"
					:value="searchForm.officeId"
					size="default"
					:accordion="true"
					@getValue="(value) => {searchForm.officeId=value}"/>
			</el-form-item>

			<el-form-item  label="申请时间" prop="createDates">
				<el-date-picker
					placement="bottom-start"
					format="YYYY-MM-DD"
					value-format="YYYY-MM-DD"
					v-model="searchForm.createDates"
					type="daterange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>

			<el-form-item>
<!--				<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>
			</el-form-item>
		</el-form>
		<div class="jp-table top" style="">
			<vxe-toolbar :refresh="{query: refreshList}" ref="toolbarRef" export custom>
				<template #buttons>
					<el-button v-if="hasPermission('monthly:add')" :disabled="isAdmin" type="primary" icon="el-icon-plus" @click="add()">新建</el-button>
				</template>
				<template #tools>
					<vxe-button
						text
						type="primary"
						: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="monthlyTable"
					show-header-overflow
					show-overflow
					highlight-hover-row
					:menu-config="{}"
					@sort-change="sortChangeHandle"
					:export-config="{
									remote: true,
									filename: `嘉溢月报数据${moment(new Date()).format('YYYY-MM-DD')}`,
									sheetName: `嘉溢月报数据${moment(new Date()).format('YYYY-MM-DD')}`,
									exportMethod: exportMethod,
									types: ['xls'],
									modes: ['current', 'selected', 'all']
								  }"
					: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="monthDate"></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)">{{scope.row.name}}</el-link>
						</template>
					</vxe-column>
					<vxe-column min-width="160" align="center" title="申请人" field="createName"></vxe-column>
					<vxe-column min-width="160" align="center" title="申请人部门" field="officeName"></vxe-column>
					<vxe-column min-width="160" align="center" title="申请时间" field="createTime"></vxe-column>
					<vxe-column title="操作" width="150px" fixed="right" align="center">
						<template  #default="scope">
							<div v-if="isJyAdmin">
								<el-button  size="small" text type="primary" v-if="hasPermission('admin:edit') && isJyAdmin"  @click="adminEdit(scope.row)">修改</el-button>
								<el-button text type="primary" size="small" v-if="hasPermission('admin:del') && isJyAdmin" @click="del(scope.row.id)">删除</el-button>
							</div>
							<div v-else>
								<el-button  size="small" text type="primary" v-if="hasPermission('monthly:edit') &&scope.row.createById === $store.state.user.id && !scope.row.isDisabled"  @click="edit(scope.row)">修改</el-button>
								<el-button text type="primary" size="small" v-if="hasPermission('monthly:del') &&scope.row.createById === $store.state.user.id && !scope.row.isDisabled"  @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>
			<MonthlyForm ref="monthlyForm" @refreshList="refreshList"></MonthlyForm>
	</div>

</template>

<script>
	import UserSelect from '@/components/userSelect'
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
	import MonthlyService from '@/api/jy/MonthlyService'
	import taskService from '@/api/flowable/taskService'
	import processService from '@/api/flowable/processService'
	import userService from '@/api/sys/userService'
	import pick from 'lodash.pick'
	import SupplierChooseForm from '@/views/materialManagement/supplier/SupplierChooseForm'
	import UserSelectSignatory from '../workClientInfo/clientUserSelect'
	import MonthlyForm from './MonthlyForm'
	export default {
		data () {
			return {
				dialogTableVisible:false,
				searchVisible: true,
				showHideItem: false,
				showHideIcon: 'el-icon-arrow-down',
				showHideName: '展示',
				num: 0,
				searchForm: {
					projectId: '',
					projectName: '',
					outMen: '',
					officeId: '',
					createById: '',
					createDates:[],
					targetCity:''
				},
				dataList: [],
				tablePage: {
					total: 0,
					currentPage: 1,
					pageSize: 10,
					orders: []
				},
				tableKey: '',
				loading: false,
				processDefinitionId: '',
				procDefKey: '',
				isAdmin: false,
				create: '',
				gridData:[],
				typeData:[],
				isJyAdmin:false
			}
		},
		MonthlyService:null,
		created () {
			this.monthlyService=new MonthlyService()
		},
		components: {
			SelectTree,
			UserSelect,
			SupplierChooseForm,
			UserSelectSignatory,
			MonthlyForm,
		},
		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.monthlyTable;
				const $toolbar = this.$refs.toolbarRef;
				$table.connect($toolbar);
			})
			this.refreshList()
		},
		activated () {
			this.refreshList()
		},
		methods: {
			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.monthlyForm.init('add','')
			},
			// 修改
			edit (row) {
				this.$refs.monthlyForm.init('edit',row.id)
			},
			// 查看
			view (row) {
				this.$refs.monthlyForm.init('view',row.id);
			},
			// 查询当前用户是否是管理员用户
			checkIsAdmin () {
				userService.is().then((data) => {
					this.isAdmin = data
				})
			},
			// 获取数据列表
			refreshList () {
				this.loading = true
				this.monthlyService.list({
					'current': this.tablePage.currentPage,
					'size': this.tablePage.pageSize,
					'orders': this.tablePage.orders,
					...this.searchForm
				}).then((data) => {
					console.log('x',data.records)
					this.dataList = data.records
					this.tablePage.total = data.total
					this.tableKey = Math.random()
					this.updateDisplayedList();
					this.loading = false
				})
				this.checkIsAdmin()
				this.checkIsJyAdmin()
				processService.getByName('嘉溢-文印申请').then((data) => {
					if (!this.commonJS.isEmpty(data.id)) {
						this.processDefinitionId = data.id
						this.procDefKey = data.key
					}
				})
			},
			updateDisplayedList() {
				this.dataList = this.itemsWithDisabledButtons();
			},
			itemsWithDisabledButtons() {
				const today = new Date();
				const currentMonth = new Date(today.getFullYear(), today.getMonth(), 1); // 本月第一天
				const currentMonthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0); // 本月最后一天
				const isAfter25th = today.getDate() > 25; // 当前日期是否在本月25号之后

				return this.dataList.map(item => {
					let formattedMonthDate = item.monthDate.replace(/年|月/g, '') // 替换'年'和'月'为'-'
						.padStart(6, '0'); // 确保是8位数字，前面用0填充

					const monthDate = new Date(formattedMonthDate.slice(0, 4) + '-' + formattedMonthDate.slice(4, 6) + '-' + '01'); // 解析为Date对象，并设置为该月的第一天

					// 判断是否需要禁用按钮
					const isDisabled = (
						monthDate < currentMonth // 在本月之前
						|| (monthDate.getFullYear() === currentMonth.getFullYear() && monthDate.getMonth() === currentMonth.getMonth() && isAfter25th) // 本月但当前日期在25号之后
					);

					return {
						...item,
						isDisabled,
					};
				});
			},

			//判断当前登陆人是否是admin
			checkIsJyAdmin(){
				userService.checkIsJyAdmin().then((data)=>{
					this.isJyAdmin = data
				})
			},
			// 当前页
			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()
			},
			// 删除
			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
					this.monthlyService.delete(ids).then((data) => {
						this.$message.success(data)
						this.refreshList()
						this.loading = false
					})
				})
			},
			resetSearch () {
				this.$refs.searchForm.resetFields()
				this.searchForm.projectId = '' // 重置时清空项目id
				this.refreshList()
			},


			adminEdit(row){
				this.$refs.monthlyForm.init('edit',row.id);
			},
			// 自定义服务端导出
			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 this.monthlyService.exportFile(params).then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadExcel(res, options.filename+ ".xls")
				}).catch(function (err) {
					if (err.response) {
						console.log(err.response)
					}
				})
			},




		}
	}
</script>
