<template>
	<div>
		<el-dialog :title="title" :close-on-click-modal="false" draggable width="1200px" @close="close" append-to-body
			@keyup.enter.native="doSubmit" v-model="visible">
			<el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method === 'view' ? 'readonly' : ''"
				:disabled="method === 'view'" label-width="100px" @submit.native.prevent>

				<el-divider content-position="left"><i class="el-icon-document"></i> 基础信息</el-divider>
				<!-- <el-row>
					<el-col :span="12">
						<el-form-item label="报销项" prop="reimbursementType"
							:disabled="status === 'audit' || status === 'taskFormDetail'" :rules="[
								{ required: true, message: '报销项不能为空', trigger: 'blur' }
							]">
							<el-radio v-model="inputForm.reimbursementType"
								v-for="item in $dictUtils.getDictList('reimbursement_type')" :label="item.value"
								style="margin-right: 20px">
								{{ item.label }}</el-radio>
						</el-form-item>
					</el-col>
				</el-row> -->
				<el-row :gutter="26">
					<el-col :span="12">
						<el-form-item label="经办人" prop="userName">
							<el-input v-model="inputForm.userName" :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="departmentName">
							<el-input v-model="inputForm.departmentName" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="报销日期" prop="reimDate">
							<el-date-picker 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="12">
						<el-form-item label="报销类型" prop="sourceType">
							<el-select v-model="inputForm.sourceType" placeholder="请选择报销类型" style="width:100%;">
								<el-option v-for="item in $dictUtils.getDictList('cw_reimbursement_source_type')"
									:key="item.value" :label="item.label" :value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="inputForm.sourceType === '5'">
						<el-form-item label="采购编号" prop="purchaseNo" :rules="[{ required: true, message: '采购编号不能为空', trigger: 'blur' },
						{ required: true, message: '采购编号不能为空', trigger: 'change' }]">
							<el-input :readonly="true" @focus="openPurForm()" v-model="inputForm.purchaseNo"
								placeholder="请选择采购编号">
								<el-button slot="append" icon="el-icon-search" @click="openPurForm()"></el-button>
							</el-input>
						</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>
				<ReimbursementComponent ref="reimbursementComponent">
				</ReimbursementComponent>

			</el-form>
			<!-- 附件 -->
			<UpLoadComponent ref="uploadComponent"></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>
			<!--      <MaterialManagementDialog ref="materialManagementDialog" @getUpload="getUpload"></MaterialManagementDialog>-->
		</el-dialog>
	</div>
</template>

<script>
import ReimbursementApprovalService from '@/api/cw/reimbursementApproval/ReimbursementApprovalService'
import UpLoadComponent from '@/views/common/UpLoadComponent'
import InvoiceReimbursementUpLoadComponent from '@/views/common/InvoiceReimbursementUpLoadComponent'
import XEUtils from 'xe-utils'
// import MaterialManagementService from '@/api/materialManagement/MaterialManagementService'
// import MaterialManagementDialog from '../../../materialManagement/file/MaterialManagementDialog'
import ReimbursementComponent from '@/views/common/reimbursement/ReimbursementComponentTest.vue'
import InvoiceConfirmStatusService from '@/api/finance/invoice/InvoiceConfirmStatusService'
import { cwInfo } from "@/utils/businessInfo";

