<!--
 * @Description: 
 * @Author: @liulin
 * @Date: 2023-02-28 16:43:01
 * @LastEditors: Do not edit
 * @LastEditTime: 2023-02-28 16:43:23
-->
<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>
		<div class="bbsl-table-content" 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">
					{{ $t('common.save')}}
				</el-button>
				<el-button slot="reference" icon="el-icon-delete" @click="handleDelete" type="danger" v-if="statementData.authority.indexOf('del')!==-1">
					{{ $t('common.delete')}}
				</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-upload" @click="exportKPL">
					{{ $t('common.export') }}
				</el-button>
				<el-button type="info" icon="el-icon-upload">
					<a :href="actionUrl+'/qf/invest/productivity/downModel'"
						target="_blank">{{ $t('report.downLoad') }}</a>
				</el-button>
			</div>
			<el-table size="mini" v-loading="loading" ref="multipleSelection" :data="tableData" border
				:style="{width: '100%',height:'100%'}" :max-height="tableMaxHeight"
				:cell-style="{'text-align': 'center'}" :header-cell-style="{'text-align': 'center'}"
				@selection-change="handleSelectionChange">
				<el-table-column width="55" v-if="statementData.authority.indexOf('edited')!==-1">
					<template slot-scope="scope">
						<!-- {{scope.$index+1,tableData.length}} -->
						<i class="el-icon-plus" style="font-weight: bold;" v-if="scope.$index+1==tableData.length"
							@click="tableAdd"></i>
					</template>
				</el-table-column>
				<el-table-column type="selection" width="55"></el-table-column>
				<el-table-column prop="enterpriseName" label="（生成线）公司" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.enterpriseName" />
					</template>
				</el-table-column>
				<el-table-column prop="enterpriseCode" label="公司编码" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.enterpriseCode" />
					</template>
				</el-table-column>
				<el-table-column prop="banburyingNum" label="密炼产线条数" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.banburyingNum" />
					</template>
				</el-table-column>
				<el-table-column prop="banburyingCapacity" label="每条线年产能（万吨）" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.banburyingCapacity" />
					</template>
				</el-table-column>
				<el-table-column prop="banburyingCapacityTotal" label="密炼线总产能（万吨）" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.banburyingCapacityTotal" />
					</template>
				</el-table-column>
				<el-table-column prop="epdmNum" label="EPDM挤出线数" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number" v-model.trim="row.epdmNum" />
					</template>
				</el-table-column>
				<el-table-column prop="epdmCapacity" label="每条线年产能（百万米）" min-width="200">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.epdmCapacity" />
					</template>
				</el-table-column>
				<el-table-column prop="epdmCapacityTotal" label="EPDM挤出线总产能（百万米）" min-width="230">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.epdmCapacityTotal" />
					</template>
				</el-table-column>
				<el-table-column prop="tpeNum" label="TPE挤出线条数" min-width="230">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number" v-model.trim="row.tpeNum" />
					</template>
				</el-table-column>
				<el-table-column prop="tpeCapacity" label="每条线年产能（百万米）" min-width="230">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.tpeCapacity" />
					</template>
				</el-table-column>
				<el-table-column prop="tpeCapacityTotal" label="TPE挤出线总产能（百万米））" min-width="230">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" type="number"
							v-model.trim="row.tpeCapacityTotal" />
					</template>
				</el-table-column>
				<el-table-column prop="fillDate" label="填报时间" min-width="230">
					<template v-slot="{ row }">
						<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.fillDate" />
					</template>
				</el-table-column>
			</el-table>
			<!-- <div class="bbsl-pagination" ref="paginationPanel">
				 <el-button type="primary">保存</el-button>
			</div> -->

		</div>
		<!-- 导入弹框 -->
		<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/invest/productivity/importExcel'"
				:show-file-list="false" :data="uploadData" :on-success="handleAvatarSuccess" :on-progress="handleProgress"
				:on-error="handleAvatarError" :headers="header">
				<i class="el-icon-upload"></i>
				<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
				<!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</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 groupCapacity from '@/api/configureInfo/groupCapacity.js'
	export default {
		name: 'annualDeclineDetails',
		components: {},
		mixins: [TableMixin],
		data() {
			return {
				loading: false,
				dialogloading: false,
				config: {
					enterpriseName: '',
					enterpriseCode: '',
					banburyingNum: '',
					banburyingCapacity: '',
					banburyingCapacityTotal: '',
					epdmNum: '',
					epdmCapacity: '',
					epdmCapacityTotal: '',
					tpeNum: '',
					tpeCapacity: '',
					tpeCapacityTotal: '',
					fillDate: ''
				},
				tableData: [{
					enterpriseName: '',
					enterpriseCode: '',
					banburyingNum: '',
					banburyingCapacity: '',
					banburyingCapacityTotal: '',
					epdmNum: '',
					epdmCapacity: '',
					epdmCapacityTotal: '',
					tpeNum: '',
					tpeCapacity: '',
					tpeCapacityTotal: '',
					fillDate: '',
					fakeId: 0,
				}],
				multipleSelection: [],
				queryParam: {
					pageBean: {
						page: 1,
						pageSize: -1
					}
				},
				total: 0,
				jbList: [],
				parentId: 0,
				sortList: {},
				title: '',
				id: '',
				dialogVisible: false,
				actionUrl: '',
				uploadData: {
					mainId: ''
				},
			}
		},
		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
			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: {
			pasteMe(e) {
				let source = e.clipboardData.getData('Text')
				// 首先对源头进行解析
				let rows = source.split('\n') // 拆成很多行
				// if (rows.length - 1 > this.tableData.length) {
				// 	this.$notify.error({
				// 		title: '错误',
				// 		message: '赋值内容超出配置内容，请重试',
				// 	})
				// 	return
				// }
				// console.log(rows, 'rows')
				let keys = Object.keys(this.config) // 配置需要填写的keys的名
				// console.log(keys, 'keys')
				let arr = []
				for (let i = 0; i < rows.length - 1; i++) {
					if (rows[i] !== '') {
						let columns = rows[i].split('\t') // 已经按列划分
						// console.log(columns, '1111')
						let dataone = {} // 声明一行数组
						for (let j = 0; j < columns.length; j++) {
							// 读取demo里的第j对应的key值
							dataone[keys[j]] = columns[j]
						}
						for (let item of Object.keys(dataone)) {
							dataone[item] = dataone[item].replace(" %", "")
							if (item == 'fillDate') {
								let fillDate = dataone['fillDate'].replace('年', '-').replace('月', '-').replace('日', '')
									.split('-')
								if (fillDate[1] < 10) {
									fillDate[1] = '0' + fillDate[1]
								}
								if (fillDate[2] < 10) {
									fillDate[2] = '0' + fillDate[2]
								}
								dataone['fillDate'] = fillDate.join('-')
							}
						}
						this.tableData[i] = {
							...this.tableData[i],
							...dataone
						}
						this.tableData[i].fakeId = i
					}
				}
				this.tableData = [...this.tableData]
			},
			//获取数据
			getData() {				this.loading = true
				this.queryParam.querys = [{
					group: "main",
					operation: "EQUAL",
					parentGroup: "",
					property: "mainId",
					relation: "AND",
					value: this.id
				}]

				groupCapacity.detailQuery(this.queryParam, res => {
					if (res.rows) {
						this.tableData = res.rows.length > 0 ? res.rows : [{}]
						this.$set(this.tableData)
					}				this.loading = false
				})
			},

			//保存
			handleSave() {

				this.tableData.forEach(e => {
					delete e.fakeId
				})
				groupCapacity.editData({
					id: this.id,
					list: this.tableData
				}, res => {
					if (res.state) {
						this.$notify({
							type: 'success',
							message: this.$t('domestic.success'),
							duration: 2000,
						})
						this.$router.go(-1)
					}
				})

			},
			//删除
			handleDelete() {
				this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.fakeMultipleSelection.forEach(m => {
						const index = this.tableData.findIndex(item => item.id === m);
						this.tableData.splice(index, 1);
					})
					if (this.multipleSelection.length > 0) {
						groupCapacity.dleDetail(this.multipleSelection, res => {
							if (res.state) {
								this.$notify({
									type: 'success',
									message: this.$t('domestic.success'),
									duration: 2000,
								})
								this.getData()
							}
						})
					}
					this.multipleSelection = []
					this.fakeMultipleSelection = []
					// 清空所有选中状态
					this.$refs.multipleSelection.clearSelection();
				}).catch(() => {});
			},
			//表格选中
			handleSelectionChange(val) {
				this.multipleSelection = []
				this.fakeMultipleSelection = []
				this.$refs.multipleSelection.selection.forEach((item) => {
					if (item.id) {
						this.multipleSelection.push(item.id)
					} else if (item.fakeId) {
						this.fakeMultipleSelection.push(item.fakeId)
					}
				})
			},
			handleClose() {
				this.dialogVisible = false
			},
			//导出
			exportKPL() {
				groupCapacity.export({
					pageBean: {
						page: 1,
						pageSize: -1,

					},
				}, res => {})



			},
			//导入运营kpl数据
			importKPL() {
				if (!this.tableData[0].fakeId && !this.tableData[0].id) {
					this.dialogVisible = true
				} else {
					this.$confirm('此操作将覆盖表格数据, 是否继续?', 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
			},
			//添加
			tableAdd() {
				if (!this.tableData[0].fakeId && !this.tableData[0].id) {
					this.tableData[0].fakeId = 0
				}
				this.tableData.push({
					fakeId: this.tableData.length,
					enterpriseName: '',
					enterpriseCode: '',
					banburyingNum: '',
					banburyingCapacity: '',
					banburyingCapacityTotal: '',
					epdmNum: '',
					epdmCapacity: '',
					epdmCapacityTotal: '',
					tpeNum: '',
					tpeCapacity: '',
					tpeCapacityTotal: '',
					fillDate: ''
				})
			}
		}
	}
</script>

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