<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>
				<span style="color: red;border-top: 20px">*</span>用车项目
				<el-button style="margin-left: 20px" type="primary" :readonly="true" :disabled="true" @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"
						:disabled="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="true" @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="true" 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="useMen"
								  :rules="[ {required: true, message:'用车人员不能为空', trigger:'blur'}]">
						<UserSelectSignatory style="width: 100%" :disabled="true" ref="userSelect2"
											 :readonly="true" :modelValue="inputForm.useMen"
											 @update:modelValue='(value) => {inputForm.useMen = value}'></UserSelectSignatory>					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="用车起止时间" prop="useDate"
								  :rules="[
								  {required: true, message:'用车起止时间不能为空', trigger:'blur'}]">
						<el-date-picker
							:disabled="true"
							v-model="inputForm.useDate"
							type="datetimerange"
							start-placeholder="请选择开始时间"
							end-placeholder="请选择结束时间"
							value-format="YYYY-MM-DD HH:mm:ss"
							time-format="HH"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="用车原因" prop="useReason"
								  :rules="[ {required: true, message:'用车原因不能为空', trigger:'blur'}]">
						<el-input :disabled="true" type="textarea" placeholder="请输入说明"  maxlength="500"  style="width:100%" v-model="inputForm.useReason" show-word-limit></el-input>
					</el-form-item>
				</el-col>

				<el-col :span="24">
					<el-form-item label="备注" prop="remarks"
								  :rules="[ ]">
						<el-input :disabled="true" type="textarea" placeholder="请输入说明"  maxlength="500"  style="width:100%" v-model="inputForm.remarks" show-word-limit></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<UpLoadComponent ref="uploadComponent"></UpLoadComponent>

		</el-form>

		<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>
				<span style="color: red;border-top: 20px">*</span>用车结算
			</el-divider>
			<el-row  :gutter="15">
				<el-col :span="12">
					<el-form-item label="开始里程数" prop="startMileage"
								  :rules="[
								  {required: true, message:'开始里程数不能为空', trigger:'blur'}]">
						<el-input
							v-on:input="inputForm.startMileage=inputForm.startMileage.replace(/[^\d.]/g,'')
							  .replace(/^\./g,'')
							  .replace(/\.{2,}/g,'.')
							  .replace('.','$#$').replace(/\./g,'').replace('$#$','.')
							  .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
							:disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'"
							placeholder="请输入开始里程数"
							style="width:100%"
							v-model="inputForm.startMileage"
							clearable
							></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="结束里程数" prop="endMileage"
								  :rules="[{required: true, message:'结束里程数不能为空', trigger:'blur'}]">
						<el-input
							v-on:input="inputForm.endMileage=inputForm.endMileage.replace(/[^\d.]/g,'')
							  .replace(/^\./g,'')
							  .replace(/\.{2,}/g,'.')
							  .replace('.','$#$').replace(/\./g,'').replace('$#$','.')
							  .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
							clearable
							@blur="check" :disabled="status === 'audit' || status === 'taskFormDetail' || method === 'view'" placeholder="请输入结束里程数"   style="width:100%" v-model="inputForm.endMileage" ></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="里程总数" prop="mileageCount"
					>
						<el-input  :disabled="true" style="width:100%" v-model="inputForm.mileageCount" ></el-input>
					</el-form-item>
				</el-col>
			</el-row>

			<el-tabs v-model="activeName1" type="border-card">
				<el-tab-pane name="accountFiles">
					<template v-slot:label>
						<span><span style="color: red;border-top: 20px">*</span> 里程数附件信息</span>
					</template>
					<!--        合同文件-->
					<UpLoadComponentAccount ref="upLoadComponentAccount"></UpLoadComponentAccount>
				</el-tab-pane>
			</el-tabs>
		</el-form>

		<ProjectForm ref="projectForm" @getProgram="getProgram"></ProjectForm>
	</div>
</template>

