<template>
	<div class="page">
		<el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm" @keyup.enter.native="refreshList()" @submit.native.prevent>
			<!-- 搜索框-->
			<el-form-item label="公司名称" prop="companyName">
				<el-input v-model="searchForm.companyName" placeholder="请输入公司名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="联系人姓名" prop="linkmanName">
				<el-input v-model="searchForm.linkmanName" placeholder="请输入联系人姓名" clearable></el-input>
			</el-form-item>
			<el-form-item label="联系人电话" prop="linkmanPhone">
				<el-input v-model="searchForm.linkmanPhone" placeholder="请输入联系人电话" clearable></el-input>
			</el-form-item>
			<el-form-item v-if="showHideItem" label="年销售额(元)" prop="annualSalesList">
				<InputNumber :disabled="false" :precision="num" :value="searchForm.annualSalesList"
							 @changefrom="(val)=>{searchForm.annualSalesList[0]=val}"
							 @changeto="(val)=>{searchForm.annualSalesList[1]=val}"
				></InputNumber>
			</el-form-item>
			<!--<el-form-item v-if="showHideItem" label="网络零售额(元)" prop="onlineRetailSalesList">
				<InputNumber :disabled="false" :precision="num" :value="searchForm.onlineRetailSalesList"
							 @changefrom="(val)=>{searchForm.onlineRetailSalesList[0]=val}"
							 @changeto="(val)=>{searchForm.onlineRetailSalesList[1]=val}"
				></InputNumber>
			</el-form-item>-->

			<el-form-item v-if="showHideItem" label="入驻平台" prop="settledPlatformId">
				<el-select
					v-model="searchForm.settledPlatformId"
					style="width: 100%"
					clearable
					placeholder="请选择"
				>
					<el-option
						v-for="item in settledPlatformList"
						:key="item.id"
						:label="item.name"
						:value="item.id"
					>
					</el-option>
				</el-select>
			</el-form-item>

			<el-form-item v-if="showHideItem" label="创建时间" prop="dates">
				<el-date-picker
					style=""
					placement="bottom-start"
					value-format="YYYY-MM-DD HH:mm:ss"
					v-model="searchForm.dates"
					type="datetimerange"
					range-separator="至"
					start-placeholder="开始日期"
					end-placeholder="结束日期">
				</el-date-picker>
			</el-form-item>

			<el-form-item>
				<el-button type="default" @click="showHide" :icon="showHideIcon">{{showHideName}}</el-button>
				<el-button type="primary" @click="refreshList()" icon="el-icon-search">查询</el-button>
				<el-button @click="resetSearch()" icon="el-icon-refresh-right">重置</el-button>
			</el-form-item>
		</el-form>

		<div class="jp-table top" style="">
			<vxe-toolbar :refresh="{query: refreshList}" ref="toolbarRef" import
						 export
						 resizable
						 custom>
				<template #buttons>
					<el-button v-if="hasPermission('wdt:merchantCompany:add')" type="primary" icon="el-icon-plus" @click="add()">新建</el-button>
					<el-button v-if="hasPermission('wdt:merchantCompany:del')" type="danger"  icon="el-icon-delete" @click="del()" :disabled="$refs.infoTable && $refs.infoTable.getCheckboxRecords().length === 0" plain>删除</el-button>
				</template>
				<template #tools>
					<vxe-button
						text
						type="primary"
						:title="searchVisible ? '收起检索' : '展开检索'"
						icon="vxe-icon-search"
						class="tool-btn"
						@click="searchVisible = !searchVisible"
					></vxe-button>

					<vxe-button
						type="text"
						title="下载导入模板"
						v-if="hasPermission('wdt:merchantCompany:import')"
						icon="vxe-icon-copy"
						class="tool-btn m-l-0"
						@click="downloadTpl()"
					>
					</vxe-button>
				</template>
			</vxe-toolbar>
			<div style="height: calc(100% - 80px)">
				<vxe-table
					border="inner"
					auto-resize
					resizable
					height="auto"
					:loading="loading"
					ref="infoTable"
					show-header-overflow
					show-overflow
					highlight-hover-row
					:menu-config="{}"
					:sort-config="{remote:true}"
					:import-config="{
									importMethod: importMethod,
									types: ['csv', 'xls', 'xlsx'],
									remote: true,
								}"
					:export-config="{
                    remote: true,
                    filename: `入驻商户数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    sheetName: `入驻商户数据${moment(new Date()).format('YYYY-MM-DD')}`,
                    exportMethod: exportMethod,
                    types: ['xlsx'],
                    modes: ['current', 'selected', 'all']
                  }"
					:data="dataList"
					:checkbox-config="{}">
					<vxe-column type="seq" width="60" title="序号"></vxe-column>
					<vxe-column type="checkbox" width="60" ></vxe-column>
					<vxe-column min-width="130" title="公司名称" field="companyName" align="center">
						<template #default="scope">
							<el-link  type="primary" :underline="false" v-if="hasPermission('wdt:merchantCompany:view')" @click="view(scope.row.id)">{{scope.row.companyName}}</el-link>
							<span v-else>{{scope.row.no}}</span>
						</template>
					</vxe-column>
					<vxe-column min-width="100" title="公司类型" field="companyTypeStr" align="center"></vxe-column>
					<vxe-column min-width="130" title="联系人姓名" field="linkmanName" align="center"></vxe-column>
					<vxe-column min-width="180" title="联系人电话" field="linkmanPhone" align="center"></vxe-column>
					<vxe-column min-width="100" title="年销售额(万元)" field="annualSales" align="center"></vxe-column>
					<vxe-column min-width="100" title="入驻平台" field="settledPlatformStr" align="center"></vxe-column>
					<vxe-column min-width="100" title="创建时间" field="createTime" align="center"></vxe-column>

					<vxe-column title="操作" min-width="130px" fixed="right" align="center">
						<template  #default="scope">
							<el-button v-if="hasPermission('wdt:merchantCompany:edit')" text type="primary" @click="edit(scope.row)">修改</el-button>
							<el-button v-if="hasPermission('wdt:merchantCompany:del')" text type="primary"  @click="del(scope.row.id)">删除</el-button>
						</template>
					</vxe-column>
				</vxe-table>
				<vxe-pager
					background
					:current-page="tablePage.currentPage"
					:page-size="tablePage.pageSize"
					:total="tablePage.total"
					:page-sizes="[10, 20, 100, 1000, {label: '全量数据', value: 1000000}]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
					@page-change="currentChangeHandle">
				</vxe-pager>

				<MerchantCompanyForm  ref="merchantCompanyForm" @refreshDataList="refreshList"></MerchantCompanyForm>
			</div>
		</div>
	</div>
</template>

<script>
	import merchantCompanyService from '@/api/wdt/merchantCompany/MerchantCompanyService'
	import settledPlatformService from '@/api/wdt/settledPlatform/SettledPlatformService'
	import InputNumber from '@/views/utils/InputNumber.vue'
	import MerchantCompanyForm from './MerchantCompanyForm'
	export default {
		data () {
			return {
				searchVisible: true,
				showHideItem: false,
				showHideIcon: 'el-icon-arrow-down',
				showHideName: '展示',
				num: 0,
				visable: false,
				gridData: [],
				settledPlatformList: [],
				searchForm: {
					companyName: '',
					linkmanName: '',
					linkmanPhone: '',
					dates: [],
					type: [],
					annualSalesList: [],
					onlineRetailSalesList: [],
					reportNumber: '',
					settledPlatformId: '',
					sourceType: ''
				},
				dataList: [],
				tablePage: {
					total: 0,
					currentPage: 1,
					pageSize: 10,
					orders: []
				},
				loading: false,
				isAdmin: false
			}
		},
		created () {
		},
		components: {
			InputNumber,
			MerchantCompanyForm
		},
		mounted () {
			this.$nextTick(() => {
				//将表格和工具栏进行关联
				const $table = this.$refs.infoTable;
				const $toolbar = this.$refs.toolbarRef;
				$table.connect($toolbar);
			})

			Promise.all([
				settledPlatformService.list({ current: 1, size: -1 }),
			]).then((result) => {
				this.settledPlatformList = result[0].records;
			});
			this.refreshList()
		},
		activated () {
			this.refreshList()
		},
		computed: {
			userName () {
				return this.$store.state.user.name
			},
			user () {
				this.create = this.$store.state.user.id
				console.log('createId', this.create)
				return this.$store.state.user
			}
		},
		methods: {
			showHide () {
				if (this.showHideItem === false) {
					this.showHideItem = true
					this.showHideIcon = 'el-icon-arrow-up'
					this.showHideName = '隐藏'
				} else {
					this.showHideItem = false
					this.showHideIcon = 'el-icon-arrow-down'
					this.showHideName = '展示'
				}
			},
			// 新增
			add () {
				this.$refs.merchantCompanyForm.init('add', '')
			},

			// 查看
			view (id) {
				this.$refs.merchantCompanyForm.init('view', id)
			},
			edit (row) {
				this.$refs.merchantCompanyForm.init('edit', row.id)
			},
			// 获取数据列表
			refreshList () {
				this.loading = true
				merchantCompanyService.list({
					'current': this.tablePage.currentPage,
					'size': this.tablePage.pageSize,
					'orders': this.tablePage.orders,
					...this.searchForm
				}).then((data) => {
					this.dataList = data.records
					this.tablePage.total = data.total
					this.loading = false
				})
			},
			// 删除
			del (id) {
				let ids = id || this.$refs.infoTable.getCheckboxRecords().map(item => {
					return item.id
				}).join(',')
				this.$confirm(`确定删除所选项吗?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.loading = true
					merchantCompanyService.delete(ids).then((data) => {
						this.$message.success(data)
						this.refreshList()
						this.loading = false
					})
				})
			},
			resetSearch () {
				this.$refs.searchForm.resetFields()
				this.searchForm.settledPlatformId = ''
				this.refreshList()
			},
			// 下载模板
			downloadTpl() {
				merchantCompanyService
					.exportTemplate()
					.then((data) => {
						// 将二进制流文件写入excel表，以下为重要步骤
						this.$utils.downloadExcel(data, "入驻商户导入模板");
					})
					.catch(function (err) {
						if (err.response) {
							console.log(err.response);
						}
					});
			},
			// 自定义服务端导入
			importMethod({ file }) {
				// 处理表单
				const formBody = new FormData();
				formBody.append("file", file);
				merchantCompanyService.importExcel(formBody).then((result) => {
					this.$message.success({
						dangerouslyUseHTMLString: true,
						message: result,
					});
					this.refreshList();
				});
			},
			// 下载文档
			exportFile () {
				this.loading = true
				merchantCompanyService.exportFile({
					'itemType': '1',
					...this.searchForm
				}).then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadExcel(res, '入驻商家信息表')
					this.loading = false
				}).catch(function (err) {
					this.loading = false
					if (err.response) {
						console.log(err.response)
					}
				})
			},
			// 当前页
			currentChangeHandle ({ currentPage, pageSize }) {
				this.tablePage.currentPage = currentPage
				this.tablePage.pageSize = pageSize
				this.refreshList()
			},
			// 自定义服务端导出
			exportMethod ({ options }) {
				console.log('进入到处系统')
				// 传给服务端的参数
				const params = {
					'current': this.tablePage.currentPage,
					'size': this.tablePage.pageSize,
					'orders': this.tablePage.orders,
					...this.searchForm,
					filename: options.filename,
					sheetName: options.sheetName,
					isHeader: options.isHeader,
					original: options.original,
					mode: options.mode,
					selectIds: options.mode === 'selected' ? options.map(item => item.id) : [],
					exportFields: options.columns.map(column => column.property)
				}
				return merchantCompanyService.exportExcel(params).then((res) => {
					// 将二进制流文件写入excel表，以下为重要步骤
					this.$utils.downloadExcel(res, options.filename)
				}).catch(function (err) {
					if (err.response) {
						console.log(err.response)
					}
				})
			},
		}
	}
</script>
