<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-row>
			<el-col :span="24">

				<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'"
						 label-width="135px" @submit.native.prevent>

					<el-divider content-position="left"><i class="el-icon-document"></i> 项目信息</el-divider>
					<el-row  :gutter="0">
						<el-col :span="12">
							<el-form-item label="报告号" prop="reportNo"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.reportNo" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="报告日期" prop="reportDate"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.reportDate" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="合同编号" prop="contractNo"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.contractNo" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="合同名称" prop="contractName"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.contractName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="委托方" prop="clientName"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.clientName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="项目编号" prop="projectNumber"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.projectNumber" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="项目名称" prop="projectName"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.projectName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="归档申请人" prop="applyUserName"
										  :rules="[
                   ]">
								<el-input :disabled="true" v-model="inputForm.applyUserName" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="归档时间" prop="applyDates"
										  :rules="[
                   ]">
								<el-date-picker
									:disabled="true"
									style="width: 100%;"
									v-model="inputForm.applyDates"
									type="date"
									value-format="YYYY-MM-DD"
									placeholder="选择归档时间">
								</el-date-picker>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="24">
							<el-form-item label="说明" prop="onlineRemarks"
										  :rules="[
                   ]">
								<el-input type="textarea"
										  maxlength="200" placeholder="请输入说明"
										  show-word-limit v-model="inputForm.onlineRemarks"></el-input>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form >
				<el-divider content-position="left"><i class="el-icon-document"></i>
					<span>文件信息</span>
				</el-divider>
				<el-row  :gutter="15" >
					<el-col :span="24">
						<vxe-table
							border
							show-overflow
							ref="clientTable"
							class="vxe-table-element"
							style="margin-left: 5em"
							:row-config="{keyField: 'id'}"
							:column-config="{resizable: true}"
							:tree-config="{transform: true, expandAll: true}"
							:key="tableKey"
							:data="tableData">
							<vxe-column field="name" title="文件要求" width="240px" tree-node>
								<template #default="scope">
							<span style="font-weight: bold"
								  v-if="scope.row.parentId === '0'"
							>{{ scope.row.name }}
							</span>
									<span
										v-if="scope.row.parentId !== '0' && scope.row.mustFlag === 1"
									><span style="color: red;font-weight: bold">* </span>{{ scope.row.name }}
							</span>
									<span
										v-if="scope.row.parentId !== '0' && scope.row.mustFlag === 0"
									>{{ scope.row.name }}
							</span>
								</template>
							</vxe-column>
							<vxe-column field="attachmentName" title="文件描述/文件名称" show-overflow="false">
								<template #default="scope">
							<span
								v-if="scope.row.levelFlag === 2"
							>
								<span style="font-weight: bold">文件格式及大小：{{ scope.row.size }}</span>
								<br>
								<span>{{ scope.row.type }}</span>
							</span>
									<div v-if="ifName(scope.row) === true">
										<el-image
											style="width: 30px; height: 30px;padding-top: 4px;"
											:src="scope.row.lsUrl"
											:preview-src-list="[scope.row.lsUrl]"
											:preview-teleported="true"
										></el-image>
									</div>
									<div v-else>
										<el-link v-if="scope.row.levelFlag === 3"  type="primary" :underline="false" @click="showFile(scope.row)">{{scope.row.attachmentName}}</el-link>
									</div>
								</template>
							</vxe-column>
							<vxe-column field="workAttachmentType" width="100px" title="文件类型"></vxe-column>
							<vxe-column field="createDate" title="上传时间" width="100px"></vxe-column>
							<vxe-column field="fileSize" width="100px" title="文件大小(M)">
								<template #default="scope">
									{{getSize(scope.row.fileSize)}}
								</template>
							</vxe-column>

							<vxe-column
								title="操作"
								width="100px"
								fixed="right"
								align="center"
							>
								<template #default="scope">
									<el-button
										v-if="scope.row.levelFlag === 2"
										type="primary"
										size="small"
										:disabled="status === 'audit' ||status === 'taskFormDetail'|| method ==='view'"
										@click="openFileForm(scope.row.id,this.inputForm.id)"
									>编辑</el-button>
									<el-button
										v-if="scope.row.levelFlag === 3"
										type="info"
										size="small"
										@click="toHref(scope.row)" >下载</el-button>

								</template>
							</vxe-column>
						</vxe-table>
					</el-col>
				</el-row>
				<FileForm ref="fileForm" @getFiles="getFiles"></FileForm>
			</el-col>
		</el-row>
	</div>
