<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
				 label-width="160px" @submit.native.prevent>
			<el-divider content-position="left"><i class="el-icon-document"></i>
				归档批次基本信息
			</el-divider>
			<el-row :gutter="15">
				<el-col :span="12">
					<el-form-item label="归档批次号" prop="no"
								  :rules="[
               ]">
						<el-input :disabled="true" placeholder="自动生成归档批次号" v-model="inputForm.no" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="归档人" prop="createName"
								  :rules="[
               ]">
						<el-input :disabled="true" placeholder="归档人" v-model="inputForm.createName" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="归档名称" prop="name"
								  :rules="[
								  {required: true, message:'归档名称不能为空', trigger:'blur'},
               ]">
						<el-input :disabled="status === 'audit' || status === 'taskFormDetail'" placeholder="请填写归档名称" v-model="inputForm.name" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="归档说明" prop="remarks"
								  :rules="[
               ]">
						<el-input :disabled="status === 'audit' || status === 'taskFormDetail'" maxlength="500"  type="textarea" placeholder="请填写归档说明" v-model="inputForm.remarks" show-word-limit></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-divider content-position="left"><i class="el-icon-document"></i>
				归档项目信息 （<a style="color: red;font-size: 14px">根据档案管理要求，一次批量归档的报告号类型需一致，不能混装。如：全是“苏兴咨字【xx】xx”或全是“苏兴内审字【xx】xx”</a>）
			</el-divider>
			<el-row :gutter="15">
				<el-button style="margin-left: 80px" type="primary" :disabled="status === 'audit' || status === 'taskFormDetail'"  @click="insertEvent" plain>
					添加项目信息
				</el-button>
				<el-popover
					placement="top"
					width="400"
					v-model="importVisible">
					<p>请先下载模板，然后再进行导入操作</p>
					<el-row :gutter="1">
						<el-col :span="6">
							<el-button :disabled="status === 'audit' || status === 'taskFormDetail'" type="success" @click="downloadTpl">下载模板</el-button>
						</el-col>
						<el-col :span="6">
							<el-upload
								action=""
								:auto-upload="false"
								:on-change="beforeUploadDetail"
								:show-file-list="false">
								<el-button :disabled="status === 'audit' || status === 'taskFormDetail'" type="primary">导入全部</el-button>
							</el-upload>
						</el-col>
					</el-row>
					<template #reference>
						<el-button style="margin-left: 20px" :disabled="status === 'audit' || status === 'taskFormDetail'" type="warning" plain>导入</el-button>
					</template>
				</el-popover>
			</el-row>
			<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
					 label-width="160px" @submit.native.prevent>
				<el-row  :gutter="15">
					<el-col :span="24">
						<vxe-table
							border
							show-overflow
							show-footer
							:column-config="{resizable: true}"
							ref="batchTable"
							:key="tableKeyProject"
							class="vxe-table-element"
							:data="inputForm.cwFillingbatchProjects"
							:edit-rules="validContactRules"
							style="margin-left: 5em"
							highlight-current-row
							:edit-config="{trigger: 'click', mode: 'row', showStatus: true, autoClear: true, icon:'_'}"
							:tree-config="{transform: true,rowField: 'id', parentField: 'parentId', accordion: true}"
							row-id="id">
							<vxe-column title="归档项目编号/文件类型" field="projectNumber" align="center" tree-node>
								<template v-slot:edit="scope">
									<el-input  v-model="scope.row.projectNumber" :disabled="true"></el-input>
								</template>
							</vxe-column>
							<vxe-column title="归档项目名称/文件描述" field="name" align="center">
								<template v-slot:edit="scope">
									<el-input  v-model="scope.row.name" :disabled="true"></el-input>
								</template>
							</vxe-column>
							<vxe-column title="报告号" field="no" align="center">
								<template #default="scope">
									<el-link  type="primary" :underline="false" v-if="status === 'audit' || status === 'taskFormDetail'" @click="getProjectInfo(scope.row.projectId)">{{scope.row.no}}</el-link>
									<el-link  style="color: #1b1e25" type="primary" :underline="false" v-else>{{scope.row.no}}</el-link>
								</template>
							</vxe-column>
							<vxe-column title="案卷号" field="achiveNo" align="center" :edit-render="{}" v-if="(status === 'audit' || status === 'taskFormDetail')">
								<template v-slot:edit="scope">
									<el-input :disabled="scope.row.level !== '1' || status === 'taskFormDetail'" placeholder="案卷号"  v-model="scope.row.achiveNo" ></el-input>
								</template>
							</vxe-column>
							<vxe-column title="状态" field="projectStatus" align="center" :edit-render="{name: '$select', options: $dictUtils.getDictList('cw_project_achieves_status')}"  v-if="status === 'audit' || status === 'taskFormDetail'" show-overflow="projectStatus">
								<template v-slot:edit="scope">
									<vxe-select v-model="scope.row.projectStatus" :disabled="scope.row.level !== '1' || status === 'taskFormDetail'" style="width: 100%;height: 100%" placeholder="状态" transfer>
										<vxe-option
											v-for="item in $dictUtils.getDictList('cw_project_achieves_status')"
											:key="item.value"
											:label="item.label"
											:value="item.value">
										</vxe-option>
									</vxe-select>
								</template>
							</vxe-column>
							<vxe-column title="操作" width="230px" fixed="right" align="center">
								<template  #default="scope">
									<el-button  v-if="scope.row.level === '1'" :disabled="status === 'audit' || status === 'taskFormDetail'" text type="primary" @click="add(scope.row)">添加</el-button>
									<el-button v-if="scope.row.level !== '1'" :disabled="status === 'audit' || status === 'taskFormDetail'" text type="primary" @click="edit(scope.row)">修改</el-button>
									<el-button text type="primary" v-if="scope.row.level === '1'"  :disabled ="scope.row.level === '1' && commonJS.isNotEmpty(scope.row.children)" @click="removeEvent(scope.row,scope.$rowIndex)">删除</el-button>
									<el-button text type="primary" v-if="scope.row.level !== '1'" :disabled="status === 'audit' || status === 'taskFormDetail'" @click="removeChildEvent(scope.row)">删除</el-button>
								</template>
							</vxe-column>
						</vxe-table>
					</el-col>
				</el-row>
			</el-form>
		</el-form>
		<ProgramPageForm ref="programPageForm" @getProgram = "getProgram"></ProgramPageForm>
		<FileForm ref="fileForm" @getFile="getFile"></FileForm>
		<ProjectRecordsForm2 ref="projectRecordsForm2"></ProjectRecordsForm2>
	</div>
