<template>
<JeepayBackground>
  <view class="page-wrapper jeepay-edit-form">
    <JeepayCustomNavbar :title="vdata.sysUserId ? '修改' : '创建' " backCtrl="back" />
    <uni-forms ref="formRef" :rules="rules" :model="vdata.formData" :label-width="140">
		
      <uni-forms-item required label="姓名" name="realname">
		  <uni-easyinput v-model="vdata.formData.realname" placeholder="请输入姓名" :inputBorder="false"></uni-easyinput>
      </uni-forms-item>
	  
      <uni-forms-item v-if="!vdata.sysUserId" required label="登录用户名" name="loginUsername">
		<uni-easyinput v-model="vdata.formData.loginUsername" placeholder="6-18位，字母开头且不包含符号" :inputBorder="false"></uni-easyinput>
      </uni-forms-item>
	  
      <uni-forms-item required label="手机号" name="telphone">
		<uni-easyinput v-model="vdata.formData.telphone" placeholder="请输入手机号" :inputBorder="false"></uni-easyinput>
      </uni-forms-item>
	  
      <uni-forms-item required label="编号">
		<uni-easyinput v-model="vdata.formData.userNo" placeholder="请输入用户编号" :inputBorder="false"></uni-easyinput>
      </uni-forms-item>
	  
      <uni-forms-item required label="性别" name="sex">
		  <JeepayRadioPopupView label="请选择性别" v-model:value="vdata.formData.sex" :list="[{ label: '男', value: 1}, { label: '女', value: 2}]">
		  </JeepayRadioPopupView>
      </uni-forms-item>
	  
      <view class="line"></view>
	  
	  <!-- -->
      <uni-forms-item required v-if="showUserType()" label="类型" name="userType">
		  <JeepayRadioPopupView label="请选择用户类型" v-model:value="vdata.formData.userType" :list="appendUserTypeList()" @change="changeUserTypeFunc">
		  </JeepayRadioPopupView>
      </uni-forms-item>
	  
	  <!-- 选择用户类型后需要显示当前已绑定的门店列表 -->
	  <uni-forms-item v-if="vdata.formData.userType && vdata.formData.userType != 1" required label="绑定门店" name="storeList">
		  <template #label>
		  	<view class="f-label">绑定门店</view>
		  </template>
			<view class="selected-sex" @tap="showStoreFunc">
				<view class="selected-box">
					<view v-for="(item) in vdata.selectedStoreList">{{item.storeName}} - {{item.storeId}}</view>
				</view>
			  <image src="/pageDevice/static/devIconImg/icon-arrow-sex.svg" mode="scaleToFill" />
		  </view>
		  
	  </uni-forms-item>
	  
      <view class="line"></view>
	  
      <uni-forms-item v-if="!vdata.sysUserId" required label="密码设置" name="pwdDefaultByPage">
		  <JeepayRadioPopupView  label="请选择密码设置类型" v-model:value="vdata.formData.pwdDefaultByPage" :list="[{ label: '默认密码', value: 1}, { label: '自定义密码', value: 0}]">
		  </JeepayRadioPopupView>
      </uni-forms-item>
	  
	  <uni-forms-item v-if="vdata.formData.pwdDefaultByPage == 0" required label="自定义密码" name="loginPassword">
	  		<uni-easyinput v-model="vdata.formData.loginPassword" placeholder="请输入自定义密码" :inputBorder="false"></uni-easyinput>
	  </uni-forms-item>	
	  
      <view class="line"></view>
    </uni-forms>
	
	<template  v-if="!vdata.sysUserId">
		
		<JeepayTableListItem title="状态" subtitle="状态禁用后，用户将无法登录APP和后台管理系统">
			<template #titleRight>
				<JeepayStateSwitch v-model:state="vdata.formData.state" :showSwitchType="true" :confirm='false'  />
			</template>
		</JeepayTableListItem>
		
		<JeepayTableListItem title="开通提醒" subtitle="启用后，用户创建完成时，将发送开通提醒短信至用户手机号">
			<template #titleRight>
				<JeepayStateSwitch v-model:state="vdata.formData.isNotify"  :showSwitchType="true" :confirm='false' />
			</template>
		</JeepayTableListItem>
		
	</template>
   
	
    <view class="confirm-wrapper">
      <view class="confirm-button flex-center" hover-class="touch-button" @tap="confirmFunc"> {{ vdata.sysUserId ? '确认修改' : '确认创建' }}</view>
    </view>
	
	
	
  </view>
	<!-- 选择门店, 店长支持多选  -->
	<JeepayPopupListSelect
	  ref="storeSelectRef"
	  :reqTableDataFunc="reqTableDataByStoreFunc"
	  :isCheckbox="vdata.formData.userType == 11" 
	  searchInputName="storeName"
	  :fields="{ key: 'storeId', left: 'storeName', right: 'storeId' }"
	/>
</JeepayBackground>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { $getPasswordRules, reqLoad, API_URL_SYS_USER_LIST, API_URL_MCH_STORE_LIST, API_URL_USER_BIND_STORE_LIST,$getBindStoreList } from '@/http/apiManager.js'
import infoBox from '@/commons/utils/infoBox.js';
import go from '@/commons/utils/go.js'
import formUtil from '@/commons/utils/formUtil.js'
import emit from '@/commons/utils/emit.js'
import storageManage from '@/commons/utils/storageManage.js'

const formRef = ref()
const storeSelectRef = ref()