<script>
	import XEUtils from 'xe-utils'
	import DriveService from '@/api/jy/DriveService'
	import { ElDatePicker } from 'element-plus';
	import ProjectForm from './ProjectForm'
	import UserSelectSignatory from '../workClientInfo/clientUserSelect'
	import UpLoadComponent from '@/views/common/UpLoadComponent'
	import UpLoadComponentAccount from '@/views/common/UpLoadComponent'
	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 {
				title: '',
				method: '',
				loading: false,
				inputForm: {
					id: '',
					applyId:'',
					useMen:'',
					useReason: '',
					useStartTime:'',
					useEndTime:'',
					remarks: '',
					projectList:[],
					files: [], // 附件信息
					accountFiles: [], // 附件信息
					procInsId: '',
					startMileage:'',
					endMileage:'',
					mileageCount:'',
					contractProper: [],
					status:''
				},
				baseKey: '',
				keyWatch: '',
				dateList:[],
				programRow:'',
				useDate:[],
				activeName1: 'accountFiles',
			}
		},
		DriveService:null,
		commonApi: null,
		created () {
			this.driveService=new DriveService()
			this.commonApi = new CommonApi()
		},
		mounted () {
		},
		activated () {
		},
		components: {
			ElDatePicker,
			ProjectForm,
			UserSelectSignatory,
			UpLoadComponent,
			UpLoadComponentAccount
		},
		computed: {
			bus: {
				get () {
					this.$refs.uploadComponent.setDividerName('附件')
					// this.$refs.upLoadComponentAccount.setDividerName('附件')
					return this.businessId
				},
				set (val) {
					this.businessId = val
				}
			}
		},
		watch: {
			'keyWatch': {
				handler (newVal) {
					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)
					this.$refs.upLoadComponentAccount.changeLoading(newVal)
				}
			}
		},
		methods: {
			getKeyWatch(keyWatch) {
				console.log('keyWatch',keyWatch)
				this.keyWatch = keyWatch
			},
			init(method, id) {
				console.log('casda a')
				this.method = method
				this.inputForm={
					id: '',
					useMen:'',
					useReason: '',
					useDate:[],
					remarks: '',
					projectList:[],
					files: [], // 附件信息
					accountFiles: [], // 附件信息
					procInsId: '',
					startMileage:'',
					endMileage:'',
					contractProper: [],
					mileageCount:'',
					status:''
				}
				this.inputForm.id = id
				this.loading = false
				this.$nextTick(() => {
					this.$refs.inputForm.resetFields()
					this.loading = true
					this.$refs.uploadComponent.clearUpload()
					this.$refs.upLoadComponentAccount.clearUpload()
					if (this.commonJS.isNotEmpty(this.inputForm.id)) {
						console.log('this.inputForm.id', this.inputForm.id)
						this.driveService.queryById(this.inputForm.id).then((data)=>{
							this.inputForm = this.recover(this.inputForm, data)
							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, 'driveApply',null,null,null,null,null)
							this.$refs.upLoadComponentAccount.newUpload(method, this.inputForm.accountFiles, 'driveAccount',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.driveService.queryById(this.inputForm.id).then((data) => {
						if (data.accountStatus !== '0' && data.accountStatus !== '1' && data.accountStatus !== '3' && data.accountStatus !== '' && data.accountStatus !== null && data.accountStatus !== undefined) { // 审核状态不是“未发起”或“暂存”或“撤回”，就弹出提示
							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.driveService.queryById(this.inputForm.id).then((data) => {
					if (data.accountStatus !== '2' ) { // status的值不等于“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error()
					} else {
						this.inputForm.status= '5'
						this.inputForm.applyId=this.inputForm.id
						let param = {status: this.inputForm.status, applyId: this.inputForm.applyId}
						this.inputForm=JSON.stringify(this.inputForm)
						this.driveService.updateStatusByApplyId(param).then(() => {
							callback(data.businessTable, data.businessId, this.inputForm)
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
			reapplyForm(callback) {
				this.loading = true
				this.driveService.queryById(this.inputForm.id).then((data) => {
					if (data.accountStatus !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.doSubmit('reapply', callback)
					}
				})
			},
			// 表单提交
			async doSubmit(status, callback) {
				this.loading = true
				this.inputForm.applyId=this.inputForm.id
				console.log('5',this.inputForm)
				if (status === 'save') {
					// 暂存
					this.loading = true
					this.inputForm.status = '1'
					if (this.$refs.upLoadComponentAccount.checkProgress()) {
						this.loading = false
						return
					}
					this.inputForm.accountFiles = this.$refs.upLoadComponentAccount.getDataList()
					this.driveService.saveAccountForm(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.startMileage) || this.commonJS.isEmpty(this.inputForm.endMileage)){
						this.$message.error('请输入里程数')
						this.loading = false
					}
					this.inputForm.accountFiles = this.$refs.upLoadComponentAccount.getDataList()
					if (this.inputForm.accountFiles.length === 0){
						this.$message.error('请上传里程数图片')
						this.loading = false
						return
					}
					// 送审  待审核
					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.driveService.saveAccountForm(this.inputForm).then((data) => {
							callback(data.businessTable, data.businessId, this.inputForm)
							this.$refs.inputForm.resetFields()
							this.loading = false
						}).catch(() => {
							this.$refs.inputForm.resetFields()
							this.loading = false
						})
					} else {
						this.loading = false
					}
				})
			},
			close() {
				this.inputForm = {
					id: '',
					useMen:'',
					useReason: '',
					useStartTime:'',
					useEndTime:'',
					remarks: '',
					projectList:[],
					files: [], // 附件信息
					accountFiles: [], // 附件信息
					procInsId: '',
					startMileage:'',
					endMileage:'',
					mileageCount:''
				}
				this.visible = false
			},
			async updateStatusById(type, callback) {
				this.loading = true
				this.inputForm.applyId=this.inputForm.id
				if (type === 'reject' || type === 'reback') {
					this.driveService.queryById(this.inputForm.id).then((data) => {
						if (data.accountStatus !== '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, applyId: this.inputForm.applyId}
								this.driveService.updateStatusByApplyId(param).then(() => {
									this.loading = false
									callback()
								})
							}
						}
					})
				} else if (type === 'hold') {
					this.driveService.queryById(this.inputForm.id).then((data) => {
						if (data.accountStatus !== '4') { // status的值不等于“驳回”就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error()
						} else {
							// 终止
							this.inputForm.applyId=this.inputForm.id
							let param = {status: '1', applyId: this.inputForm.applyId}
							this.driveService.updateStatusByApplyId(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.projectLeader = 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,
							projectLeader: 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
			},
			//计算所用里程数
			check(){
				let start=parseFloat(this.inputForm.startMileage)
				let end=parseFloat(this.inputForm.endMileage)
				if (end < start){
					this.$message.error('结束里程数不能小于开始里程数')
					return
				}
				let count=end-start
				this.inputForm.mileageCount=count
			}

		}

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