<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':''" :disabled="status === 'audit' || status === 'taskFormDetail'"
				 label-width="100px" @submit.native.prevent>

			<el-divider content-position="left"><i class="el-icon-document"></i> 基础信息</el-divider>
			<el-row :gutter="26">
				<el-col :span="12">
					<el-form-item label="登记名称" prop="reimbuserName" :rules="[{required: true, message: '登记名称不能为空', trigger: 'blur'}]">
						<el-input v-model="inputForm.reimbuserName"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="项目经理" prop="projectManager"
								  :rules="[
								  	{required: true, message: '项目经理不能为空', trigger: 'change'}
                   ]">
<!--						<UserSelectSignatory style="width: 100%" ref="userSelect1" :disabled="status === 'audit' || status === 'taskFormDetail'"-->
<!--											 :readonly="true" :limit='1' :modelValue="inputForm.projectManager"-->
<!--											 @update:modelValue='(value, label) => {inputForm.projectManager = value}'></UserSelectSignatory>-->
						<UserSelect2 :limit='1' :modelValue="inputForm.projectManager" @update:modelValue='(value, label) => {inputForm.projectManager = value}'></UserSelect2>
					</el-form-item>
				</el-col>
<!--				<el-col :span="12">-->
<!--					<el-form-item label="银行卡号" prop="bankCardNumber" :rules="[{required: true, message: '银行卡号不能为空', trigger: 'blur'}]">-->
<!--						<el-input v-model="inputForm.bankCardNumber"></el-input>-->
<!--					</el-form-item>-->
<!--				</el-col>-->
				<el-col :span="12">
					<el-form-item label="总报销金额" prop="allReimbursementAmount" :rules="[{required: true, message: '总报销金额不能为空', trigger: 'blur'}]">
						<el-input v-model="inputForm.allReimbursementAmount" :disabled="true"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="备注" prop="remarks" :rules="[]">
						<el-input type="textarea"
								  maxlength="200" placeholder="请输入简介"
								  show-word-limit v-model="inputForm.remarks"></el-input>
					</el-form-item>
				</el-col>
				<el-form v-if="status === 'audit' " style="width: 100%" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
						 label-width="110px" @submit.native.prevent>
					<el-col :span="12">
						<el-form-item label="是否实习结束" prop="completePractice" :rules="[{required: true, message: '是否实习结束不能为空', trigger: 'change'}]">
							<el-radio-group v-model="inputForm.completePractice">
								<el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-form>
				<el-form v-else-if="this.commonJS.isNotEmpty(this.inputForm.type) && this.inputForm.type !== '4' && this.inputForm.type !== '3' && this.inputForm.type === '5'" style="width: 100%" :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
						 :disabled="true" label-width="110px" @submit.native.prevent>
					<el-col :span="12">
						<el-form-item label="是否实习结束" prop="completePractice" :rules="[{required: true, message: '是否实习结束不能为空', trigger: 'change'}]">
							<el-radio-group v-model="inputForm.completePractice">
								<el-radio v-for="item in $dictUtils.getDictList('yes_no')" :label="item.value" >{{item.label}}</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<el-divider content-position="left"><i class="el-icon-document"></i>
				报销明细
				<el-button style="margin-left: 20px" type="primary" :disabled="status === 'audit' || status === 'taskFormDetail'" @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.detailList"
						style="margin-left: 5em"
						keep-source
						highlight-current-row
						:edit-rules="tableRules"
						:edit-config="{trigger: 'click', mode: 'cell', showStatus: true, autoClear: true, icon: '-'}"
					>
						<vxe-table-column field="workName" align="center" title="日志名称" :edit-render="{}" show-overflow="title">
							<template v-slot:edit="scope">
								<el-input @focus="openProgramPageForm(scope.$rowIndex)" placeholder="请填写日志名称" :readonly="true" v-model="scope.row.workName"/>
							</template>
						</vxe-table-column>
						<vxe-table-column field="createName" align="center" title="创建人" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input :readonly="true" placeholder="请填写创建人" v-model="scope.row.createName"/>
							</template>
						</vxe-table-column>
						<vxe-table-column field="internshipDays" align="center" title="实习天数" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input :disabled="true"
									v-on:input="scope.row.internshipDays=scope.row.internshipDays.replace(/[^\d.]/g,'')
							  .replace(/^\./g,'')
							  .replace(/\.{2,}/g,'.')
							  .replace('.','$#$').replace(/\./g,'').replace('$#$','.')
							  .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
									v-model="scope.row.internshipDays"
									controls-position="right"
									:controls="false"
									style="width:100%;"
									placeholder="请输入实习天数"
									clearable
								>
								</el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column   field="reimbursementAmount" align="center"   title="报销金额(元)" :edit-render="{}">
							<template v-slot:edit="scope">
								<el-input
									v-on:input="scope.row.reimbursementAmount=scope.row.reimbursementAmount.replace(/[^\d.]/g,'')
							  .replace(/^\./g,'')
							  .replace(/\.{2,}/g,'.')
							  .replace('.','$#$').replace(/\./g,'').replace('$#$','.')
							  .replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
									v-model="scope.row.reimbursementAmount"
									controls-position="right"
									:controls="false"
									style="width:100%;"
									placeholder="请输入报销金额(元)"
									clearable
								>
								</el-input>
							</template>
						</vxe-table-column>
						<vxe-table-column title="操作" align="center" width="100">
							<template v-slot="scope">
								<el-button type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'base')">删除</el-button>
							</template>
						</vxe-table-column>
					</vxe-table>
				</el-col>
			</el-row>
		</el-form>
		<ProgramPageForm ref="programPageForm" @getProgram="getProgram"></ProgramPageForm>
	</div>
