<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>
		{{statementData}}
		{{statementData.authority.indexOf('edited')}}
		<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">
						{{ $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/operation/newOrders/downModel'"
							target="_blank">{{ $t('report.downLoad') }}</a>
					</el-button>
				</div>
				<el-table size="mini" v-loading="loading" ref="multipleSelection" :data="tableData" border
					:max-height="tableMaxHeight" :style="{width: '100%'}" :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="salesReport" label="销售报告" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.salesReport" />
						</template>
					</el-table-column>
					<el-table-column prop="customerEn" label="客户（英文）" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.customerEn" />
						</template>
					</el-table-column>
					<el-table-column prop="customerCn" label="客户（中文）" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.customerCn" />
						</template>
					</el-table-column>
					<el-table-column prop="modelName" label="品牌" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.modelName" />
						</template>
					</el-table-column>
					<el-table-column prop="projectName" label="项目" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" 
								v-model.trim="row.projectName" />
						</template>
					</el-table-column>
					<el-table-column prop="nominationDate" label="提名时间" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe"
								v-model.trim="row.nominationDate" />
						</template>
					</el-table-column>
					<el-table-column prop="productiontime" label="量产时间" min-width="200">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" 
								v-model.trim="row.productiontime" />
						</template>
					</el-table-column>
					<el-table-column prop="revenue" label="年销售额(百万欧）" min-width="230">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" type="number"
								v-model.trim="row.revenue" />
						</template>
					</el-table-column>
					<el-table-column prop="revenueLifetime" label="生命周期销售额（百万欧）" min-width="230">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe" v-model.trim="row.revenueLifetime" />
						</template>
					</el-table-column>
					<el-table-column prop="enterpriseCode" label="承接工厂"
						min-width="230">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe"
								v-model.trim="row.enterpriseCode" />
						</template>
					</el-table-column>
					<el-table-column prop="ebitdaRate" label="当期平均EBITDA率"
						min-width="230">
						<template v-slot="{ row }">
							<el-input @paste.native.capture.prevent="pasteMe"
								v-model.trim="row.ebitdaRate" />
						</template>
					</el-table-column>
				</el-table>
				<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/operation/newOrders/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>
			</el-upload>
		</el-dialog>

	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import {
		TableMixin
	} from '@/mixins/tableMixin'
	import dictUtils from '@/components/dict/DictSelectUtils.js'
	import newOrder from '@/api/configureInfo/newOrder.js'
	export default {
		name: 'newOrderDetails',
		components: {},
		mixins: [TableMixin],
		data() {
			return {
				loading: false,
				dialogloading: false,
				config: {
					modelCode: '',
					modelName: '',
					nominationDate: '',
					sop: '',
					estimatedVolume: '',
					revenue: '',
					revenueLifetime: '',
					ebitdaRate: '',
					enterpriseCode: '',
					customerDevelopmentCenter: ''
				},
				tableData: [{
					modelCode: '',
					modelName: '',
					nominationDate: '',
					sop: '',
					estimatedVolume: '',
					revenue: '',
					revenueLifetime: '',
					ebitdaRate: '',
					enterpriseCode: '',
					customerDevelopmentCenter: '',
					fakeId: 0,
				}],
				multipleSelection: [],
				queryParam: {
					pageBean: {
						page: 1,
						pageSize: -1
					}
				},
				total: 0,
				jbList: [],
				parentId: 0,
				sortList: {},
				title: '',
				id: '',
				dialogVisible: false,
				actionUrl: '',
				uploadData: {
					mainId: ''
				},statementData:{}
			}
		},
		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
				}]

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

			//保存
			handleSave() {

				if (this.title == '新增') {
					this.tableData.forEach(e => {
						delete e.id
						delete e.fakeId
					})
					newOrder.saveData({
						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)
						}
					})
				} else if (this.title == '编辑') {
					newOrder.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) {
						newOrder.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() {
				newOrder.export(this.queryParam, 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,
					modelCode: '',
					modelName: '',
					nominationDate: '',
					sop: '',
					estimatedVolume: '',
					revenue: '',
					revenueLifetime: '',
					ebitdaRate: '',
					enterpriseCode: '',
					customerDevelopmentCenter: ''
				})
			}
		}
	}
</script>

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