<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-form size="large" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
				 label-width="170px" @submit.native.prevent>

			<el-row  :gutter="15">
				<el-col :span="24" >
					<el-divider content-position="left"><i class="el-icon-document"></i>
						合同信息
					</el-divider>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同名称" prop="contractName"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.contractName" placeholder="请填写合同名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同金额(元)" prop="contractAmount"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.contractAmount" placeholder="请填写合同金额(元)"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="委托方" prop="primaryLinkman"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.primaryLinkman" placeholder="请填写委托方"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同类型(大类)" prop="contractTypeFirst"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.contractTypeFirst" placeholder="请填写合同类型(大类)"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="合同类型(小类)" prop="contractType"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.contractType" placeholder="请填写合同类型(小类)"></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row  :gutter="15">
				<el-col :span="24" >
					<el-divider content-position="left"><i class="el-icon-document"></i>
						项目基本信息
					</el-divider>
				</el-col>
				<el-col :span="12">
					<el-form-item label="项目名称" prop="projectName"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.projectName" placeholder="请填写项目名称"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="项目所在地" prop="projectPlace"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.projectPlace" placeholder="请填写项目所在地"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="建设地点" prop="buildPlace"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.buildPlace" placeholder="请填写建设地点"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="项目负责人" prop="projectLeader"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.projectLeader" placeholder="请填写项目负责人"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="创建人" prop="createByName"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.createByName" placeholder="请填写创建人"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="创建时间" prop="createTime"
								  :rules="[
			 ]">
						<el-input :disabled="true" v-model="inputForm.createTime" placeholder="请填写创建时间"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" v-if="isBgs">
					<el-form-item label="归档盒号" prop="caseNumber"
								  :rules="[
								  {required: true, message:'归档盒号不能为空', trigger:'change'}

			 ]">
						<el-input :disabled="false" v-model="inputForm.caseNumber" placeholder="请填写归档盒号"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12" v-else>
					<el-form-item label="归档盒号" prop="caseNumber"
								  :rules="[

			 ]">
						<el-input :disabled="true" v-model="inputForm.caseNumber" placeholder="请填写归档盒号"></el-input>
					</el-form-item>
				</el-col>

			</el-row>
			<el-row  :gutter="15">
<!--				<el-button  type="primary"  icon="el-icon-plus" @click="add()">新建</el-button>-->
					<el-col :span="24">
						<el-form-item label="备注" prop="remarks"
									  :rules="[
                 ]">
							<el-input :rows="4" :disabled="status === 'audit' || status === 'taskFormDetail'|| method ==='view'"  show-word-limit maxlength="500" type="textarea" v-model="inputForm.remarks" placeholder="请填写备注"></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="260px" 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>

		<!--        附件-->
<!--		<UpLoadComponent ref="uploadComponent"></UpLoadComponent>-->
		<FileForm ref="fileForm" @getFiles="getFiles"></FileForm>

	</div>
</template>