</template>

<script>
	import ProgramPageForm from './ProgramPageForm'
	import reimburseRegisterService from '@/api/human/register/ReimburseRegisterService'
	// import UserSelectSignatory from '@/views/cw/workClientInfo/clientUserSelect'
	import UserSelect2 from '@/components/userSelect'
	import XEUtils from "xe-utils";

	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				tableRules: {
					reimbursementAmount: [
						{ required: true, message: '请填写报销金额' }
					]
				},
				title: '',
				method: '',
				visible: false,
				loading: false,
				indexRow: '',
				inputForm: {
					userId: '',
					procInsId: '',
					bankCardNumber: '',
					remarks: '',
					projectManager: '',
					allReimbursementAmount: '',
					reimbuserName: '',
					completePractice: '',
					type: '',
					detailList: [],
				},
				keyWatch: '',
				baseKey: '',
			}
		},
		created () {
		},
		components: {
			// UserSelectSignatory,
			ProgramPageForm,
			UserSelect2,
		},
		computed: {
			bus: {
				get () {
					return this.businessId
				},
				set (val) {
					this.businessId = val
				}
			},
			name () {
				return this.$store.state.user.name
			},
			userId () {
				return this.$store.state.user.id
			}
		},
		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)
				}
			}
		},
		methods: {
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			getUpload () {
			},
			init (method, id) {
				this.method = method
				this.inputForm = {
					bankCardNumber: '',
					procInsId: '',
					userId: '',
					remarks: '',
					projectManager: '',
					allReimbursementAmount: '',
					reimbuserName: '',
					completePractice: '',
					type: '',
					detailList: [],
				}
				if (method === 'add') {
					this.title = `新建实习报销登记`
				} else if (method === 'edit') {
					this.title = '修改报销类型'
				}
				if (this.status === 'audit' || this.status === 'taskFormDetail') {
					method = 'view'
				}
				console.log('this.status', this.status)
				this.inputForm.id = id
				this.visible = true
				this.loading = false
				this.$nextTick(() => {
					this.loading = true
					reimburseRegisterService.findById(this.inputForm.id).then((data) => {
						this.inputForm.detailList = []
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm = JSON.parse(JSON.stringify(this.inputForm))

						if (this.commonJS.isEmpty(this.inputForm.detailList)) {
							this.inputForm.detailList = []
						}

						this.loading = false
					})
				})
			},
			close () {
				this.$refs.inputForm.resetFields()
				this.$refs.inputForm.detailList = []
				this.visible = false
			},
			reapplyForm (callback) {
				this.loading = true
				reimburseRegisterService.findById(this.inputForm.id).then((data) => {
					if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.startForm(callback)
					}
				})
			},
			// 暂存
			async saveForm (callback) {
				this.loading = true
				this.inputForm.type = '1'
				reimburseRegisterService.save(this.inputForm).then((data) => {
					callback()
					this.$refs.inputForm.resetFields()
					this.loading = false
				}).catch(() => {
					this.$refs.inputForm.resetFields()
					this.loading = false
				})
			},
			// 送审
			async startForm (callback) {
				this.inputForm.assignee = this.inputForm.projectManager
				this.$refs['inputForm'].validate(async (valid) => {
					if (valid) {
						this.loading = true

						if (this.commonJS.isEmpty(this.inputForm.detailList)) {
							this.$message.error('至少填写一条报销明细')
							this.loading = false
							return
						}
						this.inputForm.detailList.forEach((item, index) => {
							if (this.commonJS.isEmpty(item.workName)) {
								this.loading = false
								this.$message.warning('报销明细中第 ' + (index + 1) + ' 条数据的 “日志名称” 不能为空')
								throw new Error()
							}
							// 在这里执行对每个元素的操作
						});

						this.inputForm.type = '2'
						reimburseRegisterService.save(this.inputForm).then((data) => {
							this.inputForm.title = `${this.$store.state.user.name} 发起了 - [实习-报销登记]`
							this.inputForm.id = data.businessId
							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
					}
				})
			},

			// 通过
			async agreeForm (callback) {
				this.loading = true
				reimburseRegisterService.findById(this.inputForm.id).then((data) => {
					if (data.type !== '2') { // 审核状态不是“审核中”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.$refs['inputForm'].validate(async (valid) => {
							if (valid) {
								this.loading = true
								console.log('this.inputForm',this.inputForm)
								reimburseRegisterService.save(this.inputForm).then((data) => {
									callback(data.businessTable, data.businessId, this.inputForm)
									this.loading = false
								}).catch(() => {
									this.loading = false
								})
							} else {
								this.loading = false
							}
						})
					}
				})
			},
			// 修改状态
			updateStatusById (type, callback) {
				if (type === 'reject') {
					this.loading = true
					reimburseRegisterService.findById(this.inputForm.id).then((data) => {
						if (data.type !== '2') { // 审核状态不是“审核中”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.inputForm.type = '4'
							reimburseRegisterService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				} else if (type === 'hold') {
					this.loading = true
					reimburseRegisterService.findById(this.inputForm.id).then((data) => {
						if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						} else {
							this.inputForm.type = '1'
							reimburseRegisterService.updateStatusById(this.inputForm).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}
			},
			insertEvent(type) {
				if (type === 'base') {
					this.$refs.baseTable.insertAt({})
					this.inputForm.detailList.push({})
					this.baseKey = Math.random()
				}
			},
			footerMethod2({columns, data}) {
				const footerData = [
					columns.map((column, columnIndex) => {
						if (columnIndex === 0) {
							return '报销金额汇总(元)'
						}
						if (['reimbursementAmount'].includes(column.property)) {
							this.inputForm.allReimbursementAmount = XEUtils.sum(data, column.property)
							return XEUtils.sum(data, column.property)
						}
						return null
					})
				]
				return footerData
			},
			// 删除
			removeEvent(row, rowIndex, type) {
				if (type === 'base') {
					this.$refs.baseTable.remove(row)
					this.inputForm.detailList.splice(rowIndex, 1)
				}
			},
			openProgramPageForm(rowIndex) {
				console.log('this.inputForm.detailList', this.inputForm.detailList)
				if (this.commonJS.isEmpty(this.inputForm.detailList[0].workName) || this.inputForm.detailList.length === 1) {
					this.$refs.programPageForm.init()
				} else {
					if (this.commonJS.isEmpty(this.inputForm.detailList[0].programId)) {
						this.$refs.programPageForm.init('s')
					} else {
						this.$refs.programPageForm.init(false)
					}
				}
				this.programRow = rowIndex
			},
			getProgram(rows) {
				rows.forEach((item, index) => {
					this.inputForm.programId = item.id
					if (index === 0) {
						let r = this.inputForm.detailList[this.programRow]
						r.workName = item.workName
						r.createName = item.createName
						r.internshipDays = item.internshipDays
						r.workLogId = item.id
						r.reimbursementAmount = item.allMoney
						this.inputForm.detailList[this.programRow] = r
						this.baseKey = Math.random()
					} else {
						let r = {
							workName: item.workName,
							createName: item.createName,
							internshipDays: item.internshipDays,
							workLogId: item.id,
							reimbursementAmount: item.allMoney
						}
						this.$refs.baseTable.insertAt(r)
						this.inputForm.detailList.push(r)
						this.baseKey = Math.random()
					}
				})
				this.$forceUpdate()
				this.programRow = ''
			},
		}
	}
</script>
<style scoped>
	/deep/ .el-input-number .el-input__inner {
		text-align: left;
	}
</style>
<style>
	.vxe-select--panel {
		z-index: 9997 !important
	}
</style>
