<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-dialog
			:title="title"
			:close-on-click-modal="false"
			draggable
			width="1300px"
			@close="close"
			@keyup.enter.native=""
			v-model="visible">
		<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'"
				 label-width="160px" @submit.native.prevent>
			<el-divider content-position="left"><i class="el-icon-document"></i>
				<span style="color: red;border-top: 20px">*</span>关联项目
				<el-button style="margin-left: 20px" type="primary" :readonly="true" :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'" @click="insertEvent('base')"  plain>
					新增
				</el-button>
			</el-divider>
			<el-row  :gutter="15">
				<el-col :span="24">
					<vxe-table
						border
						:footer-method="footerMethod2"
						show-overflow
						show-footer
						ref="baseTable"
						:key="baseKey"
						class="vxe-table-element"
						:data="inputForm.projectList"
						style="margin-left: 5em"
						@cell-click=""
						@edit-closed=""
						keep-source
						:readonly="true"
						highlight-current-row
						:edit-rules="tableRules"
						:edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true, icon: '-'}"
					>
						<vxe-table-column field="name" align="center" title="项目名称" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-input  :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'" @focus="openProgramPageForm(scope.$rowIndex)" placeholder="请填写项目名称" :readonly="true" v-model="scope.row.name"/>
							</template>
						</vxe-table-column>
						<vxe-table-column field="no" align="center" title="项目编号" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input :disabled="true" :readonly="true" placeholder="请填写项目编号" v-model="scope.row.no"/>
							</template>
						</vxe-table-column>
						<vxe-table-column  field="leader" align="center" title="项目负责人" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input :disabled="true" placeholder="请填写项目负责人" v-model="scope.row.leader"/>
							</template>
						</vxe-table-column>
						<vxe-table-column field="createTime" align="center" title="创建时间" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input :disabled="true" placeholder="请填写创建时间" v-model="scope.row.createTime"/>
							</template>
						</vxe-table-column>
						<vxe-table-column title="操作" align="center" width="100">
							<template v-slot="scope">
								<el-button :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'base')">删除</el-button>
							</template>
						</vxe-table-column>
					</vxe-table>
				</el-col>
			</el-row>

			<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="createName"
					>
						<el-input :disabled="true" v-model="inputForm.createName" placeholder="请输入申请人名称" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="申请人部门" prop="officeName"
					>
						<el-input :disabled="true" v-model="inputForm.officeName" placeholder="请输入申请人部门" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="申请时间" prop="createTime">
						<el-input :disabled="true" v-model="inputForm.createTime" placeholder="请输入申请时间" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="黑白页数量" prop="normalPage">
						<el-input :disabled="true" v-model="inputForm.normalPage" placeholder="请输入黑白页数量" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="彩页数量" prop="colorPage"
								  :rules="[
								  {required: true, message:'彩页数量不能为空', trigger:'blur'}]">
						<el-input oninput="value=value.replace(/[^\d]/g,'')" @change="updateNormal"  v-model="inputForm.colorPage" placeholder="请输入彩页数量" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="装订数量" prop="bookbindingNum"
								  :rules="[
								  {required: true, message:'装订数量不能为空', trigger:'blur'}]">
						<el-input oninput="value=value.replace(/[^\d]/g,'')"  v-model="inputForm.bookbindingNum" placeholder="请输入装订数量" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="其他" prop="otherNum"
								  :rules="[]">
						<el-input  v-model="inputForm.otherNum" placeholder="请输入其他数量" clearable></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="文印内容" prop="content"
								  :rules="[ ]">
						<el-input :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'" type="textarea" placeholder="请输入文印内容"  maxlength="500"  style="width:100%" v-model="inputForm.content" show-word-limit></el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<ProjectForm ref="projectForm" @getProgram="getProgram"></ProjectForm>
		<UpLoadComponent ref="uploadComponent" @updateSealType="updateSealType"></UpLoadComponent>
			<template #footer>
			<span class="dialog-footer">
			  <el-button  @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button  type="primary" v-if="method != 'view'" @click="doSubmit()" icon="el-icon-circle-check" v-noMoreClick>确定</el-button>
			</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import XEUtils from 'xe-utils'
	import InscriptionService from '@/api/jy/InscriptionService'
	import { ElDatePicker } from 'element-plus';
	import ProjectForm from './ProjectForm'
	import UserSelectSignatory from '../workClientInfo/clientUserSelect'
	import UpLoadComponent from '@/views/common/InscriptionUpLoadComponent'
	import CommonApi from '@/api/cw/common/CommonApi'
	import SelectTree from '@/components/treeSelect/treeSelect.vue'
	import OSSSerivce, {openWindowOnUrl,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: '',
				loading: false,
				visible: false,
				inputForm: {
					id: '',
					createName:this.$store.state.user.name,
					officeName:this.$store.state.user.office.name,
					createTime:this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
					normalPage:'',
					colorPage:'',
					bookbindingNum:'',
					otherNum:'',
					content:'',
					files: [], // 附件信息
					procInsId: '',
					projectList:[],
					minister:'',
					examiner:'',
					approver:''
				},
				baseKey: '',
				keyWatch: '',
				programRow:'',

			}
		},
		InscriptionService:null,
		commonApi: null,
		created () {
			this.inscriptionService=new InscriptionService()
			this.commonApi = new CommonApi()
			this.ossService = new OSSSerivce()
		},
		mounted () {
		},
		activated () {
		},
		components: {
			ElDatePicker,
			ProjectForm,
			UserSelectSignatory,
			UpLoadComponent,
			SelectTree,
		},
		computed: {
			bus: {
				get () {
					this.$refs.uploadComponent.setDividerName('附件')
					return this.businessId
				},
				set (val) {
					this.businessId = val
				}
			}
		},
		watch: {
			'keyWatch': {
				handler (newVal) {
					console.log('几里路')
					if (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)
				}
			}
		},
		methods: {
			getKeyWatch(keyWatch) {
				this.keyWatch = keyWatch
			},
			init(method, id) {
				this.method = method
				this.inputForm={
					id: '',
					createName:'',
					officeName:'',
					createTime:'',
					normalPage:'',
					colorPage:'',
					bookbindingNum:'',
					otherNum:'',
					content:'',
					files: [], // 附件信息
					procInsId: '',
					projectList:[],
					minister:'',
					examiner:'',
					approver:'',
					pageTotal:''
				}
				this.inputForm.id = id
				console.log('this.inputForm.id', this.inputForm.id)
				this.loading = false
				this.visible = true
				if (method === 'edit'){
					this.title = '修改文印信息'
				}else if (method === 'view'){
					this.title = '查看文印信息'
				}
				this.$nextTick(() => {
					this.$refs.inputForm.resetFields()
					this.loading = true
					this.$refs.uploadComponent.clearUpload()
					// if (this.commonJS.isNotEmpty(this.inputForm.id)) {

					this.inscriptionService.queryById(this.inputForm.id).then((data)=>{
						if (this.commonJS.isEmpty(this.inputForm.createName)){
							this.inputForm.createName=this.$store.state.user.name
						}
						if (this.commonJS.isEmpty(this.inputForm.officeName)){
							this.inputForm.officeName=this.$store.state.user.office.name							}
						if (this.commonJS.isEmpty(this.inputForm.createTime)){
							this.inputForm.createTime=this.moment(new Date()).format('YYYY-MM-DD')
						}
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm.files=data.files
						console.log('s',this.inputForm)
						if (this.status === 'audit' || this.status === 'taskFormDetail') {
							method = 'view'
						}
						console.log('me',method)
						this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'inscription',null,null,null,null,null)
						this.loading = false
					})
					// }
				})
			},
			saveForm(callback) {
				this.doSubmit('save', callback)
			},
			startForm(callback) {
				this.loading = true
				if (this.commonJS.isNotEmpty(this.inputForm.id)) {
					this.inscriptionService.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 this.inscriptionService.queryById(this.inputForm.id).then((data) => {
					if (data.status !== '2' ) { // status的值不等于“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error()
					} else {
						this.inputForm.status= '2'
						if (this.commonJS.isEmpty(this.inputForm.examiner) && this.commonJS.isNotEmpty(this.inputForm.minister)){
							this.inputForm.examiner=this.$store.state.user.id
						}
						if (this.commonJS.isEmpty(this.inputForm.minister)){
							this.inputForm.minister=this.$store.state.user.id
						}
						this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data)=>{
							if (this.commonJS.isNotEmpty(data)) {
								if (data === '副总经理审核') {
									this.inputForm.status = '5'
									this.inputForm.approver=this.$store.state.user.id
								}
							}
							let param = {status: this.inputForm.status, id: this.inputForm.id}
							this.inputForm=JSON.stringify(this.inputForm)
							this.inscriptionService.updateStatusById(this.inputForm).then(() => {
								callback(data.businessTable, data.businessId, this.inputForm)
								this.loading = false
							}).catch(() => {
								this.loading = false
							})
						})
					}
				})
			},
			reapplyForm(callback) {
				this.loading = true
				this.inscriptionService.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
				console.log('5',this.inputForm)
				if (status === 'save') {
					// 暂存
					this.loading = true
					this.inputForm.status = '1'
					if (this.$refs.uploadComponent.checkProgress()) {
						this.loading = false
						return
					}
					this.inputForm.files = this.$refs.uploadComponent.getDataList()
					this.inscriptionService.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.inputForm.projectList.length ===0) {
						this.$message.error('请选择项目')
						this.loading = false
						return
					}
					if (this.commonJS.isEmpty(this.inputForm.files)) {
						this.$message.error('请上传附件')
						this.loading = false
						return
					}
					if (this.commonJS.isEmpty(this.inputForm.colorPage)){
						this.$message.error('请输入彩页数量')
						this.loading = false
						return
					}
					if (this.commonJS.isEmpty(this.inputForm.bookbindingNum)){
						this.$message.error('请输入装订数量')
						this.loading = false
						return
					}
					if (this.$refs.uploadComponent.checkProgress()) {
						this.loading = false
						return
					}
					this.inputForm.files = this.$refs.uploadComponent.getDataList()
					// 送审  待审核
					this.inputForm.status = '2'
				} else if (status === 'agree') {
					this.inputForm.status= '5'
				} else if (status === 'reapply') {
					this.inputForm.status = '2'
				}
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						console.log('form',this.inputForm)
						this.inscriptionService.adminEditForm(this.inputForm).then((data) => {
							this.visible = false
							this.$emit('refreshList')
						}).catch(() => {
							this.$refs.inputForm.resetFields()
							this.loading = false
						})
					} else {
						this.loading = false
					}
				})
			},
			close() {
				this.inputForm = {
					id:'',
					projectList:[],
					name:'',
					no:'',
					projectLeader:'',
					projectCreateDate:'',
					createById:'',
					createByName:'',
					createDate:'',
					remarks:'',
					files: [], // 附件信息
					types:[], //用印类型
					number:'', //用印份数
					projectId:'',
				}
				this.visible = false
			},
			async updateStatusById(type, callback) {
				this.loading = true
				if (type === 'reject' || type === 'reback') {
					this.inscriptionService.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}
								this.inscriptionService.updateStatusById(param).then(() => {
									this.loading = false
									callback()
								})
							}
						}
					})
				} else if (type === 'hold') {
					this.inscriptionService.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}
							this.inscriptionService.updateStatusById(param).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}

			},
			insertEvent(type) {
				if (type === 'base') {
					if (this.inputForm.projectList.length>=1){
						if (this.commonJS.isEmpty(this.inputForm.projectList[0].projectId)){
							this.$message.error('第一行不能为空')
							return
						}
					}
					this.$refs.baseTable.insertAt({})
					this.inputForm.projectList.push({})
					this.baseKey = Math.random()
				}
				console.log('22',this.inputForm.projectList)
			},
			// 删除
			removeEvent(row, rowIndex, type) {
				if (type === 'base') {
					this.$refs.baseTable.remove(row)
					this.inputForm.projectList.splice(rowIndex, 1)
				}
			},
			openProgramPageForm(rowIndex) {
				this.$refs.projectForm.init()
				this.programRow = rowIndex
				console.log('11',this.programRow)
			},
			getProgram(rows) {
				console.log('1',rows)
				rows.forEach((item, index) => {
					this.inputForm.programId = item.id
					if (index === 0) {
						let r = this.inputForm.projectList[this.programRow]
						r.projectId=item.id
						r.name = item.name
						r.no = item.no
						r.leader = item.projectLeader
						r.createTime = item.createTime
						console.log('2',this.inputForm.projectList[this.programRow])
					} else {
						let r = {
							projectId: item.id,
							name: item.name,
							no: item.no,
							leader: item.projectLeader,
							createTime: item.createTime,
						}
						this.$refs.baseTable.insertAt(r)
						this.inputForm.projectList.push(r)
						this.baseKey = Math.random()
					}

				})
				this.$forceUpdate()
				this.programRow = ''
				// this.inputForm.reconciliationArea = this.inputForm.financeInvoiceBaseDTOList[0].location
			},
			updateSealType(files){
				this.inputForm.files = this.$refs.uploadComponent.getDataList()
				let page=''
				this.inscriptionService.getPageTotal(this.inputForm).then((data)=>{
					console.log('datqa',data)
					page=data-this.inputForm.colorPage
					console.log('page',page)
					this.inputForm.normalPage=page
				})

				console.log('file1',this.inputForm.normalPage)
			},
			updateNormal(){
				this.inputForm.normalPage = this.inputForm.pageTotal - this.inputForm.colorPage
			}

		}

	}
</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>
