<template>
	<div v-loading="loading">
		<div class="white-box">
			<!-- 功能搜索 -->
			<div class="filter-box">
				<filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
			</div>

			<!-- 列表展示 -->
			<el-table ref="wrapper" :data="tableData" stripe style="width: 100%;" @selection-change="handleSelectionChange" :height="tool.getTableHeight()">
				<el-table-column :fixed="leftFixed" type="selection" width="55" v-if="tableHeaders"></el-table-column>
				<el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :fixed="tableHeader.index == 'USER_NAME' || tableHeader.index == 'REAL_NAME' ? leftFixed : false">
					<template slot-scope="scope">
						<template v-if="scope.row[tableHeader.index].other.tag">
							<el-tag
								:type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null"
								:size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null"
								:class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null">
								{{scope.row[tableHeader.index].value}}
							</el-tag>
						</template>
						<template v-else>
							<template v-if="tableHeader.index === 'USER_NAME'">
								<el-dropdown v-if="permission.hasPermission(`user/login-to-frontend`)">
									<span class="el-dropdown-link">
										{{scope.row.USER_NAME.value}} <i class="el-icon-arrow-down el-icon--right"></i>
									</span>
									<el-dropdown-menu slot="dropdown">
										<el-dropdown-item command="login" v-show="scope.row.BTF_URL !== null">
											<a :href="`${frontendServer}/#/login-by-backend?${scope.row.BTF_URL}`" target="_blank" style="color:#606266;">{{ $t('member.quickLogon') }}</a>
										</el-dropdown-item>
									</el-dropdown-menu>
								</el-dropdown>
								<el-tag type="primary" size="small" class="no-border" v-if="!permission.hasPermission(`user/login-to-frontend`)">{{ scope.row.USER_NAME.value }}</el-tag>
							</template>
							<template v-else>
								<div v-html="scope.row[tableHeader.index].value"></div>
							</template>
						</template>
					</template>
				</el-table-column>
				<el-table-column :fixed="fixed" :label="$t('common.action')" width="180">
					<template slot-scope="{row}">
						<el-dropdown size="small" trigger="click">
							<el-button type="primary" size="small" @click.stop="">{{ $t('common.action') }}<i class="el-icon-arrow-down el-icon--right"></i></el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item @click.native="handleModifyPassword(row)" v-if="permission.hasPermission(`user/modify-password`)">{{ $t('member.changePassword') }}</el-dropdown-item>
								<el-dropdown-item @click.native="handleModifyProfile(row)" v-if="permission.hasPermission(`user/modify-profile`)">{{ $t('member.modifyPersonalData') }}</el-dropdown-item>
								<el-dropdown-item @click.native="handleStatusActive(row)" v-if="permission.hasPermission(`user/modify-status`)">{{ $t('member.statusActivation') }}</el-dropdown-item>
								<el-dropdown-item @click.native="handleStatusLock(row)" v-if="permission.hasPermission(`user/modify-status`)">{{ $t('member.statusLock') }}</el-dropdown-item>
								<el-dropdown-item @click.native="handleIsModifyPassword(row, 1)" v-if="permission.hasPermission(`user/is-modify-password-status`)">{{ $t('member.openPasswordModification') }}</el-dropdown-item>
								<el-dropdown-item @click.native="handleIsModifyPassword(row, 0)" v-if="permission.hasPermission(`user/is-modify-password-status`)">{{ $t('member.turnOffPasswordModification') }}</el-dropdown-item>
							</el-dropdown-menu>
						</el-dropdown>
					</template>
				</el-table-column>
			</el-table>

			<!-- 快捷功能 -->
			<div class="white-box-footer">
				<el-dropdown size="small" trigger="click" v-show="permission.hasPermission(`user/is-dec`)" style="margin: 5px;">
					<el-button type="primary" size="small" @click.stop="">
						{{ $t('member.stockistManagement') }}<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item command="isDec" @click.native="handleIsDecManage(true)">{{ $t('member.setAsStockist') }}</el-dropdown-item>
						<el-dropdown-item command="notDec" @click.native="handleIsDecManage(false)">{{ $t('member.cancelStockist') }}</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>

				<el-dropdown size="small" trigger="click" v-show="permission.hasPermission(`user/is-atlas`)" style="margin: 5px;">
					<el-button type="primary" size="small" @click.stop="">
						{{ $t('member.chartManagement') }}<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item command="isAtlas" @click.native="handleIsAtlasManage(true)">{{ $t('member.displayChart') }}</el-dropdown-item>
						<el-dropdown-item command="notAtlas" @click.native="handleIsAtlasManage(false)">{{ $t('member.hiddenChart') }}</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>

				<el-dropdown size="small" trigger="click" v-show="permission.hasPermission(`user/is-recharge`)" style="margin: 5px;">
					<el-button type="primary" size="small" @click.stop="">
						{{ $t('member.rechargeManagement') }}<i class="el-icon-arrow-down el-icon--right"></i>
					</el-button>
					<el-dropdown-menu slot="dropdown">
						<el-dropdown-item command="isAtlas" @click.native="handleIsRechargeManage(true)">{{ $t('member.displayRecharge') }}</el-dropdown-item>
						<el-dropdown-item command="notAtlas" @click.native="handleIsRechargeManage(false)">{{ $t('member.hideRecharge') }}</el-dropdown-item>
					</el-dropdown-menu>
				</el-dropdown>
				<el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`user/index-export`)" style="margin: 5px;">{{ $t('member.exportExcel') }}</el-button>


				<pagination v-show="totalCount>0" :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>

		<!-- 修改密码 -->
		<el-dialog :title="formModifyPassword.typeName" :visible.sync="dialogModifyPasswordVisible" :width="screenWidth">
			<el-form ref="form" :model="formModifyPassword" label-width="120px" class="form-dialog" :label-position="labelPosition">
				<el-form-item :label="$t('member.type')">
					<el-select v-model="formModifyPassword.passwordType" :placeholder="$t('member.selectType')">
						<el-option v-for="(item,key) in passwordType" :label="item.label" :value="item.type" :key="key"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('member.password')">
					<el-input :placeholder="$t('member.password')"  v-model="formModifyPassword.password"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleModifyPasswordSubmit" :loading="submitPasswordButtonStat">{{ $t('common.confirm') }}</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 修改会员信息 -->
		<el-dialog :title="formModifyProfile.typeName" :visible.sync="dialogModifyProfileVisible" :width="screenWidth" :destroy-on-close="true">
			<el-form ref="form" :model="formModifyProfile" label-width="150px" :label-position="labelPosition">
				<el-form-item :label="$t('member.memberName')">
					<el-input v-model="formModifyProfile.realName"></el-input>
				</el-form-item>
				<el-form-item :label="$t('member.identityNo')">
					<el-input v-model="formModifyProfile.idCard"></el-input>
				</el-form-item>
        <el-form-item :label="$t('transportationConfig.countryName')">
          <el-select v-model="formModifyProfile.country" filterable ref="countryId" @change="countryChange" @blur="countryVisibleChange($event)">
            <el-option v-for="(item,index) in allCountry" :key="index" :label="item.NAME" :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('common.language')">
          <el-select v-model="formModifyProfile.language">
            <el-option v-for="(item,index) in allLanguage" :key="index" :label="item.NAME" :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
				<el-form-item :label="$t('member.phoneNumber')">
					<el-input v-model="formModifyProfile.mobile"></el-input>
				</el-form-item>
				<el-form-item :label="$t('member.bankName')">
					<el-select v-model="formModifyProfile.openBank" :placeholder="$t('member.selectBankName')">
						<el-option v-for="(item,index) in allOpenBank" :key="index" :label="item.BANK_NAME" :value="item.BANK_CODE"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="$t('member.bankAddress')">
					<el-input v-model="formModifyProfile.bankAddress"></el-input>
				</el-form-item>
				<el-form-item :label="$t('member.bankAccount')">
					<el-input v-model="formModifyProfile.bankNo"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleModifyProfileSubmit" :loading="submitProfileButtonStat">{{ $t('common.confirm') }}</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import tool from '@/utils/tool'
