<template>
	<div class="content-main">
		<el-tabs v-model="activeName" @tab-click="handletabClick">
			<el-tab-pane label="进销存表" name="inventory"></el-tab-pane>
			<el-tab-pane label="库存年限表" name="age"></el-tab-pane>
			<el-tab-pane label="库存分布表" name="distribution"></el-tab-pane>
		</el-tabs>
		<el-form :inline="true" :model="searchForm" class="search-bm-boder">
			<el-row>
        		<el-form-item label="汇总期数:">
					<el-date-picker
						v-model="searchForm.hzqs"
						type="month"
						clearable
						value-format="yyyy-MM"
						placeholder="请选择汇总期数"
					></el-date-picker>
        		</el-form-item>
        		<el-form-item label="汇总日期:" prop="dateList">
        		  <el-date-picker
        		    class="dateInputCompatible"
        		    clearable
        		    v-model="searchForm.dateList"
        		    type="daterange"
        		    range-separator="至"
        		    start-placeholder="开始日期"
        		    end-placeholder="结束日期"
        		    value-format="yyyy-MM-dd"
        		  ></el-date-picker>
        		</el-form-item>
				<el-form-item>
					<div class="search-button">
						<span class="search-line"></span>
						<el-button
							type="primary"
							size="small"
							class="iconfont iconchaxun"
							@click="searchInfo"
							>查询</el-button
						>
						<el-button
							type="primary"
							@click="reSetForm"
							size="small"
							class="iconfont iconzhongzhi"
							>重置</el-button
						>
					</div>
				</el-form-item>
			</el-row>
		</el-form>
		<el-row class="exportBtnBg">
			<el-button
				type="primary"
				class="iconfont icondaochu11"
				size="small"
				@click="handleAdd"
				>生成汇总表</el-button
			>
		</el-row>
		<el-table :data="tableData" border stripe tooltip-effect="dark">
			<el-table-column
     		   type="index"
     		   label="序号"
     		   align="center"
     		   width="60"
     		 ></el-table-column>
			<el-table-column
				prop="hzqs"
				label="汇总期数"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column
				prop="hzrq"
				label="汇总日期"
				align="center"
				show-overflow-tooltip
			></el-table-column>
			<el-table-column
				prop="qckc"
				label="期初库存"
				align="center"
				show-overflow-tooltip
				v-if="activeName == 'inventory'"
			>
          		<template slot-scope="scope">
					{{
          		    	String(scope.row.qckc).indexOf(".") > -1
          		    	  ? Number(scope.row.qckc).toLocaleString(undefined, {
          		    	      minimumFractionDigits: 3,
          		    	      maximumFractionDigits: 3,
          		    	    })
          		    	  : Number(scope.row.qckc).toLocaleString()
          		  	}}
          		</template>
			</el-table-column>
			<el-table-column
				prop="qmkc"
				label="期末库存"
				align="center"
				show-overflow-tooltip
			>
          		<template slot-scope="scope">
					{{
          		    	String(scope.row.qmkc).indexOf(".") > -1
          		    	  ? Number(scope.row.qmkc).toLocaleString(undefined, {
          		    	      minimumFractionDigits: 3,
          		    	      maximumFractionDigits: 3,
          		    	    })
          		    	  : Number(scope.row.qmkc).toLocaleString()
          		  	}}
          		</template>
			</el-table-column>
			<el-table-column
				align="center"
				label="操作"
				width="120"
			>
				<template slot-scope="scope">
					<el-tooltip
						class="item"
						effect="light"
						content="查看"
						placement="top"
					>
						<el-button
							type="primary"
							size="small"
							@click="showInfo(scope.row)"
							class="operate_show_btn iconfont iconchakan2"
						></el-button>
					</el-tooltip>
					<el-tooltip
						class="item"
						effect="light"
						content="删除"
						placement="top"
						v-if="scope.$index == 0"
					>
						<el-button
							type="primary"
							size="small"
							@click="editInfo(scope.row)"
							class="operate_delete_btn iconfont iconshanchu"
						></el-button>
					</el-tooltip>
				</template>
			</el-table-column>
		</el-table>
		<el-row class="pagination-wrap">
			<el-pagination
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
				:current-page="pageForm.pageNum"
				:page-sizes="[10, 20, 30, 40]"
				:page-size="pageForm.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageForm.total"
			></el-pagination>
		</el-row>
	</div>
</template>