<script>
	import ProjectInfoService from "@/api/jy/ProjectInfoService";
	import UserSelectSignatory from '../workClientInfo/clientUserSelect'
	import FileForm from './FileForm'
	import UpLoadComponent from '@/views/common/JyArchiveUpLoadComponent'
	import CommonApi from '@/api/cw/common/CommonApi'
	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'
	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				title: '',
				method: '',
				visible: false,
				loading: false,
				inputForm: {
					id: '',
					contractName:'',
					contractAmount:'',
					primaryLinkman:'',
					contractTypeFirst:'',
					contractType:'',
					projectName:'',
					projectPlace:'',
					buildPlace:'',
					projectLeader:'',
					createByName:'',
					createTime:'',
					fileList:[],
					status:'',
					projectId:'',
					remarks:'',
					procInsId:'',
					no:'',
					caseNumber:''
				},
				keyWatch: '',
				tabName:'',
				tableData: [],
				isBgs: false
			}
		},
		ProjectInfoService:null,
		commonApi: null,
		created () {
			this.projectInfoService=new ProjectInfoService()
			this.ossService = new OSSSerivce()
			this.commonApi = new CommonApi()

		},
		computed: {
			bus: {
				get () {
					// this.$refs.uploadComponent.setDividerName('附件')
					return this.businessId

				},
				set (val) {
					this.businessId = val
				}
			}
		},
		watch: {
			'keyWatch': {
				handler (newVal) {
					console.log('dsad')
					if (this.bus) {
						console.log('dsad',this.bus)
						if (this.bus !== 'false') {
							this.init('', this.bus)
						}
					} else {
						this.$nextTick(() => {
							this.$refs.inputForm.resetFields()
						})
					}
				}
			},
			'loading': {
				handler (newVal) {
					this.$emit('changeLoading', newVal)
					// this.$refs.uploadComponent.changeLoading(newVal)
				}
			}
		},
		components: {
			UserSelectSignatory,
			UpLoadComponent,
			FileForm,
			OSSSerivce,
		},
		methods: {
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			init (method, id,tabName) {
				this.tabName = tabName
				this.method = method
				console.log('method', method)
				this.inputForm = {
					id: '',
					contractName:'',
					contractAmount:'',
					primaryLinkman:'',
					contractTypeFirst:'',
					contractType:'',
					projectName:'',
					projectPlace:'',
					buildPlace:'',
					projectLeader:'',
					createByName:'',
					createTime:'',
					fileList:[],
					status:'',
					projectId:'',
					remarks:'',
					procInsId:'',
					no:'',
					caseNumber:''
				}
				this.inputForm.id = id
				this.visible = true
				if (method === 'add') {
					// this.inputForm.id = 'add'
					this.title = `新建项目`
				} else if (method === 'edit') {
					this.title = '修改项目'
				} else if (method === 'view') {
					this.title = '查看项目详情'
				}
				this.loading = false
				this.$nextTick(() => {
					this.$refs.inputForm.resetFields()
					this.loading = true
					// this.$refs.uploadComponent.clearUpload()
					// this.$refs.archiveFile.clearUpload()
					console.log('id',this.$store.state.user)
					this.projectInfoService.findByIdArchive(this.inputForm.id).then((data) => {
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm.contractName=data.jyProjectList.contractName
						this.inputForm.contractAmount=data.jyProjectList.contractAmount
						this.inputForm.primaryLinkman=data.jyProjectList.primaryLinkman
						this.inputForm.contractTypeFirst=data.jyProjectList.contractTypeFirst
						this.inputForm.contractType=data.jyProjectList.contractType
						this.inputForm.projectName=data.jyProjectList.name
						this.inputForm.projectPlace=data.jyProjectList.place
						this.inputForm.buildPlace=data.jyProjectList.buildPlace
						this.inputForm.createByName=data.jyProjectList.createById
						this.inputForm.createTime=data.jyProjectList.createTime
						this.inputForm.projectLeader=data.jyProjectList.leader
						this.inputForm.projectId=data.projectId
						this.inputForm.remarks=data.remarks
						this.inputForm.no = data.jyProjectList.no
						console.log('data', data)
						if (this.status === 'audit' || this.status === 'taskFormDetail') {
							method = 'view'
						}
						console.log('method2',method)
						this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data)=> {
							if (this.commonJS.isNotEmpty(data)) {
								if (data === '办公室审核') {
									this.isBgs = true
								}
							}
						})
						this.projectInfoService.getAttachmentList(data.projectId,this.inputForm.id).then((data) => {
							this.tableData = data
						})

						// this.$refs.uploadComponent.newUpload(method, this.inputForm.fileList, 'jyProjectArchive', null, '附件', null, null, null)
						// this.$refs.archiveFile.newUpload('view', [], 'cwWorkContract', null, null, null, null, false)
						this.loading = false
					})
				})
			},
			close () {
				// this.$refs.uploadComponent.clearUpload()
				this.inputForm = {
					id: '',
					contractName:'',
					contractAmount:'',
					primaryLinkman:'',
					contractTypeFirst:'',
					contractType:'',
					projectName:'',
					projectPlace:'',
					buildPlace:'',
					projectLeader:'',
					createByName:'',
					createTime:'',
					fileList:[],
					status:'',
					projectId:'',
					remarks:'',
					procInsId:'',
					no:'',
					caseNumber:''
				}
				this.$refs.inputForm.resetFields()
				this.visible = false
			},
			reapplyForm (callback) {
				this.loading = true
				this.projectInfoService.findByIdArchive(this.inputForm.id).then((data) => {
					if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.startFormTrue(callback)
					}
				})
			},
			saveForm (callback) {
				this.doSubmit('save', callback)
			},
			startForm (callback) {
				this.loading = true
				if (this.commonJS.isNotEmpty(this.inputForm.id)) {
					this.projectInfoService.findByIdArchive(this.inputForm.id).then((data) => {
						if (this.commonJS.isNotEmpty(data.status) && data.status !== '0' && data.status !== '1' && data.status !== '3' && data.status !== '6') { // 审核状态不是“未发起”或“暂存”或“撤回”或"超期未发起"，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.startFormTrue(callback)
						}
					})
				} else {
					this.startFormTrue(callback)
				}
			},
			startFormTrue (callback) {
				this.doSubmit('start', callback)
			},
			async agreeForm (callback) {
				this.loading = true
				await this.projectInfoService.findByIdArchive(this.inputForm.id).then((data) => {
					if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error()
					} else {
						this.inputForm.status = '2'
						this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data)=> {
							if (this.commonJS.isNotEmpty(data)) {
								if (data === '办公室审核') {
									this.inputForm.status = '5'
								}
							}
							this.doSubmit('agree', callback)
						})

					}
				})
			},
			// 表单提交
			async doSubmit (status, callback) {
				this.loading = true
				if (status === 'save') {
					// 暂存
					this.loading = true
					this.inputForm.status = '1'
					this.projectInfoService.saveFormArchive(this.inputForm).then((data) => {
						this.inputForm.assignee = this.inputForm.auditPeople
						this.inputForm.id = data.businessId
						callback(data.businessTable, data.businessId, this.inputForm)
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
					return
				} else if (status === 'start') {
					// 送审  待审核
					this.inputForm.status = '2'
				} else if (status === 'agree') {
					// 审核同意


				}
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						this.tableData.forEach(item=>{
							console.log('item',item)
							if (item.levelFlag === 2 && item.mustFlag === 1){
								console.log('len',item.children.length)
								if (item.children.length === 0){
									this.loading = false
									this.$message.error('文件未上传')
									throw new Error('文件未上传')
								}
							}
						})
						if (this.inputForm.status === '5'){
							if (this.commonJS.isEmpty(this.inputForm.caseNumber)){
								this.loading = false
								this.$message.error('归档盒号为空,请输入')
								throw new Error('归档盒号为空,请输入')
							}
						}
						this.projectInfoService.saveFormArchive(this.inputForm).then((data) => {
							this.inputForm.id = data.businessId
							let processTitle = `${this.inputForm.createByName} 发起了${this.inputForm.projectName} - ${this.inputForm.no} ` + `[嘉溢-项目归档]`
							this.inputForm.title = processTitle
							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 (await this.$refs.uploadComponent.checkProgress()) {
				// 	this.loading = false
				// 	throw new Error()
				// } else {
					if (type === 'reject' || type === 'reback') {
						this.projectInfoService.findByIdArchive(this.inputForm.id).then((data) => {
							if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
								this.loading = false
								this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
								throw new Error()
							} else {
								// if (type === 'agree') {
								//   // 同意
								//   this.inputForm.status = '5'
								// }
								if (type === 'reject') {
									// 驳回
									this.inputForm.status = '4'
									this.loading = true
									// this.inputForm.workAttachmentDtoList = this.$refs.uploadComponent.getDataList()
									this.projectInfoService.saveFormOut(this.inputForm).then((data) => {
										this.loading = false
									}).catch(() => {
										this.loading = false
									})
									// return
								}
								if (type === 'reback') {
									// 撤回
									this.inputForm.status = '3'
								}
								if (type === 'reject' || type === 'reback') {
									let param = {status: this.inputForm.status, id: this.inputForm.id}
									this.loading = true
									this.projectInfoService.updateStatusByArchiveId(param).then(() => {
										this.loading = false
										callback()
									})
								}
							}
						})
					} else if (type === 'hold') {
						this.projectInfoService.findByIdArchive(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.id}
								this.projectInfoService.updateStatusByArchiveId(param).then(() => {
									this.loading = false
									callback()
								})
							}
						})
					}
				// }
			},
			// 下载一级校审
			downloadFirstAuditTpl () {
				// this.$utils.downloadExcel('/sys/project/import/template')
				this.loading = true
				if (this.tabName === '一级校审') {
					this.projectInfoService.downloadFirstAuditTpl(this.inputForm.id, this.inputForm.projectId).then((res) => {
						console.log('hh',res)
						// 将二进制流文件写入excel表，以下为重要步骤
						this.$utils.downloadWord(res, this.tabName)
						this.loading = false
					}).catch(function (err) {
						this.loading = false
						if (err.response) {
							console.log(err.response)
						}
					})
				}
				if (this.tabName === '二级校审') {
					this.projectInfoService.downloadSecondAuditTpl(this.inputForm.id, this.inputForm.projectId).then((res) => {
						// 将二进制流文件写入excel表，以下为重要步骤
						this.$utils.downloadWord(res, this.tabName)
						this.loading = false
					}).catch(function (err) {
						this.loading = false
						if (err.response) {
							console.log(err.response)
						}
					})
				}
				if (this.tabName === '三级校审') {
					this.projectInfoService.downloadThirdlyAuditTpl(this.inputForm.id, this.inputForm.projectId).then((res) => {
						// 将二进制流文件写入excel表，以下为重要步骤
						this.$utils.downloadWord(res, this.tabName)
						this.loading = false
					}).catch(function (err) {
						this.loading = false
						if (err.response) {
							console.log(err.response)
						}
					})
				}
			},
			//测试按钮
			openFileForm(id,typeId){
				this.$refs.fileForm.init("add", id,this.inputForm.projectId)
			},
			showFile (row) {
				console.log("showFile",row)
				row.name = row.attachmentName
				openWindowOnUrl(row)
			},
			toHref (row) {
				console.log("toHref",row)
				toHref(row)
			},
			getFiles(){
				this.projectInfoService.getAttachmentList(this.inputForm.projectId,this.inputForm.id).then((data) => {
					this.tableData = data
					this.tableKey = Math.random()
				})

			},
			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]
				}
			},
			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
				}
			},

		}
	}
</script>
<style lang="scss">
	.el-input-number .el-input__inner {
		text-align: left;
	}
	.el-divider__text {
		font-size: 16px;
		font-weight: bold;
	}

</style>