</template>

<script>
	import moment from 'moment';
	import FileForm from '@/views/cw/reportManagement/reportReview/FileForm'
	import OSSSerivce, {
		// eslint-disable-next-line no-unused-vars
		beforeAvatarUpload,
		// eslint-disable-next-line no-unused-vars
		openWindowOnUrl,
		// eslint-disable-next-line no-unused-vars
		toHref
	} from '@/api/sys/OSSService'
	import reportOnlineArchivingService from '@/api/cw/reportManagement/ReportOnlineArchivingService'
	import projectReportService from '@/api/cw/reportManagement/ProjectReportService'
	import CommonApi from '@/api/cw/common/CommonApi'
	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				tableKey: '',
				tableData: [],
				detailKey: '',
				title: '',
				method: '',
				loading: false,
				inputForm: {
					reviewBy: '',
					onlineArchivingProcInsId: '',
					onlineArchivingId: '',
					projectId: '',
					reportNo: '',
					reportDate: '',
					contractNo: '',
					contractName: '',
					clientName: '',
					projectNumber: '',
					applyDates: new Date(),
					onlineRemarks: '',
					applyUserName: this.$store.state.user.name,
					applyUserId: this.$store.state.user.id,
					projectName: '',
					createBy: {
						id: '',
						name: this.$store.state.user.name
					},
				},
				keyWatch: '',
			}
		},
		commonApi: null,
		created () {
			this.commonApi = new CommonApi()
		},
		computed: {
			bus: {
				get () {
					return this.businessId
				},
				set (val) {
					this.businessId = val
				}
			}
		},
		watch: {
			'keyWatch': {
				handler (newVal) {
					if (this.commonJS.isNotEmpty(this.bus)) {
						this.init('', this.bus)
					} else {
						this.$nextTick(() => {
							// this.$refs.inputForm.resetFields()
						})
					}
				}
			},
			'loading': {
				handler (newVal) {
					this.$emit('changeLoading', newVal)
				}
			}
		},
		components: {
			FileForm,
		},
		methods: {
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			init (method, id) {
				console.log('method', method)
				this.method = method
				this.inputForm = {
					reviewBy: '',
					onlineArchivingProcInsId: '',
					onlineArchivingId: '',
					projectId: '',
					reportNo: '',
					reportDate: '',
					contractNo: '',
					contractName: '',
					clientName: '',
					projectNumber: '',
					applyDates: '',
					onlineRemarks: '',
					applyUserName: '',
					applyUserId: '',
					projectName: '',
					createBy: {
						id: '',
						name: this.$store.state.user.name
					},
				}
				this.inputForm.id = id
				this.loading = false
				this.$nextTick(() => {
					// this.$refs.inputForm.resetFields()

					this.loading = true
					projectReportService.queryByIdNew(this.inputForm.id).then((data) => {
						if (data) {
							this.inputForm = this.recover(this.inputForm, data)

							projectReportService.getAttachmentList(data.projectId,this.inputForm.id,'归档').then((data) => {
								this.tableData = data
								this.tableKey = Math.random()
							})

							if (this.commonJS.isEmpty(this.inputForm.applyUserId)) {
								this.inputForm.applyUserId = this.$store.state.user.id
								this.inputForm.applyUserName = this.$store.state.user.name
							}
							if (this.commonJS.isEmpty(this.inputForm.applyDates)) {
								this.inputForm.applyDates = this.moment(new Date()).format('YYYY-MM-DD')
							}

							if (this.status === 'taskFormDetail' || this.status === 'audit') {
								this.method = 'view'
							} else {
								this.method = 'false'
							}
							this.loading = false
						} else {
							projectReportService.queryByOnlineArchivingId(this.inputForm.id).then((data2) => {
								if (data2) {
									this.inputForm = this.recover(this.inputForm, data2)

									projectReportService.getAttachmentList(data2.projectId,this.inputForm.id,'归档').then((data) => {
										this.tableData = data
										this.tableKey = Math.random()
									})

									if (this.commonJS.isEmpty(this.inputForm.applyUserId)) {
										this.inputForm.applyUserId = this.$store.state.user.id
										this.inputForm.applyUserName = this.$store.state.user.name
									}
									if (this.commonJS.isEmpty(this.inputForm.applyDates)) {
										this.inputForm.applyDates = this.moment(new Date()).format('YYYY-MM-DD')
									}

									if (this.status === 'taskFormDetail' || this.status === 'audit') {
										this.method = 'view'
									} else {
										this.method = 'false'
									}
									this.loading = false
								}

							})
						}

					})
				})
			},
			saveForm (callback) {
				this.doSubmit('save', callback)
			},
			startForm (callback) {
				this.loading = true
				if (this.commonJS.isNotEmpty(this.inputForm.id)) {
					reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((data) => {
						if (this.commonJS.isNotEmpty(data.status) && data.status !== '0' && data.status !== '1' && data.status !== '3') { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.doSubmit('start', callback)
						}
					})
				} else {
					this.doSubmit('start', callback)
				}
			},
			async agreeForm (callback) {
				this.loading = true
				await reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((data) => {
					if (data.status !== '2') { // 审核状态不是“待审核”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error()
					} else {
						this.doSubmit('agree', callback)
					}
				})
			},
			reapplyForm (callback) {
				this.loading = true
				reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((data) => {
					if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.doSubmit('reapply', callback)
					}
				})
			},
			// 表单提交
			doSubmit (status, callback) {
				if (status === 'save') {
					// 暂存
					this.inputForm.status = '1'
					this.loading = true
					reportOnlineArchivingService.saveForm(this.inputForm).then((data) => {
						callback(data.businessTable, data.businessId, this.inputForm)
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
					return
				} else if (status === 'start') {
					// 送审  待审核
					this.inputForm.status = '2'
					this.inputForm.assignee = this.inputForm.reviewBy
				} else if (status === 'agree') {
					// 审核同意
					this.inputForm.agreeDate = this.moment(new Date()).format('YYYY-MM-DD')
					this.inputForm.agreeUserId = this.$store.state.user.id
					// this.inputForm.status = '5'
				} else if (status === 'reapply') {
					this.inputForm.status = '2'
					this.inputForm.assignee = this.inputForm.reviewBy
				}
				if (this.commonJS.isEmpty(this.tableData)) {
					this.loading = false
					this.$message.error('附件信息加载中，请稍等!')
					throw new Error('附件信息加载中，请稍等!')
				}
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						if (status === 'agree') {
							console.log('this.inputForm.onlineArchivingProcInsId', this.inputForm.onlineArchivingProcInsId)
							//判断当前节点是哪一个节点
							this.commonApi.getTaskNameByProcInsId(this.inputForm.onlineArchivingProcInsId).then((data) => {
								if (this.commonJS.isNotEmpty(data)) {
									if (data === '报告归档管理员审核') {
										this.inputForm.status = '5'
									} else {
										this.inputForm.status = '2'
									}
								}
								console.log('data', data)
								reportOnlineArchivingService.saveForm(this.inputForm).then((data2) => {
									callback(data2.businessTable, data2.businessId, this.inputForm)
									this.loading = false
								}).catch(() => {
									this.loading = false
								})
							})



						}else{

							this.tableData.forEach(item=>{
								if (item.levelFlag === 2 && item.mustFlag === 1){
									if (item.children.length === 0){
										this.loading = false
										this.$message.error(item.name + '文件未上传')
										throw new Error(item.name + '文件未上传')
									} else {
										item.children.forEach(child => {
											const fileExtension = child.attachmentName.split('.').pop(); // 获取文件后缀名
											const supportedFileTypes = item.type.split(','); // 支持的文件类型数组
											if (!supportedFileTypes.includes(fileExtension)) {
												this.loading = false;
												this.$message.error(child.attachmentName + ' 文件类型不受支持');
												throw new Error(child.attachmentName + ' 文件类型不受支持');
											}
										});
									}
								}
							})

							reportOnlineArchivingService.saveForm(this.inputForm).then((data) => {
								callback(data.businessTable, data.businessId, this.inputForm)
								this.loading = false
							}).catch(() => {
								this.loading = false
							})

						}

					} else {
						this.loading = false
					}
				})
			},
			async updateStatusById (type, callback) {
				this.loading = true
				if (type === 'reject' || type === 'reback') {
					await reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((data) => {
						if (data.status !== '2') { // status的值不等于“审核中”就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error()
						} else {
							if (type === 'reject') {
								reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((review) => {
									console.log('review', review)
									this.rejectOn(callback)
								})
							}
							if (type === 'reback') {
								// 撤回
								let param = {status: '3', id: this.inputForm.onlineArchivingId}
								reportOnlineArchivingService.updateStatusByReportId(param)
							}
						}
					})
				} else if (type === 'hold') {
					reportOnlineArchivingService.queryByReportId(this.inputForm.id).then((data) => {
						if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error()
						} else {
							// 终止
							let param = {status: '1', id: this.inputForm.onlineArchivingId}
							reportOnlineArchivingService.updateStatusByReportId(param).then(() => {
								callback()
								this.loading = false
							})
						}
					})
				}
			},
			// 这个方法是这个之前这个页面的驳回方法，现在粘出来复用
			rejectOn (callback) {
				// 驳回
				let param
				this.inputForm.status = '4'
				param = {status: this.inputForm.status,
					id: this.inputForm.onlineArchivingId,
					needUpdate2: this.inputForm.needUpdate2,
					needUpdate3: this.inputForm.needUpdate3,
					remark2: this.inputForm.remark2,
					remark3: this.inputForm.remark3,
					details: this.inputForm.details
				}
				reportOnlineArchivingService.updateStatusByReportId(param).then(() => {
					this.loading = false
					callback()
				})
			},
			close () {
				this.inputForm = {
					reviewBy: '',
					onlineArchivingProcInsId: '',
					onlineArchivingId: '',
					projectId: '',
					reportNo: '',
					reportDate: '',
					contractNo: '',
					contractName: '',
					clientName: '',
					projectNumber: '',
					applyDates: '',
					onlineRemarks: '',
					applyUserName: '',
					applyUserId: '',
					projectName: '',
					createBy: {
						id: '',
						name: this.$store.state.user.name
					},
				}
			},
			ifName (row) {
				if (this.commonJS.isEmpty(row.attachmentName)) {
					row.attachmentName = '---'
					return false
				}
				let suffix = row.attachmentName.substring(row.attachmentName.lastIndexOf('.') + 1)
				if (suffix === 'jpg' || suffix === 'png' || suffix === 'gif' || suffix === 'bmp' || suffix === 'jpeg') {
					return true
				} else {
					return false
				}
			},
			showFile (row) {
				console.log("showFile",row)
				row.name = row.attachmentName
				openWindowOnUrl(row)
			},
			getSize (value) {
				if (this.commonJS.isEmpty(value)) {
					return ''
				} else {
					let val = parseInt(value)
					let k = 1024
					let sizes = ['B', 'KB', 'MB', 'GB', 'PB', 'TB', 'EB', 'ZB', 'YB']
					let i = Math.floor(Math.log(val) / Math.log(k))
					let result = val / Math.pow(k, i);
					let kb = parseFloat(result.toPrecision(3));
					return kb + '' + sizes[i]
				}
			},
			//测试按钮
			openFileForm(id,typeId){
				console.log('this.id', id )
				this.$refs.fileForm.init("add", id,this.inputForm.projectId)
			},
			toHref (row) {
				console.log("toHref",row)
				toHref(row)
			},
			getFiles(){
				projectReportService.getAttachmentList(this.inputForm.projectId,this.inputForm.id,'归档').then((data) => {
					this.tableData = data
					this.tableKey = Math.random()
				})

			},
		}
	}
</script>
<style scoped>
	/deep/ .el-input-number .el-input__inner {
		text-align: left;
	}

	/deep/ .vxe-select-option {
		padding: 0 .6em;
		max-width: 600px;
		overflow: visible;
		text-overflow: ellipsis;
		white-space: nowrap;
		-webkit-user-select: none;
		-moz-user-select: none;
		-ms-user-select: none;
		user-select: none
	}
</style>