<script>
import { authorityControl } from '@/api/login/login'
import {
	selectJxcbbList,
	selectKcnfbList,
	selectKcfbList,
	deleteJxcbb,
	deleteKcnfb,
	deleteKcfb,
} from '@/api/unregulatedReserves/reportSummary/index'
import { getNowDate1 } from '@/utils'
export default {
	data() {
		return {

			searchShowMoreBool: false,
			tableData: [],
			listLoading: true,
			searchForm: {
				hzqs: '',
				dateList: [],
			},
			pageForm: {
				pageNum: 1,
				pageSize: 10,
				total: 1,
			},
			buttonNameList: [],

			activeName: 'inventory', //进销存，年限表，分布表
			dialogVisible: false,
			dialogData: {
				tsbz: '',
				yy: '',
				bjr: '',
				bjrq: '',
			},
			isShow: false,
		}
	},
	created() {
		// this.getresourceCode();
		if (this.$route.query.activeName == ""||this.$route.query.activeName == "inventory") {
			this.activeName = 'inventory'
		}else if (this.$route.query.activeName == "age") {
			this.activeName = "age"
		}else if (this.$route.query.activeName == "distribution") {
			this.activeName = "distribution"
		}
		this.getCcList('start')
	},
	methods: {
		getCcList(type) {
			if (type != 'start') {
				//非初始化调用：查询、分页
				sessionStorage.setItem(
					'searchData',
					JSON.stringify(this.searchForm)
				)
				sessionStorage.setItem(
					'pageData',
					JSON.stringify(this.pageForm)
				)
			} else {
				//初始化分两种情况，详情页等返回后的初始化，以及第一次进入此菜单的初始化
				if (JSON.parse(sessionStorage.getItem('searchData'))) {
					//详情页返回后，将对应查询条件和分页的字段赋值，页面回显参数
					this.searchForm = JSON.parse(
						sessionStorage.getItem('searchData')
					)
					this.pageForm = JSON.parse(
						sessionStorage.getItem('pageData')
					)
				} else {
					//第一次进去此菜单时，保存上方默认的data
					sessionStorage.setItem(
						'searchData',
						JSON.stringify(this.searchForm)
					)
					sessionStorage.setItem(
						'pageData',
						JSON.stringify(this.pageForm)
					)
				}
			}
			let data = {
				...this.searchForm,
				...this.pageForm,
			}
			if (this.searchForm.dateList) {
				data.hzrqStart = this.searchForm.dateList[0]
				data.hzrqEnd = this.searchForm.dateList[1]
			} else {
				data.hzrqStart = null
				data.hzrqEnd = null
			}
			if (this.activeName == 'inventory') {
				selectJxcbbList(data)
					.then((res) => {
						if (res.infoCode == 200) {
							this.tableData = res.data.items || []
							this.pageForm.total = res.data.total
						}
					})
					.catch((err) => {
						console.log(err)
					})
			} else if (this.activeName == 'age') {
				selectKcnfbList(data)
					.then((res) => {
						if (res.infoCode == 200) {
							this.tableData = res.data.items || []
							this.pageForm.total = res.data.total
						}
					})
					.catch((err) => {
						console.log(err)
					})
			} else if (this.activeName == 'distribution') {
				selectKcfbList(data)
					.then((res) => {
						if (res.infoCode == 200) {
							this.tableData = res.data.items || []
							this.pageForm.total = res.data.total
						}
					})
					.catch((err) => {
						console.log(err)
					})
			}
		},

		reSetForm() {
			this.searchForm = {
				hzqs: '',
				dateList: [],
			}
			this.pageForm.pageNum = 1
			this.getCcList()
		},

		//点击搜索时
		searchInfo() {
			this.pageForm.pageNum = 1
			this.getCcList()
		},
		//点击查看
		showInfo(row) {
			if (this.activeName == 'inventory') {
				this.$router.push({
					name: 'reportSummaryDetail',
					query: {
						state: 'detail',
						hzqs: row.hzqs,
					},
				})
			} else if (this.activeName == 'age') {
				this.$router.push({
					name: 'RsummarydetailYear',
					query: {
						state: 'detail',
						hzqs: row.hzqs,
					},
				})
			} else if (this.activeName == 'distribution') {
				this.$router.push({
					name: 'RsdetailDistribution',
					query: {
						state: 'detail',
						hzqs: row.hzqs,
					},
				})
			}
		},
		//点击删除
		async editInfo(row) {
      		await this.$confirm("是否确认删除？", "提示", {
      		  confirmButtonText: "确定",
      		  cancelButtonText: "取消",
      		  type: "warning",
      		});
			if (this.activeName == 'inventory') {
				deleteJxcbb(row.id)
					.then((res) => {
						if (res.infoCode == 200) {
							this.$message.success('删除成功')
							this.getCcList()
						}
					})
					.catch((err) => {
						console.log(err)
					})
			} else if (this.activeName == 'age') {
				deleteKcnfb(row.id)
					.then((res) => {
						if (res.infoCode == 200) {
							this.$message.success('删除成功')
							this.getCcList()
						}
					})
					.catch((err) => {
						console.log(err)
					})
			} else if (this.activeName == 'distribution') {
				deleteKcfb(row.id)
					.then((res) => {
						if (res.infoCode == 200) {
							this.$message.success('删除成功')
							this.getCcList()
						}
					})
					.catch((err) => {
						console.log(err)
					})
			}
		},
		//点击生成
		handleAdd() {
			let newHzqs = ""
			if (this.tableData.length>0) {
				newHzqs = this.tableData[0].hzqs.substr(5,2)
				if (newHzqs < 9) {
					newHzqs = this.tableData[0].hzqs.substr(0,6) + (Number(newHzqs)+1)
				}else if (newHzqs >= 9 && newHzqs != "12") {
					newHzqs = this.tableData[0].hzqs.substr(0,5) + (Number(newHzqs)+1)
				}else if (newHzqs == "12") {
					newHzqs = Number(this.tableData[0].hzqs.substr(0,4))+1 + "-" + "01"
				}
			}else{
				newHzqs = getNowDate1()
			}
			if (this.activeName == 'inventory') {
				this.$router.push({
					name: 'reportSummaryDetail',
					query: {
						state: 'add',
						hzqs: newHzqs,
					},
				})
			} else if (this.activeName == 'age') {
				this.$router.push({
					name: 'RsummarydetailYear',
					query: {
						state: 'add',
						hzqs: newHzqs,
					},
				})
			} else if (this.activeName == 'distribution') {
				this.$router.push({
					name: 'RsdetailDistribution',
					query: {
						state: 'add',
						hzqs: newHzqs,
					},
				})
			}
		},
		//导出
		handleExport(row) {
			let data = {
				...this.searchForm,
				...this.pageForm,
			}
			if (this.searchForm.dateList) {
				data.hzrqStart = this.searchForm.dateList[0]
				data.hzrqEnd = this.searchForm.dateList[1]
			} else {
				data.hzrqStart = null
				data.hzrqEnd = null
			}
			if (this.activeName == 'statistics') {
				dcjlExport(data)
					.then((res) => {
						let exportName = '交易统计表.xlsx'
						let blob = new Blob([res], {
							type: 'application/vnd.ms-excel;charset=utf-8',
						})
						if (
							!!window.ActiveXObject ||
							'ActiveXObject' in window
						) {
							window.navigator.msSaveOrOpenBlob(blob, exportName)
						} else {
							const link = document.createElement('a')
							link.style.display = 'none'
							link.href = URL.createObjectURL(blob)
							link.setAttribute('download', exportName)
							document.body.appendChild(link)
							link.click()
							document.body.removeChild(link)
						}
					})
					.catch()
			} else {
				dcjyhzExport(data)
					.then((res) => {
						let exportName = '交易汇总表.xlsx'
						let blob = new Blob([res], {
							type: 'application/vnd.ms-excel;charset=utf-8',
						})
						if (
							!!window.ActiveXObject ||
							'ActiveXObject' in window
						) {
							window.navigator.msSaveOrOpenBlob(blob, exportName)
						} else {
							const link = document.createElement('a')
							link.style.display = 'none'
							link.href = URL.createObjectURL(blob)
							link.setAttribute('download', exportName)
							document.body.appendChild(link)
							link.click()
							document.body.removeChild(link)
						}
					})
					.catch()
			}
		},

		//分页
		handleSizeChange(val) {
			this.pageForm.pageSize = val
			this.getCcList()
		},
		handleCurrentChange(val) {
			this.pageForm.pageNum = val
			this.getCcList()
		},
		//定义导出Excel表格事件
		exportExcel() {
			/* 从表生成工作簿对象 */
			var wb = XLSX.utils.table_to_book(
				document.querySelector('#out-table')
			)
			/* 获取二进制字符串作为输出 */
			var wbout = XLSX.write(wb, {
				bookType: 'xlsx',
				bookSST: true,
				type: 'array',
			})
			try {
				FileSaver.saveAs(
					//Blob 对象表示一个不可变、原始数据的类文件对象。
					//Blob 表示的不一定是JavaScript原生格式的数据。
					//File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
					//返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
					new Blob([wbout], { type: 'application/octet-stream' }),
					//设置导出文件名称
					'sheetjs.xlsx'
				)
			} catch (e) {
				if (typeof console !== 'undefined') console.log(e, wbout)
			}
			return wbout
		},
		handletabClick(tab, event) {
			this.searchForm = {
				jyjb: '',
				jylx: '',
				jyfs: '',
				hth: '',
				pzbm: '',
				dateList: [],
			}
			;(this.pageForm = {
				pageNum: 1,
				pageSize: 10,
			}),
				(this.activeName = tab.name)
			this.searchShowMoreBool = false
			this.getCcList()
		},
		changeNd(val) {
			this.pageForm.pageNum = 1
			this.getCcList()
		},
	},
}
</script>

<style lang="scss" scoped>
.pagination-wrap {
	text-align: right;
	margin-top: 10px;
}

/* .input-w-220 {
  width: 220px;
} */
.iconfont {
	font-size: 13px;
}

/* .iconfont {
  color: white;
} */
#out-table {
	border: 2px solid black;
}
#khxx_icon {
	padding: 0 5px !important;
	height: 26px !important;
	background: #169bd5 !important;
}
</style>