export default {
	data() {
		return {
			title: '',
			method: '',
			visible: false,
			loading: false,
			humanKeyProcured: '',
			inputForm: {
				reimbursementType: '0',
				userName: '',
				no: '',
				department: '',
				reimDate: '',
				remarks: '',
				detailInfos: [],
				detailInfoContracts: [],
				detailInfoReports: [],
				detailInfoOthers: [],
				detailInfoProcured: [],
				humanInfoProcured: [],
				invoiceReimbursements: [],
				invoiceReimbursementFiles: [], // 电子发票附件信息
				amountInfos: [],
				files: [], // 附件信息
				sourceType: '',
				preList: [],
				purchaseNo: '',
				tradeTotalPrice: '',
				purchaseId: '',
				procDefId: '',
				procDefKey: '',
				formTitle: '',
				departmentName: ''
			}
		}
	},
	reimbursementApprovalService: null,
	invoiceConfirmStatusService: null,

	// materialManagementService: null,
	created() {
		this.reimbursementApprovalService = new ReimbursementApprovalService()
		// this.materialManagementService = new MaterialManagementService()
		this.invoiceConfirmStatusService = new InvoiceConfirmStatusService()

	},
	components: {
		InvoiceReimbursementUpLoadComponent,
		UpLoadComponent,
		ReimbursementComponent
		// MaterialManagementDialog
	},
	methods: {
		initReimbursementComponent() {
			this.$refs.reimbursementComponent.initComponent("reimbursement", "cw", cwInfo.name, cwInfo.code, this.inputForm, this.isConfirm, this.status)
		},
		init(method, id) {
			this.method = method
			this.inputForm = {
				reimbursementType: '0',
				userName: '',
				no: '',
				department: '',
				reimDate: '',
				remarks: '',
				detailInfos: [],
				amountInfos: [],
				invoiceReimbursements: [],
				invoiceReimbursementFiles: [], // 电子发票附件信息
				files: [], // 附件信息
				detailInfoContracts: [],
				detailInfoReports: [],
				detailInfoOthers: [],
				detailInfoProcured: [],
				humanInfoProcured: [],
				sourceType: '',
				preList: [],
				purchaseNo: '',
				tradeTotalPrice: '',
				purchaseId: '',
				departmentName: ''
			}
			if (method === 'add') {
				this.title = `新建报销`
			} else if (method === 'edit') {
				this.inputForm.id = id
				this.title = '报销修改'
			} else if (method === 'view') {
				this.inputForm.id = id
				this.title = '报销详情'
			} else if (method === 'addChild') {
				this.title = '添加下级结构'
				this.inputForm.parentId = id
			}
			this.visible = true
			this.loading = false
			this.$nextTick(() => {
				if (method === 'edit' || method === 'view') { // 修改或者查看
					this.loading = true
					this.$refs.inputForm.resetFields()
					this.reimbursementApprovalService.findById(this.inputForm.id).then((data) => {
						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
						this.$refs.uploadComponent.clearUpload()
						// this.$refs.invoiceReimbursementUpLoadComponent.clearUpload()
						if (this.status === 'audit' || this.status === 'taskFormDetail') {
							method = 'view'
						}
						if (this.commonJS.isEmpty(this.inputForm.department)) {
							this.inputForm.department = this.$store.state.user.office.id
							this.inputForm.departmentName = this.$store.state.user.office.name
						}
						if (this.commonJS.isEmpty(this.inputForm.userId)) {
							this.inputForm.userId = this.$store.state.user.id
						}
						if (this.commonJS.isEmpty(this.inputForm.userName)) {
							this.inputForm.userName = this.$store.state.user.name
						}
						if (this.commonJS.isEmpty(this.inputForm.reimDate)) {
							this.inputForm.reimDate = new Date()
						}
						if (this.commonJS.isEmpty(this.inputForm.invoiceReimbursementFiles)) {
							this.inputForm.invoiceReimbursementFiles = []
						}
						if (this.commonJS.isEmpty(this.inputForm.files)) {
							this.inputForm.files = []
						}
						if (this.commonJS.isEmpty(this.inputForm.reimbursementType)) {
							this.inputForm.reimbursementType = '0'
						}
						// this.$refs.invoiceReimbursementUpLoadComponent.newUpload(method, this.inputForm.invoiceReimbursementFiles, 'reimbursement', 300, '电子发票附件')
						this.$refs.uploadComponent.newUpload(method, this.inputForm.files, 'reimbursement')
						this.inputForm = JSON.parse(JSON.stringify(this.inputForm))
						if (this.commonJS.isNotEmpty(this.inputForm.purchaseId)) {
							this.startPur(this.inputForm.purchaseId)
						}
						// 获取文件确认状态
						this.invoiceConfirmStatusService.getListByUser(this.inputForm.id).then(data => {
							// 先构建一个 Map 方便查找
							const statusMap = new Map(data.map(item => [item.invoiceId, item.status]));
							// 遍历 targetArray 给每项加 confirmStatus
							this.inputForm.invoiceReimbursementFiles.forEach(item => {
								const status = statusMap.get(item.id);
								if (status !== undefined) {
									item.confirmStatus = status;
								}
							});
						})
						this.initReimbursementComponent()

						this.loading = 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
						return XEUtils.sum(data, column.property)
					}
					return null
				})
			]
			return footerData
		},
		// 表单提交
		doSubmit() {
			this.$refs['inputForm'].validate((valid) => {
				if (valid) {
					this.loading = true
					if (this.$refs.uploadComponent.checkProgress()) {
						this.loading = false
						return
					}
					if (this.commonJS.isEmpty(this.inputForm.files)) {
						this.inputForm.files = []
					}
					this.inputForm.files = this.$refs.uploadComponent.getDataList()
					this.reimbursementApprovalTypeService.save(this.inputForm).then((data) => {
						this.close()
						this.$message.success(data)
						this.$emit('refreshDataList')
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
				}
			})
		},
		close() {
			this.$refs.inputForm.resetFields()
			this.inputForm.detailInfos = []
			this.inputForm.detailInfoContracts = []
			this.inputForm.detailInfoReports = []
			this.inputForm.detailInfoOthers = []
			this.inputForm.detailInfoProcured = []
			humanInfoProcured: [],
				this.inputForm.purchaseNo = ''
			this.inputForm.preList = ''
			this.inputForm.purchaseId = ''
			this.inputForm.amountInfos = []
			this.$refs.uploadComponent.clearUpload()
			this.visible = false
		},
		// 删除
		removeEvent(row, rowIndex, type) {
			if (type === 'detail') {
				this.$refs.detailTable.remove(row)
				this.inputForm.detailInfos.splice(rowIndex, 1)
			}
			if (type === 'amount') {
				this.$refs.amountTable.remove(row)
				this.inputForm.amountInfos.splice(rowIndex, 1)
			}
		},
		// 新增
		async insertEvent(type) {
			if (type === 'detail') {
				await this.$refs.detailTable.insert().then((data) => {
					this.inputForm.detailInfos.push(data)
				})
			}
			if (type === 'amount') {
				await this.$refs.amountTable.insert().then((data) => {
					this.inputForm.amountInfos.push(data)
				})
			}
		},
		startPur(id) {
			// this.materialManagementService.findById(id).then((data) => {
			//   this.inputForm.preList = data.detailInfos
			//   this.inputForm.purchaseNo = data.purchaseNo
			//   let i = this.inputForm.preList.length
			//   for (let j = 0; j < i; j++) {
			//     if (this.commonJS.isNotEmpty(this.inputForm.preList[j].tradePrice)) {
			//       if (this.commonJS.isNotEmpty(this.inputForm.preList[j].tradeNumber)) {
			//         this.inputForm.preList[j].priceSum = this.inputForm.preList[j].tradePrice * this.inputForm.preList[j].tradeNumber
			//       }
			//     }
			//   }
			// })
			this.$forceUpdate()
		},
		getPurChoose(row) {
			this.inputForm.purchaseId = row.id
			this.startPur(row.id)
		},
		footerMethod555({ columns, data }) {
			const footerData = [
				columns.map((column, columnIndex) => {
					if (columnIndex === 0) {
						return '商品总价'
					}
					if (['priceSum'].includes(column.property)) {
						// eslint-disable-next-line no-undef
						this.inputForm.tradeTotalPrice = XEUtils.sum(data, column.property)
						return XEUtils.sum(data, column.property)
					}
					return null
				})
			]
			return footerData
		},
		seeFileInfo(index) {
			if (this.commonJS.isEmpty(this.inputForm.preList[index].fileInfoLost)) {
				this.inputForm.preList[index].fileInfoLost = []
			}
			// this.$refs.materialManagementDialog.newUpload('view', this.inputForm.preList[index].fileInfoLost, null, null, null, null, null, false, index)
		},
		footerMethod1111({ columns, data }) {
			const footerData = [
				columns.map((column, columnIndex) => {
					if (columnIndex === 0) {
						return '汇总'
					}
					if (['amount'].includes(column.property)) {
						// eslint-disable-next-line no-undef
						return XEUtils.sum(data, column.property)
					}
					if (['taxAmount'].includes(column.property)) {
						// eslint-disable-next-line no-undef
						return XEUtils.sum(data, column.property)
					}
					if (['count'].includes(column.property)) {
						// eslint-disable-next-line no-undef
						return XEUtils.sum(data, column.property)
					}
					return null
				})
			]
			return footerData
		},
	}
}
</script>
