<template>
	<div class="bbsl-common-page" v-loading="loading">
		<div class="bbsl-table-search">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item :to="{path: '/platLayout/reportFilling'}">{{
                    $t('report.rootNode')
                }}</el-breadcrumb-item>
				<el-breadcrumb-item :to="{
                        path:
                            '/platLayout/reportFillingComp?id=' +
                            this.$route.query.reportId,
                    }">
					{{
                        $i18n.locale === 'zh-CN'
                            ? this.$route.query.parentName
                            : this.$route.query.parentNameEn
                    }}
				</el-breadcrumb-item>
				<el-breadcrumb-item>{{ this.$route.query.fillYear }}-{{
                        this.$route.query.fillMonth < 10 ? '0' : ''
                    }}{{ this.$route.query.fillMonth }}
					{{ $t('report.detailNode') }}
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<el-row :gutter="10" class="card-table flex">
			<el-col class="card-table-container" style="width: 100%" ref="contentPanel">
				<div class="bbsl-btn-content" ref="btnPanel">
					<el-button icon="el-icon-plus" type="primary" class="btn btn-plus" @click="handleSave" v-if="statementData.authority.indexOf('edited')!==-1"
						:disabled="!hasData">
						{{ $t('common.save') }}
					</el-button>
					<el-button type="success" icon="el-icon-upload" @click="importKPL" v-if="statementData.authority.indexOf('edited')!==-1">{{ $t('common.import') }}
					</el-button>
					<el-button type="warning" icon="el-icon-download" @click="exportKPL">
						{{ $t('common.export') }}
					</el-button>
					<el-button type="info" icon="el-icon-download">
						<a :href="actionUrl + '/qf/finance/plBudget/downModel'"
							target="_blank">{{ $t('report.downLoad') }}</a>
					</el-button>
				</div>

				<ux-grid border size="mini" v-if="hasData" :data="tableData" v-loading="loading" keep-source
					 show-summary :edit-config="{ trigger: 'click', mode: 'cell' }" 
					ref="multipleSelection" :style="{width: '100%'}" :max-height="tableMaxHeight"
					:header-cell-style="{'text-align': 'center'}">
					<ux-table-column field="subjectName" title="subjectName" min-width="200" show-overflow-tooltip
						fixed="left">
					</ux-table-column>
					<ux-table-column field="subjectCode" title="subjectCode" min-width="160" align="center"
						show-overflow-tooltip fixed="left">
					</ux-table-column>
					<ux-table-column field="subjectUnit" title="subjectUnit" min-width="100" align="center"
						show-overflow-tooltip fixed="left">
					</ux-table-column>
					<ux-table-column v-for="(value, key) in tableHearder" :key="key" :field="key" :title="key"
						min-width="120" align="center">
						<template slot-scope="scope">
							<el-input type="number" v-model.trim="scope.row[key]" @change="
                                    (val) =>
                                        changeData(val, scope.row.subjectCode, key)
                                " />
						</template>
					</ux-table-column>
					<ux-table-column v-for="(item, index) in totalheader" :key="item" :field="item" :title="item"
						:min-width="index == 2 ? 260 : 160" align="center">
						<template slot-scope="scope">
							<el-input type="number" v-model.trim="scope.row[item]" @change="
                                    (val) =>
                                        changeData(val, scope.row.subjectCode, item)
                                " />
						</template>
					</ux-table-column>
				</ux-grid>
				<el-empty v-if="!loading && !hasData" :description="$t('report.importTemp')">
					<el-button type="success" icon="el-icon-upload" @click="importKPL">{{ $t('common.import') }}
					</el-button>
				</el-empty>
				<el-col ref="paginationPanel"></el-col>
			</el-col>
		</el-row>
		<!-- 导入弹框 -->
		<el-dialog :title="$t('common.import')" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" v-loading="dialogloading" element-loading-text="拼命导入中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
			<el-upload class="upload-demo" drag :action="actionUrl + '/qf/finance/plBudget/importExcel'"
				:data="uploadData" :show-file-list="false" :on-success="handleAvatarSuccess"  :on-progress="handleProgress"
				:on-error="handleAvatarError"  :headers="header">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">
					{{ $t('report.importTips')
                    }}<em>{{ $t('report.importTipsLoad') }}</em>
				</div>
			</el-upload>
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import {
		TableMixin
	} from '@/mixins/tableMixin'
	import dictUtils from '@/components/dict/DictSelectUtils.js'
	import profitBudget from '@/api/configureInfo/profitBudget.js'
	export default {
		name: 'profitBudgetDetails',
		components: {},
		mixins: [TableMixin],
		data() {
			return {
				hasData: false,
				loading: false,
				dialogloading: false,
				tableData: [],
				tableHearder: {}, // 表头
				multipleSelection: [],
				queryParam: {
					pageBean: {
						page: 1,
						pageSize: -1,
					},
				},
				total: 0,
				jbList: [],
				parentId: 0,
				sortList: {},
				title: '',
				id: '',
				dialogVisible: false,
				actionUrl: '',
				uploadData: {
					mainId: '',
				},
				modifyData: {},
				totalheader: [
					'Total',
					'Consolidation Posting',
					'Consolidated Financial Statement',
				],
				totalKey: {
					Total: 'budgetTotal',
					'Consolidation Posting': 'budgetPosting',
					'Consolidated Financial Statement': 'budgetConsolidated',
				},
			}
		},
		watch: {},

		created() {
			this.statementData=JSON.parse(window.localStorage.getItem("statementData"))
			if (this.$i18n.locale === 'zh-CN') {
				this.jbList = dictUtils.getDictItemsFromCache('jb')
			} else {
				this.jbList = dictUtils.getDictItemsFromCache('jb_en')
			}
			this.actionUrl = window.context.portal
			console.log(this.$route.query)
			this.title = this.$route.query.name ? this.$route.query.name : '编辑'
			this.id = this.$route.query.id
			this.uploadData.mainId = this.$route.query.id
			this.title == '编辑' ? this.getData() : ''
		},
		computed: mapState({
			header: (state) => {
				return {
					Authorization: `Bearer ${state.login.currentUser.token}`,
				}
			},
		}),
		mounted() {},
		methods: {
			changeData(value, code, column) {
				if (this.modifyData[code]) {
					this.modifyData[code][column] = value
				} else {
					this.modifyData[code] = {
						[column]: value,
					}
				}
			},
			//获取数据
			getData() {
				this.loading = true
				this.queryParam.querys = [{
					group: 'main',
					operation: 'EQUAL',
					parentGroup: '',
					property: 'mainId',
					relation: 'AND',
					value: this.id,
				}, ]

				profitBudget.headerDetailQuery(this.queryParam, (res) => {
					console.log(res)
					if (res.state) {
						console.log(res)
						let length = res.value.length
						if (length) {
							this.hasData = true
							this.tableHearder = res.value[0]
							delete this.tableHearder.subjectName
							delete this.tableHearder.subjectCode
							delete this.tableHearder.subjectUnit
							delete this.tableHearder.subjectLevel
							delete this.tableHearder.Total
							delete this.tableHearder['Consolidation Posting']
							delete this.tableHearder[
								'Consolidated Financial Statement'
							]
							res.value.splice(0, 1)
							this.tableData = res.value
							let tempData = res.value
							tempData.forEach((item) => {
								let space = ''
								let level = parseInt(item.subjectLevel)
								if (level) {
									for (let i = 1; i <= level; i++) {
										space += '\xa0'
									}
								}
								item.subjectName = space + item.subjectName
							})
							this.$set(this.tableData)
						} else {
							this.hasData = false
						}
					}
					this.loading = false
				})
			},

			//保存
			handleSave() {
				let keys = Object.keys(this.modifyData)
				if (!keys.length) {
					this.$message({
						message: this.$t('report.unchanged'),
						type: 'warning',
					})
				} else {
					// 数据提交格式组装
					// dataUpload 动态字段
					// totalListUpload 固定统计字段
					// 动态字段格式
					//   [{
					//      subjectCode:'',
					//      budgetYtd:'',
					//      enterpriseCode: ''
					//    },{
					//      subjectCode:'',
					//      budgetYtd:'',
					//      enterpriseCode: ''
					//  }]
					//  固定统计字段格式
					//   [{
					//      subjectCode:'',
					//      budgetTotal:'',
					//      budgetPosting: '',
					//      budgetConsolidated:''
					//    },{
					//      subjectCode:'',
					//      budgetTotal:'',
					//      budgetPosting: '',
					//      budgetConsolidated:''
					//  }]
					let dataUpload = []
					let totalListUpload = []
					for (let key in this.modifyData) {
						let totalObj = {}

						for (let valKey in this.modifyData[key]) {
							let obj = {}
							obj.subjectCode = key
							if (!this.totalheader.includes(valKey)) {
								obj.enterpriseCode = valKey
								obj.budgetYtd = this.modifyData[key][valKey]
								dataUpload.push(obj)
							}
							if (this.totalheader.includes(valKey)) {
								totalObj.subjectCode = key
								totalObj[this.totalKey[valKey]] =
									this.modifyData[key][valKey]
							}
						}
						if (totalObj.subjectCode) {
							totalListUpload.push(totalObj)
						}
					}
					profitBudget.batchUpdateData({
							id: this.id,
							list: dataUpload,
							totalList: totalListUpload,
						},
						(res) => {
							if (res.state) {
								this.modifyData = {}
								this.$notify({
									type: 'success',
									message: this.$t('domestic.success'),
									duration: 2000,
								})
								this.getData()
								// this.$router.go(-1)
							}
						}
					)
				}
			},
			handleClose() {
				this.dialogVisible = false
			},
			//导出
			exportKPL() {
				profitBudget.export(this.queryParam, (res) => {})
			},
			//导入运营kpl数据
			importKPL() {
				if (!this.tableData.length) {
					this.dialogVisible = true
				} else {
					this.$confirm(
							this.$t('report.importCoverTips'),
							this.$t('common.tips'), {
								confirmButtonText: this.$t('common.confirm'),
								cancelButtonText: this.$t('common.cancel'),
								type: 'warning',
							}
						)
						.then(() => {
							this.dialogVisible = true
						})
						.catch(() => {})
				}
			},
			//上传成功
			handleAvatarSuccess(res, file) {
				this.dialogVisible = false
				this.dialogloading = false
				this.$notify({
					type: 'success',
					message: this.$t('domestic.success'),
					duration: 2000,
				})
				this.getData()
			},
			handleAvatarError(err, file, fileList) {
				this.dialogVisible = false
				this.dialogloading = false
				this.$notify({
					type: 'error',
					message: this.$t('domestic.failure'),
					duration: 2000,
				})
			},
			handleProgress(event, file, fileList) {
				this.dialogloading = true
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "~@/assets/css/fillDetail.scss";
</style>