</template>

<script>
	// import XEUtils from 'xe-utils'
	import fillingbatchService from '@/api/cw/fillingbatch/FillingbatchService'
	import ProgramPageForm from "./ProgramPageForm";
	import FileForm from "./FileForm";
	import ProjectRecordsForm2 from '../projectRecords/ProjectRecordsForm2'
	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: {
					no: '',
					createById: '',
					createName: '',
					name: '',
					remarks: '',
					cwFillingbatchProjects: []
				},
				programRow: '',
				err: '',
				keyWatch: '',
				tableKeyProject:'',
				validContactRules: {
					projectStatus: [
						{required: true, message: '状态不可以为空'}
					]
				}
			}
		},
		created() {
		},
		mounted() {
		},
		components: {
			ProgramPageForm,
			FileForm,
			ProjectRecordsForm2
		},
		computed: {
			bus: {
				get() {
					// this.$refs.uploadComponent.setDividerName('附件')
					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)
					// this.$refs.uploadComponent.changeLoading(newVal)
				}
			}
		},
		methods: {
			getKeyWatch(keyWatch) {
				this.keyWatch = keyWatch
			},
			init(method, id) {
				this.method = method
				this.inputForm = {
					no: '',
					createById: '',
					createName: '',
					name: '',
					remarks: '',
					cwFillingbatchProjects: []
				}
				this.inputForm.id = id
				this.loading = false
				this.$nextTick(() => {
					this.$refs.inputForm.resetFields()
					this.loading = true
					fillingbatchService.queryById(this.inputForm.id).then((data) => {

						this.inputForm = this.recover(this.inputForm, data)
						if (this.commonJS.isEmpty(this.inputForm.createName)){
							this.inputForm.createById = this.$store.state.user.id
							this.inputForm.createName = this.$store.state.user.name
						}
						if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects)){
							this.inputForm.cwFillingbatchProjects = []
						}
						console.log('this.inputForm',this.inputForm)
						this.expandAllTreeEvent()
						this.loading = false
					})
				})
			},
			saveForm(callback) {
				this.doSubmit('save', callback)
			},
			startForm(callback) {
				this.loading = true
				if (this.commonJS.isNotEmpty(this.inputForm.id)) {
					fillingbatchService.queryById(this.inputForm.id).then((data) => {
						if (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) {
				console.log('进入方法')
				this.loading = true
				await fillingbatchService.queryById(this.inputForm.id).then((data) => {
					if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error()
					} else {
						for (let i = 0; i < this.inputForm.cwFillingbatchProjects.length; i++) {
							if (this.inputForm.cwFillingbatchProjects[i].level === '1'){
								if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects[i].projectStatus)){
									this.loading = false
									this.$message.error('第'+(i+1)+'行的项目状态未选择')
									throw new Error('第'+(i+1)+'行的项目状态未选择')
								}else {
									if (this.inputForm.cwFillingbatchProjects[i].projectStatus === '5'){
										if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects[i].achiveNo)){
											this.loading = false
											this.$message.error('第'+(i+1)+'行的案卷号未填写')
											throw new Error('第'+(i+1)+'行的案卷号未填写')
										}
									}
								}


							}
						}

						// 审核同意
						this.inputForm.status = '5'
						fillingbatchService.updateStatusById(this.inputForm).then(() => {
							this.inputForm.id = data.businessId
							console.log('data22', data)
							callback(data.businessTable, data.businessId, this.inputForm, data.recordType)
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
			reapplyForm(callback) {
				this.loading = true
				fillingbatchService.queryById(this.inputForm.id).then((data) => {
					if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.doSubmit('reapply', callback)
					}
				})
			},
			// 表单提交
			async doSubmit(status, callback) {
				this.loading = true
				if (status === 'save') {
					// 暂存
					this.loading = true
					this.inputForm.status = '1'
					fillingbatchService.saveForm(this.inputForm).then((data) => {
						callback(data.businessTable, data.businessId, this.inputForm)
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
					return
				} else if (status === 'start') {
					// 送审  待审核
					if (this.commonJS.isEmpty(this.inputForm.name)){
						this.loading = false
						this.$message.warning('归档名称为空,请填写')
						throw new Error()
					}
					if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects)){
						this.loading = false
						this.$message.warning('请选择归档项目')
						throw new Error()
					}
					this.inputForm.status = '2'
				} else if (status === 'agree') {
					for (let i = 0; i < this.inputForm.cwFillingbatchProjects.length; i++) {
						if (this.inputForm.cwFillingbatchProjects[i].level === '1'){
							if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects[i].achiveNo)){
								this.loading = false
								this.$message.error('第'+(i+1)+'行的案卷号未填写')
								throw new Error('第'+(i+1)+'行的案卷号未填写')
							}
							if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects[i].projectStatus)){
								this.loading = false
								this.$message.error('第'+(i+1)+'行的项目状态未选择')
								throw new Error('第'+(i+1)+'行的项目状态未选择')
							}
						}
					}

					// 审核同意
					this.inputForm.status = '5'
				} else if (status === 'reapply') {
					this.inputForm.status = '2'
				}
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						console.log('this.inputForm',this.inputForm)
						fillingbatchService.saveForm(this.inputForm).then((data) => {
							this.inputForm.id = data.businessId
							console.log('data22', data)
							callback(data.businessTable, data.businessId, this.inputForm, data.recordType)
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					} else {
						this.loading = false
					}
				})
			},
			close() {
				this.inputForm = {
					no: '',
					createById: '',
					createByName: '',
					name: '',
					remarks: '',
					cwFillingbatchProjects: []
				}
				this.visible = false
			},
			insertEvent() {
				this.$refs.programPageForm.init()
			},
			async updateStatusById(type, callback) {
				this.loading = true
				if (type === 'reject' || type === 'reback') {
					fillingbatchService.queryById(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'
							}
							if (type === 'reback') {
								// 撤回
								this.inputForm.status = '3'
							}
							if (type === 'reject' || type === 'reback') {
								let param = {status: this.inputForm.status, id: this.inputForm.id}
								fillingbatchService.updateStatusById(param).then(() => {
									this.loading = false
									callback()
								})
							}
						}
					})
				} else if (type === 'hold') {
					fillingbatchService.queryById(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}
							fillingbatchService.updateStatusById(param).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}
			},
			// 下载模板
			downloadTpl() {
				this.loading = true
				fillingbatchService.exportTemplate().then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					console.log('res',res)
					this.$utils.downloadExcel(res, '批量归档导入模板')
					this.loading = false
				}).catch(function (err) {
					this.loading = false
					if (err.response) {
						console.log(err.response)
					}
				})
			},

			getProgram(rows){
				if (this.commonJS.isEmpty(this.inputForm.cwFillingbatchProjects)) {
					this.inputForm.cwFillingbatchProjects = []
				}
				console.log('row',rows)
				rows.forEach(item => {
					let d={
						reportId: item.reportId,
						projectNumber : item.projectNumber,
						name : item.name,
						no :item.no,
						parentId :'',
						level:item.level,
						id:item.reportId
					}
					this.$refs.batchTable.insertAt(d)
					this.inputForm.cwFillingbatchProjects.push(d)
					this.tableKeyProject = Math.random()
				})
				console.log('this.inputForm.cwFillingbatchProjects',this.inputForm.cwFillingbatchProjects)
			},
			add(row){
				this.$refs.fileForm.init('add',row)
			},
			getFile(list){
				console.log('list',list)

				list.forEach(item=>{
					if (this.commonJS.isEmpty(item.id)){
						this.$refs.batchTable.insertAt(item)
						this.inputForm.cwFillingbatchProjects.push(item)
						this.tableKeyProject = Math.random()
					}
				})
				console.log('this.inputForm.cwFillingbatchProjects1',this.inputForm.cwFillingbatchProjects)
			},
			removeEvent(row,rowIndex){
				this.$refs.batchTable.remove(row)
				this.inputForm.cwFillingbatchProjects.splice(rowIndex, 1)
			},
			removeChildEvent(row){
				this.inputForm.cwFillingbatchProjects= this.remoteChild(this.inputForm.cwFillingbatchProjects,row.id)
				console.log('this.inputForm.cwFillingbatchProjects',this.inputForm.cwFillingbatchProjects)
			},
			remoteChild(list,id){
				list=list.filter(item=>{
					let flag = item.id!=id //过滤非匹配id

					if(flag){
						if(item.children.length>0){
							item.children = this.remoteChild(item.children,id)
						}
						return true
					}else{
						return flag
					}

				})
				return list
			},
			edit(row){
				this.$refs.fileForm.init('edit',row)
			},
			getProjectInfo(id){
				this.$refs.projectRecordsForm2.init('view', id)
			},
			//展开行
			expandAllTreeEvent(){
				console.log('121')
				this.$refs.batchTable.setAllTreeExpand(true)
			},
			beforeUploadDetail(file) {
				const formBody = new FormData()
				formBody.append('file', file.raw)
				this.loading = true
				fillingbatchService.importDetail(formBody).then(async (result) => {
					if (this.commonJS.isEmpty(result)) {
						this.importVisible = false
						this.loading = false
						throw new Error()
					}
					// for await (let item of result) {
					// 	this.$refs.batchTable.insertAt(item)
					// 	this.inputForm.cwFillingbatchProjects.push(item)
					// 	this.tableKeyProject = Math.random()
					// }
					await this.detailPush(result)
					this.importVisible = false
					this.loading = false
				}).catch(() => {
					this.importVisible = false
					this.loading = false
				})
			},
			async detailPush(data) {
				if (this.commonJS.isNotEmpty(data)) {
					await data.forEach(item => {
						if (this.commonJS.isNotEmpty(item.cwFillingbatchFiles)){
							this.getFile(item.cwFillingbatchFiles)
						}
						console.log('item',item)
					})
					this.getProgram(data)
				}
				this.$message.success('导入完成')
			},



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

	/deep/ .vxe-footer--row .vxe-footer--column:nth-child(1) .vxe-cell--item {
		font-weight: 700;
	}
</style>