import baseInfo from '@/utils/baseInfo'
import FilterUser from '@/components/FilterUser'
import permission from '@/utils/permission'
import Pagination from '@/components/Pagination'
import filterHelper from '@/utils/filterHelper'
import waves from "@/directive/waves";
import {getOperatingSystem, getScreenWidth} from "@/utils"
import region from "@/store/modules/region"
import {
	fetchCloseDec, fetchCloseDecGet, fetchCloseLoginGet, fetchMemberExport, fetchMemberList, fetchProfileGet,
	updateModifyPassword, updateModifyProfile, updateSetActive, updateSetAsStockist, updateSetChartDisplay, updateSetLock, updateSetModifyPassword, updateSetRechargeDisplay,
} from "@/api/member"
import {getBank} from "@/api/site";

export default {
	name: 'memberList',
	directives: { waves },
	components: {FilterUser, Pagination},
	mounted() {
		// TODO: 测试接口
		// this.getData()

		if (permission.hasPermission(`user/close-login`) || permission.hasPermission(`user/close-area-login`) || permission.hasPermission(`user/batch-close-login`)) {
			fetchCloseLoginGet().then(response => {
				this.apps = response.data.apps
				this.closeSwitch = response.data.closeSwitch
				if (permission.hasPermission(`user/close-dec`) || permission.hasPermission(`user/close-area-dec`) || permission.hasPermission(`user/batch-close-dec`)) {
					fetchCloseDecGet().then(response => {
						this.closeDecSwitch = response.data.closeSwitch
						this.getData()
					}).catch(error => {
						this.$message({
							message: error,
							type: 'warning'
						})
					})
				} else {
					this.getData()
				}
			}).catch(error => {
				this.$message({
					message: error,
					type: 'warning'
				})
			})
		} else {
			if (permission.hasPermission(`user/close-dec`) || permission.hasPermission(`user/close-area-dec`) || permission.hasPermission(`user/batch-close-dec`)) {
				fetchCloseDecGet().then(response => {
					this.closeDecSwitch = response.data.closeSwitch
					this.getData()
				}).catch(error => {
					this.$message({
						message: error,
						type: 'warning'
					})
				})
			} else {
				this.getData()
			}
		}
	},
	data() {
		return {
			tableHeaders: null,
			tableData: null,
			loading: true,
			multipleSelection: [],
			currentPage: 1,
			totalPages: 1,
			totalCount: 1,
			pageSize: 20,
			frontendServer: process.env.VUE_APP_FRONTEND_WEBSITE,
			baseDecLevels: baseInfo.decLevels(),
			baseEmpLevels: baseInfo.empLevels(),
			tool: tool,
			permission: permission,
			filterTypes: null,
			filterModel: {},
			dialogVisible: false,
			formCloseLogin: {
				userName: null,
				typeName: this.$t('member.loginManagement'),
				type: null,
				isClose: 0,
				remark: '',
				areaSelected: null,
			},
			regionDataPlus: region.regionInfo.regionData,
			apps: null,
			closeSwitch: null,
			submitButtonStat: false,
			dialogDecVisible: false,
			dialogModifyPasswordVisible: false,
			dialogModifyProfileVisible: false,
			formCloseDec: {
				userName: null,
				typeName: this.$t('member.entryManage'),
				type: null,
				isClose: 0,
				remark: '',
				areaSelected: null,
			},
			formModifyPassword: {
				userId:'',
				password: '',
				typeName: this.$t('member.changePassword'),
				passwordType: 'password',
			},
			formModifyProfile: {
				userId:'',
				typeName: this.$t('member.modifyPersonalData'),
				nation: '',
				realName: '',
				idCard: '',
				mobile: '',
				openBank: '',
				bankAddress: '',
				bankNo: '',
			},
			passwordType: [
				{
					type:"password",
					label: this.$t('member.loginPassword'),
				},
				{
					type:"payPassword",
					label: this.$t('member.paymentPassword'),
				},
			],
			allOpenBank:null,
			allNation:null,
      allCountry: null,
      allLanguage: null,
			submitDecButtonStat: false,
			submitPasswordButtonStat: false,
			submitProfileButtonStat: false,
			transferPropForm: {
				userIds: [],
				allowTransfer: true,
				transferProp: 100,
				withdrawProp: 0,
				remark: '',
			},
			closeUserData: null,
			screenWidth: getScreenWidth() > 500 ? '500px' : getScreenWidth() + 'px',
			labelPosition: getScreenWidth() >= 500 ? 'right' : 'top',
			leftFixed: getScreenWidth() < 500 ? false : 'left',
			fixed: getScreenWidth() < 500 ? false : 'right',
			// leftFixed: ['Android', 'ios'].includes(getOperatingSystem()) ? false : 'left',
			// fixed: ['Android', 'ios'].includes(getOperatingSystem()) ? false : 'right',
      originalCountry: '',
		}
	},
	methods: {
    countryVisibleChange(event){
    },
    countryChange(row){
      this.$nextTick(() => {
        this.$refs.countryId.blur()
        this.$confirm( this.$t('member.modifyCountry'), this.$t('common.hint'), {
          confirmButtonText: this.$t('common.confirm'),
          cancelButtonText: this.$t('common.cancel'),
          type: 'warning'
        }).then(() => {
          // this.$message({
          //   type: 'success',
          //   message: '!'
          // });
          this.getBanks(row)

        }).catch(() => {
          this.formModifyProfile.country = this.originalCountry
          this.getBanks(this.originalCountry)
        });

      });


    },

    getBanks(countryId){
      getBank( { countryId: countryId, }).then(response => {
        this.formModifyProfile.openBank = null
        this.allOpenBank = response
      }).catch(error => {
        this.$message({
          message: error,
          type: 'warning'
        })

      })
    },
		handleSelectionChange(val) {
			this.multipleSelection = val
		},
		handleCurrentChange(page) {
			this.getData(page, this.pageSize)
		},
		handleSizeChange(pageSize) {
			this.getData(this.currentPage, pageSize)
		},
		handleFilterUser(filterData) {
      console.log(filterData)
			filterHelper.handleFilterUser(this, filterData)
		},
		handleFilter() {
			this.getData()
		},
		getData(page, pageSize) {
			this.loading = true
			const paramsData = Object.assign({
				page: (page === null || page == undefined) ? 1 : page,
				pageSize: (pageSize === null || pageSize == undefined) ? this.pageSize : pageSize
			}, this.filterModel)
			fetchMemberList(paramsData).then(response => {
				this.filterTypes = response.data.filterTypes
				this.tableData = response.data.list
				this.totalCount = +response.data.totalCount
				this.currentPage = page
				this.pageSize = pageSize
				this.filterTypes = response.data.filterTypes
				this.tableHeaders = response.data.columnsShow
				this.loading = false
			}).catch(error => {
				this.$message({
					message: error,
					type: 'warning'
				})
				this.loading = false
			})
		},
		handleIsDecManage(isDec) {
			if (this.multipleSelection.length < 1) {
				this.$message({
					message: this.$t('member.selectMemberData'),
					type: 'warning'
				})
				return
			}
			let isDecTip = isDec === true ? this.$t('member.setAsStockist') : this.$t('member.cancelStockist')
			this.$confirm( this.$t('member.sureWant') + `【${isDecTip}】？`, this.$t('common.hint'), {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			}).then(() => {
				let selectedIds = []
				for (let val of this.multipleSelection) {
					selectedIds.push(val.USER_ID)
				}
				this.loading = true
				updateSetAsStockist( { userIds: selectedIds, isDec: isDec }).then(response => {
					this.$message({
						message: response.data,
						type: 'success'
					})

					this.loading = false
					this.getData(this.currentPage, this.pageSize)
				}).catch(error => {
					this.$message({
						message: error,
						type: 'warning'
					})
					this.loading = false
				})
			})
		},
		handleIsAtlasManage(isAtlas) {
			if (this.multipleSelection.length < 1) {
				this.$message({
					message: this.$t('member.selectMemberData'),
					type: 'warning'
				})
				return
			}
			let isAtlasTip = isAtlas === true ? this.$t('member.displayChart') : this.$t('member.hiddenChart')
			this.$confirm(this.$t('member.sureWant') + `【${isAtlasTip}】？`, this.$t('common.hint'), {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			}).then(() => {
				let selectedIds = []
				for (let val of this.multipleSelection) {
					selectedIds.push(val.USER_ID)
				}
				this.loading = true
				updateSetChartDisplay( { userIds: selectedIds, isAtlas: isAtlas }).then(response => {
					this.$message({
						message: response.data,
						type: 'success'
					})

					this.loading = false
					this.getData(this.currentPage, this.pageSize)
				}).catch(error => {
					this.loading = false
					this.$message({
						message: error,
						type: 'error'
					})
				})
			})
		},
		handleIsRechargeManage(isRecharge) {
			if (this.multipleSelection.length < 1) {
				this.$message({
					message: this.$t('member.selectMemberData'),
					type: 'warning'
				})
				return false
			}
			let isRechargeTip = isRecharge === true ? this.$t('member.displayRecharge') : this.$t('member.hideRecharge')
			this.$confirm(this.$t('member.sureWant') + `【${isRechargeTip}】？`, this.$t('common.hint'), {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			}).then(() => {
				let selectedIds = []
				for (let val of this.multipleSelection) {
					selectedIds.push(val.USER_ID)
				}
				this.loading = true
				updateSetRechargeDisplay( { userIds: selectedIds, isRecharge: isRecharge }).then(response => {
					this.$message({
						message: response.data,
						type: 'success'
					})
					this.loading = false
					this.getData(this.currentPage, this.pageSize)
				}).catch(error => {
					this.loading = false
					this.$message({
						message: error,
						type: 'warning'
				    })
				})
			})
		},
		handleExport() {
			this.$confirm(this.$t('member.exportDataHint'), this.$t('common.hint'), {
				confirmButtonText: this.$t('common.confirm'),
				cancelButtonText: this.$t('common.cancel'),
				type: 'warning'
			}).then(() => {
				this.loading = true
				fetchMemberExport( this.filterModel).then(response => {
					this.$message({
						message: response.data,
						type: 'success'
					})
					this.loading = false
					this.getData(this.currentPage, this.pageSize)
				}).catch(error => {
					this.loading = false
					this.$message({
						message: error,
						type: 'warning'
				    })
				})
			})
		},
		handleModifyPassword(row){
			this.formModifyPassword.userId = row.USER_ID;
			this.dialogModifyPasswordVisible = true
		},
		handleModifyProfile(row){
			this.dialogModifyProfileVisible = true
			fetchProfileGet( { id: row.USER_ID }).then(response => {
				this.formModifyProfile = response.data.userInfo
				this.allOpenBank = response.data.allOpenBank
				this.allNation = response.data.allNation
        this.allCountry = response.data.country
        this.allLanguage = response.data.language
        this.originalCountry = JSON.parse(JSON.stringify(response.data.userInfo.country))
			}).catch(error => {
				this.$message({
					message: error,
					type: 'error'
				})
				this.loading = false
			})
		},
		handleStatusActive(row) {
			this.loading = true
			updateSetActive( { userId: row.USER_ID, status: 1 }).then(response => {
				this.$message({
					message: response.data,
					type: 'success'
				})
				this.loading = false
				this.getData(this.currentPage, this.pageSize)
			}).catch(error => {
				this.$message({
					message: error,
					type: 'error'
				})
				this.loading = false
			})
		},
		handleStatusLock(row) {
			this.loading = true
			updateSetLock( { userId: row.USER_ID, status: 0 }).then(response => {
				this.$message({
					message: response.data,
					type: 'success'
				})
				this.loading = false
				this.getData(this.currentPage, this.pageSize)
			}).catch(error => {
				this.$message({
					message: error,
					type: 'error'
				})
				this.loading = false
			})
		},
		handleIsModifyPassword(row, status){
			this.loading = true
			updateSetModifyPassword( { userId: row.USER_ID, status: status }).then(response => {
				this.$message({
					message: response.data,
					type: 'success'
				})
				this.loading = false
				this.getData(this.currentPage, this.pageSize)
			}).catch(error => {
				this.$message({
					message: error,
					type: 'error'
				})
				this.loading = false
			})
		},
		handleModifyPasswordSubmit() {
			this.submitPasswordButtonStat = true
			updateModifyPassword( this.formModifyPassword).then(response => {
				this.$message({
					message: response.data,
					type: 'success'
				})

				this.submitPasswordButtonStat = false
				this.dialogModifyPasswordVisible = false

				this.getData(this.currentPage, this.pageSize)
			}).catch(error => {
				this.$message({
					message: error,
					type: 'error'
				})
				this.submitPasswordButtonStat = false
			})
		},
		handleModifyProfileSubmit() {
			this.submitProfileButtonStat = true
			updateModifyProfile( this.formModifyProfile).then(response => {
				this.$message({
					message: response.data,
					type: 'success'
				})

				this.submitProfileButtonStat = false
				this.dialogModifyProfileVisible = false

				this.getData(this.currentPage, this.pageSize)
			}).catch(error => {
				this.$message({
					message: error,
					type: 'warning'
				})
				this.submitProfileButtonStat = false
				// this.dialogModifyProfileVisible = false
			})
		},
	}
}
</script>

<style>
.app-main {
	padding: 15px;
}
.app-container {
	padding: 0;
}
.white-box {
	padding: 15px;
}
.form-page {
	width: 100%;
}
</style>