onLoad((options) => {
	
	// test() // 本地测试。 
	
	// 获取密码规则 
	$getPasswordRules().then(({bizData}) => {
		vdata.passwordRules = bizData
	})
	
	// 修改页面 
	if(options.sysUserId){
		
		vdata.sysUserId = options.sysUserId
		reqLoad.getById(API_URL_SYS_USER_LIST, vdata.sysUserId).then(({bizData}) => {
			vdata.formData = bizData
			
			// 查询已绑定门店
			reqLoad.list(API_URL_USER_BIND_STORE_LIST, {sysUserId: options.sysUserId, pageSize: -1}).then((storeRes) => {
				vdata.selectedStoreList = storeRes.bizData.records
			})
			
		})
		
	}
	
})

	
const rules = {
	realname: {
		rules:[ formUtil.rules.requiredInput() ],
	},
	loginUsername: {
		rules:[ formUtil.rules.requiredInput(), formUtil.rules.patternRule('登录用户名', formUtil.regexp.loginUsername) ],
	},
	telphone: {
		rules:[ formUtil.rules.requiredInput(), formUtil.rules.patternRule('联系人电话', formUtil.regexp.mobile) ],
	},
	sex: {
		rules:[ formUtil.rules.requiredSelect('性别', 'number') ],
	},
	userType: {
		rules:[ formUtil.rules.requiredSelect('用户类型', 'number') ],
	},
	pwdDefaultByPage: {
		rules:[ formUtil.rules.requiredSelect('密码类型', 'number') ],
	},
	loginPassword: {
		rules:[{ format: 'string', required: true, errorMessage: '请输入密码', validateFunction: function(rule,value,data,callback){
				if(!new RegExp(vdata.passwordRules.regexpRules).test(value)){
					callback(vdata.passwordRules.errTips)
					return false;
				}
					
				return true;
			}
		}],
	}
}


const vdata = reactive({
	
	sysUserId: null, // 新建 or 修改 
	
	 // 表单数据 
	formData: {
		state: 1,
		isNotify: 0,
		pwdDefaultByPage: undefined,  // 1-默认， 0-自定义 （ 注意， 前端的值， 后端无需该字段 ）
	},
	
	
	
	passwordRules: { }, // 密码验证规则
	
	selectedStoreList: [], // 选择的门店
	
})

// 切换用户类型后， 绑定的门店取消。 
function changeUserTypeFunc(){
	vdata.selectedStoreList = []
}


function reqTableDataByStoreFunc(params) {
	params.userType = vdata.formData.userType
  return  $getBindStoreList(params) 
}

function showStoreFunc(){
	
  // 选择门店
  storeSelectRef.value.open().then((selected) => {
	  
	vdata.selectedStoreList = []
	  if(selected){
		vdata.selectedStoreList = vdata.formData.userType == 11 ? selected : [selected]
	  }
	storeSelectRef.value.close() //自行关闭
  })
}



function confirmFunc(){
	
	formUtil.validate(formRef.value).then(() => {
		
		// 超管， 必须选择门店。 
		if(vdata.formData.userType != 1 && vdata.selectedStoreList.length <= 0){
			infoBox.showToast("请选择绑定门店")
			return Promise.reject()
		}
		
		// 处理选择门店
		let reqData = Object.assign({}, vdata.formData)
		let storeIdList = []
		vdata.selectedStoreList.forEach(r => storeIdList.push(r.storeId) )
		reqData.storeIdList = storeIdList.join() // 后端需要是 逗号拼接类型。 
		
		// 处理 密码
		if(vdata.formData.pwdDefaultByPage == 1){
			reqData.loginPassword = ""
		}
		
		return reqLoad.addOrUpdate(vdata.sysUserId, API_URL_SYS_USER_LIST, reqData)
	})
	.then(( {bizData} ) => {
		emit.pageEmit(emit.ENAME_REF_SYS_USER_LIST) // 更新列表
		go.back(1, emit.ENAME_REF_SYS_USER_DETAIL) // 返回详情 && 更新详情
	})
	
}

function appendUserTypeList(){
	
	// 店长 && 新增
	if(storageManage.userInfo().userType == 11){
		return [{ label: '店员', value: 12}]
	}
	
	return [{ label: '超级管理员', value: 1}, { label: '店长', value: 11}, { label: '店员', value: 12}]
	
}

function showUserType(){
	
	// 新增页面都显示
	if(!vdata.sysUserId){
		return true;
	}
	
	// 店长 && 修改  不显示
	if(storageManage.userInfo().userType == 11){
		return false;
	}
	
}



function test(){
	let time = new Date().getTime()
	vdata.formData.realname = '张三'
	vdata.formData.loginUsername = 'A'+ time
	vdata.formData.telphone = ('12' + time + '').substring(0, 11)
	vdata.formData.userNo = 'A'+ time
	vdata.formData.sex = 1
	vdata.formData.userType = 12
	vdata.formData.pwdDefaultByPage = 1
}

</script>


<style lang="scss" scoped>
input {
  font-size: 32rpx;
}
.f-label {
	width: 240rpx;
}
.selected-sex {
  display: flex;
	justify-content: space-between;
	align-items: flex-start;
	margin-top: 45rpx;
	margin-bottom: 10rpx;
  font-size: 32rpx;
  color: #b3b3b3;
  image {
    width: 120rpx;
    height: 120rpx;
		margin-top: -40rpx;
  }
	.selected-box {
		color: #000;
	}
}
.confirm-wrapper {
  padding: 50rpx 30rpx;
  .confirm-button {
    height: 110rpx;
    color: #fff;
    border-radius: 20rpx;
    background: $jeepay-bg-primary;
  }
}
</style>
