<template xmlns:v-slot="http://www.w3.org/1999/XSL/Transform">
	<div>
		<el-dialog
			:title="title"
			:close-on-click-modal="false"
			draggable
			width="1400px"
			height="500px"
			@close="close"
			append-to-body
			v-model="visible">
			<el-row>
				<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="status === 'audit' || status === 'taskFormDetail'"
						 label-width="135px" @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="operator">
								<el-input v-model="inputForm.operator" :disabled="true"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="报销编号" prop="no">
								<el-input v-model="inputForm.no" :disabled="true"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="所属部门" prop="operatorOffice">
								<el-input v-model="inputForm.operatorOffice" :disabled="true"></el-input>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="报销日期" prop="reimDate" :rules="[{required: true, message:'请选择报销日期', trigger:'blur'}]">
								<el-date-picker
									placement="bottom-start"
									v-model="inputForm.reimDate"
									type="date"
									value-format="YYYY-MM-DD"
									style="width: 100%"
									placeholder="选择日期">
								</el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item label="备注" prop="remarks">
								<el-input v-model="inputForm.remarks"
										  type="textarea"
										  :rows="5"
										  maxlength="500"
										  placeholder="请输入简介"
										  show-word-limit>
								</el-input>
							</el-form-item>
						</el-col>
					</el-row>
					<el-divider content-position="left"><i class="el-icon-document"></i>
						项目报销详情
						<el-button style="margin-left: 20px" type="primary" :disabled="method==='view' || status === 'audit' || status === 'taskFormDetail'" @click="insertEvent('detail')" plain>
							新增
						</el-button>
					</el-divider>
					<el-row  :gutter="15" >
						<el-col :span="24">
							<vxe-table
								border
								show-footer
								show-overflow
								:footer-method="footerMethod"
								ref="detailTable"
								:key="detailKey"
								class="vxe-table-element"
								:data="inputForm.accountDetails"
								style="margin-left: 5em"
								highlight-current-row
								:edit-config="{trigger: 'click', mode: 'row', showStatus: true, autoClear: true, icon:'_'}"
								:edit-rules="validRules"
							>
								<vxe-table-column field="userName" title="报销人" :edit-render="{}" :rules="[{required: true, message:'请选择报销人', trigger:'blur'}]">
									<template v-slot:edit="scope">
										<el-input v-model="scope.row.userName" @focus="userPullListForm(scope.$rowIndex)"></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="deptName" title="报销部门" :edit-render="{}">
									<template v-slot:edit="scope">
										<el-input :disabled='true' v-model="scope.row.deptName" ></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="registerName" title="指定报销" :edit-render="{}" :rules="[{required: true, message:'请选择报销项目', trigger:'blur'}]">
									<template v-slot:edit="scope">
										<el-input v-model="scope.row.registerName" @focus="openProgramPageForm(scope.$rowIndex, scope.row)"></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="number" title="费用(元)" :edit-render="{}" :rules="[{required: true, message:'请输入费用', trigger:'blur'}]">
									<template v-slot:edit="scope">
										<el-input maxlength="15" v-model="scope.row.number" @keyup.native="scope.row.number = twoDecimalPlaces(scope.row.number)"></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="receiptNumber" title="收据张数" :edit-render="{}">
									<template v-slot:edit="scope">
										<el-input v-model="scope.row.receiptNumber" oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10"></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="days" title="出差天数" :edit-render="{}">
									<template v-slot:edit="scope">
										<el-input v-model="scope.row.days" oninput ="value=value.replace(/\D|^0/g,'')" maxlength="10"></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column field="content" title="内容" :edit-render="{}">
									<template v-slot:edit="scope">
										<el-input v-model="scope.row.content" ></el-input>
									</template>
								</vxe-table-column>
								<vxe-table-column title="操作" width="100">
									<template v-slot="scope">
										<el-button size="small" type="danger" @click="removeEvent(scope.row,scope.$rowIndex,'detail')">删除</el-button>
									</template>
								</vxe-table-column>
							</vxe-table>
						</el-col>
					</el-row>
				</el-form>
				<el-tabs v-model="activeName" type="border-card" style="width: 100%;margin-top: 20px" @tab-click="tabHandleClick">
					<el-tab-pane label="附件" name="enclosure">
						<!--        合同文件-->
						<UpLoadComponent ref="enclosure"></UpLoadComponent>
					</el-tab-pane>
				</el-tabs>
			</el-row>
			<template #footer>
			<span class="dialog-footer">
			  <el-button @click="close()" icon="el-icon-circle-close">关闭</el-button>
			  <el-button  v-if="method === 'edit'" type="primary" icon="el-icon-circle-check" @click="doSubmit()">确定</el-button>
			</span>
			</template>
		</el-dialog>
		<UserPullForm ref="userPullForm" @getProgramForUser="getProgramForUser"></UserPullForm>
		<RegisterChoose ref="registerChoose" @getProgram="getProgram"></RegisterChoose>
	</div>
</template>

<script>
	import UpLoadComponent from '@/views/common/UpLoadComponent'
	import reimburseSubmitAccountService from '@/api/human/register/ReimburseSubmitAccountService'
	import UserPullForm from '@/views/finance/invoice/UserPullForm'
	import XEUtils from "xe-utils";
	import RegisterChoose from './ReimburseRegisterChoose'

	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				validRules: {
					userName: [
						{required: true, message: '报销人不能为空'}
					],
					deptName: [
						{required: true, message: '报销部门不能为空'}
					],
					registerName: [
						{required: true, message: '指定报销不能为空'}
					],
					number: [
						{required: true, message: '费用(元)不能为空'}
					]
				},
				title: '',
				method: '',
				visible: false,
				loading: false,
				indexRow: '',
				inputForm: {
					userId: '',
					procInsId: '',
					operator: '',
					no: '',
					operatorOffice: '',
					operatorOfficeId: '',
					reimDate: '',
					remarks: '',
					totalNum: '',
					accountDetails: [],
					files: [],
				},
				activeName: 'enclosure',
				keyWatch: '',
				detailKey: '',
			}
		},
		created () {
		},
		components: {
			UserPullForm,
			RegisterChoose,
			UpLoadComponent,
		},
		computed: {
			bus: {
				get () {
					this.$refs.enclosure.setDividerName('附件', false)
					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)
					this.$refs.enclosure.changeLoading(newVal)
				}
			}
		},
		methods: {
			getKeyWatch (keyWatch) {
				this.keyWatch = keyWatch
			},
			getUpload () {
			},
			init (method, id) {
				this.method = method
				this.activeName = 'enclosure'
				this.inputForm = {
					userId: '',
					procInsId: '',
					operator: '',
					no: '',
					operatorOffice: '',
					operatorOfficeId: '',
					reimDate: '',
					remarks: '',
					totalNum: '',
					accountDetails: [],
					files: [],
				}
				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
					reimburseSubmitAccountService.findById(this.inputForm.id).then((data) => {
						this.$refs.enclosure.clearUpload()
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm = JSON.parse(JSON.stringify(this.inputForm))

						if (this.commonJS.isEmpty(this.inputForm.operator)) {
							this.inputForm.operator = this.$store.state.user.name
						}

						if (this.commonJS.isEmpty(this.inputForm.operatorOffice)) {
							this.inputForm.operatorOfficeId = this.$store.state.user.office.id
							this.inputForm.operatorOffice = this.$store.state.user.office.name
						}
						this.$refs.enclosure.newUpload(method, this.inputForm.files, 'submitAccount', null, null, null, null, false)
						this.loading = false
					})
					if (method !== 'edit' && method !== 'view') {
						this.$refs.enclosure.newUpload(method, [], 'submitAccount', null, null, null, null, false)
					}
				})
			},
			// 表单提交
			doSubmit () {
				this.$refs['inputForm'].validate((valid) => {
					if (valid) {
						this.loading = true
						if (this.$refs.enclosure.checkProgress()) {
							this.loading = false
							return
						}
						this.inputForm.files = this.$refs.enclosure.getDataList()
						reimburseSubmitAccountService.save(this.inputForm).then((data) => {
							this.close()
							this.$message.success(data)
							this.$emit('refreshList')
							this.loading = false
						}).catch(() => {
							this.loading = false
						})
					}
				})
			},
			close () {
				this.$refs.inputForm.resetFields()
				this.inputForm.accountDetails = []
				this.$refs.enclosure.clearUpload()
				this.visible = false
			},
			footerMethod ({ columns, data }) {
				const footerData = [
					columns.map((column, columnIndex) => {
						if (columnIndex === 0) {
							return '总报销费用'
						}
						if (['number'].includes(column.property)) {
							// eslint-disable-next-line no-undef
							this.inputForm.totalNum = XEUtils.sum(data, column.property)
							return XEUtils.sum(data, column.property)
						}
						return null
					})
				]
				return footerData
			},
			// 新增
			async insertEvent (type) {
				if (type === 'detail') {
					let d = {
						userName: this.$store.state.user.name,
						deptName: this.$store.state.user.office.name,
						userId: this.$store.state.user.id,
						deptId: this.$store.state.user.office.id
					}
					if (this.commonJS.isEmpty(this.inputForm.accountDetails)) {
						this.inputForm.accountDetails = []
					}
					this.$refs.detailTable.insertAt(d)
					this.inputForm.accountDetails.push(d)
					this.detailKey = Math.random()
				}
			},
			// 报销人下拉弹窗
			userPullListForm (rowIndex) {
				this.indexRow = rowIndex
				this.$refs.userPullForm.init()
			},
			getProgramForUser (rows) {
				this.inputForm.accountDetails[this.indexRow].userId = rows[0].id
				this.inputForm.accountDetails[this.indexRow].userName = rows[0].name
				this.inputForm.accountDetails[this.indexRow].deptId = rows[0].parentId
				this.inputForm.accountDetails[this.indexRow].deptName = rows[0].officeName
				this.indexRow = ''
				this.$forceUpdate()
			},
			twoDecimalPlaces (num) {
				let str = num.toString()
				var len1 = str.substr(0, 1)
				var len2 = str.substr(1, 1)
				// eslint-disable-next-line eqeqeq
				if (str.length > 1 && len1 == 0 && len2 != '.') {
					str = str.substr(1, 1)
				}
				// eslint-disable-next-line eqeqeq
				if (len1 == '.') {
					str = ''
				}
				// eslint-disable-next-line eqeqeq
				if (str.indexOf('.') != -1) {
					var str_ = str.substr(str.indexOf('.') + 1)
					// eslint-disable-next-line eqeqeq
					if (str_.indexOf('.') != -1) {
						str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
					}
					if (str_.length > 2) {
						this.$message.warning(`金额小数点后只能输入两位，请正确输入！`)
						return (str = '')
					}
				}
				// eslint-disable-next-line no-useless-escape
				str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
				return str
			},
			// 删除
			removeEvent (row, rowIndex, type) {
				if (type === 'detail') {
					this.$refs.detailTable.remove(row)
					this.inputForm.accountDetails.splice(rowIndex, 1)
				}
			},
			openProgramPageForm (rowIndex, row) {
				this.indexRow = rowIndex
				this.$refs.registerChoose.init()
			},
			getProgram (rows) {
				if (this.commonJS.isNotEmpty(rows)) {
					this.inputForm.accountDetails[this.indexRow].registerId = rows.map(item => { return item.id }).join(',')
					this.inputForm.accountDetails[this.indexRow].registerName = rows.map(item => { return item.reimbuserName }).join(',')
					this.inputForm.accountDetails[this.indexRow].number = rows.totalNum
					this.detailKey = Math.random()
				}
				this.indexRow = ''
				this.$forceUpdate()
			},
			tabHandleClick (event) {
				// console.log(event)
			},
		}
	}
</script>
