<template>

  <s-layout
  	title="执行对象"
  	navbar="inner"
  	showBackButton
	showImportButton
  	:bgStyle="{ color: '#FAFAFA' }"
	@import="state.showImport = true;state.importVal=''"
  >
	<view v-if="reason!==3" class="form_label">请添加执行对象</view>
    <uni-forms ref="formRef" v-model="formData" :rules="rules">
      <view class="form_item" v-for="(item, index) in formData.phoneList" :key="index">
		<view class="close_icon" @tap="removeItem(index)"></view>
		<view class="label">对象{{index+1}}：</view>
        <uni-forms-item 
			:name="`phoneList.${index}.phone`"
			:rules="rules['phoneList.*.phone'].rules"
		 >
          <uni-easyinput 
			  v-model="item.phone"
			  placeholder="手机号"
			  :clearable="false"
			  :inputBorder="false"
			  :maxlength="11"
		  />
        </uni-forms-item>
        
        <uni-forms-item 
			:name="`phoneList.${index}.name`"
		>
          <uni-easyinput
			  v-model="item.name"
			  placeholder="姓名"
			  :clearable="false"
			  :inputBorder="false"
		  />
        </uni-forms-item>
        
        <uni-forms-item 
			:name="`phoneList.${index}.gender`"
		>
          <uni-data-select
			  v-model="item.gender"
			  placeholder="性别"
			  :clear="false"
			  :localdata="genderOptions"
		  />
        </uni-forms-item>
      </view>
    </uni-forms>
	<view class="add_btn_box">
		<view class="add_btn" @tap="addItem"></view>
	</view>
    <view class="submit_btn" @click="submitForm">{{reason===3?'开始执行任务':'下一步'}}</view>
	<su-popup :show="state.showImport" round="20" type="center" :isMaskClick="false" showClose @close="state.showImport=false">
			<view class="import_wrap">
				<view class="import_cont">
					<view class="title">
						<view class="label">批量导入</view>
						<view class="span">（单次仅支持识别1000个）</view>
					</view>
					<view class="cont">
						<uni-easyinput
						  :inputBorder="false"
						  type="textarea"
						  v-model="state.importVal"
						  placeholderStyle="color:#999999;font-size:24rpx;font-weight:400;line-height:34rpx;"
						  placeholder="请按照以下格式粘贴，用逗号隔开电话号码如:13800138000,13812341234,18912341234"
						  :clearable="false"
						  :maxlength="-1"
						/>
					</view>
				</view>
				<view class="group_btn">
					<view class="item_btn confirm_btn" @tap="onImport">导入</view>
				</view>
			</view>
	</su-popup>
  </s-layout>
</template>

<script setup>
import { ref, reactive, unref, computed } from 'vue'
import sheep from '@/common'
import { onLoad } from '@dcloudio/uni-app'
import taskApi from '@/common/api/member/task'
const formRef = ref(null)

const formData = reactive({
  phoneList: [{ phone: null, name: null, gender: null }]
})
const state = reactive({
  showImport: false,
  importVal: ''
})
const reason = ref(null)

const genderOptions = [
  { value: 1, text: '男' },
  { value: 2, text: '女' },
  { value: 0, text: '未知' }
]

const rules = reactive({
  'phoneList.*.phone': {
    rules: [
      { required: true, errorMessage: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号' },
    ]
  },
  'phoneList.*.name': {
    rules: [
      { required: true, errorMessage: '请输入姓名' },
      { minLength: 2, maxLength: 10, errorMessage: '姓名长度2-10个字符' }
    ]
  },
  'phoneList.*.gender': {
    rules: [
      { required: true, errorMessage: '请选择性别' }
    ]
  }
})
const taskFormInfo = computed(() => sheep.$store('task').taskFormInfo)
onLoad(async (options) => {
  	reason.value = Number(options.reason||null)
	formData.phoneList = taskFormInfo.value.phoneList
  })
const addItem = () => {
  formData.phoneList.push({ phone: null, name: null, gender: null })
}

const removeItem = (index) => {
  if (formData.phoneList.length > 1) {
    formData.phoneList.splice(index, 1)
  } else {
    uni.showToast({
      title: '至少保留一项',
      icon: 'none'
    })
  }
}

const submitForm = async () => {
	const validate = await unref(formRef).validate().catch((error) => {
      console.log('error: ', error)
    })
	if (!validate) return
	sheep.$store('task').updateTaskFormInfo(formData)
	if(reason.value===3){
		const { code, data } = await taskApi.addTask({
			...taskFormInfo.value,
			planTime: taskFormInfo.value.planTime+':00'
		})
		if (code === 1) {
			sheep.$store('task').resetTaskData()
			sheep.$router.go('/pages/index/index')
		}
	}else{
		sheep.$router.go('/pages/task/speechTest')
	}
}
function convertPhoneNumbers(input,maxlength=50) {
    // 使用正则表达式分割字符串（支持逗号、中文逗号、空格等分隔符）
	const phoneRegex = /1[3-9]\d{9}/g;
	let phones = input.match(phoneRegex)
 //    const phones = input.split(/[,，\s]+/)
	// .filter(phone => {
 //        // 验证是否为有效的手机号（11位且以1开头）
 //        return /^1[3-9]\d{9}$/.test(phone);
 //    })
    if(!phones){
		phones=[]
	}
    return phones.slice(0,maxlength).map(phone => ({
        phone: phone,
        name: null,
        gender: null
    }))
}
function onImport(){
	uni.showLoading({
		title: '识别中',
	})
	const phones = convertPhoneNumbers(state.importVal,1000)
	if(!phones||!phones.length){
		uni.hideLoading()
		uni.showToast({
		  title: '识别失败',
		  icon: 'none'
		})
		return
	}
	if(formData.phoneList.length===1&&!formData.phoneList[0].phone&&!formData.phoneList[0].name&&!formData.phoneList[0].gender){
		formData.phoneList = phones
	}else{
		phones.forEach((item) => {
		  formData.phoneList.push(item);
		})
	}
	uni.hideLoading()
	state.showImport = false
}
</script>

<style lang="scss" scoped>
.form_label{
	font-weight: bold;
	font-size: 40rpx;
	color: #222222;
	line-height: 58rpx;
	padding: 40rpx 30rpx 10rpx;
}
.form_item {
  margin: 30rpx;
  padding: 20rpx 20rpx 10rpx;
  width: 690rpx;
  min-height: 172rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  flex-wrap: wrap;
  position: relative;
  .close_icon{
  	width: 48rpx;
  	height: 48rpx;
  	position: absolute;
  	top: 20rpx;
  	right: 20rpx;
  	background: url('/static/close-icon.png') no-repeat center/48rpx 48rpx;
  }
  .label{
	  width: 100%;
	  font-weight: bold;
	  font-size: 28rpx;
	  color: #222222;
	  line-height: 40rpx;
	  margin-bottom: 20rpx;
  }
  :deep(){
  	.uni-forms-item__inner{
  		padding-bottom: 40rpx;
  	}
  	.uni-easyinput__placeholder-class{
  		font-weight: 400;
  		font-size: 28rpx;
  		color: #CCCCCC;
  	}
  	.uni-easyinput{
  		background: #FAFAFA;
  		border-radius: 20rpx;
		width: 236rpx;
		margin-right: 20rpx;
  	}
  	.uni-easyinput__content-input{
  		height: 72rpx;
  		line-height: 72rpx;
  		padding: 0 20rpx !important;
  		box-sizing: border-box;
  		font-weight: 500;
  		font-size: 28rpx;
  		color: #222222;
  	}
	.uni-stat__select{
		.uni-stat-box{
			border-radius: 20rpx;
		}
	}
	.uni-select{
		height: 72rpx;
		width: 136rpx;
		border: none;
		padding: 0 20rpx !important;
		background: #FAFAFA;
		box-sizing: border-box;
		.uni-select__input-box{
			height: 72rpx;
			.uni-select__input-placeholder{
				font-weight: 400;
				font-size: 28rpx;
				color: #999999;
			}
		}
	}
  }
}
.add_btn_box{
	padding: 80rpx 0 534rpx;
	.add_btn{
		margin: 0 auto;
		width: 216rpx;
		height: 82rpx;
		min-height: 82rpx;
		background: url('/static/add_btn.png') no-repeat center/216rpx 82rpx;
	}
}

.submit_btn{
	width: 630rpx;
	height: 104rpx;
	line-height: 104rpx;
	background: #35E89A;
	border-radius: 40rpx;
	font-weight: bold;
	font-size: 32rpx;
	color: #222222;
	text-align: center;
	position: fixed;
	left: calc(50%);
	transform: translateX(-50%);
	bottom: 40rpx;
}
.import_wrap{
	width: 610rpx;
	min-height: 450rpx;
	padding: 34rpx 30rpx 30rpx;
	background: #FFFFFF;
	box-sizing: border-box;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	.import_cont{
		.title{
			font-size: 28rpx;
			line-height: 40rpx;
			display: flex;
			align-items: center;
			.label{
				font-weight: bold;
				color: #222222;
			}
			.span{
				font-weight: 400;
				color: #999999;
			}
		}
		
		.cont{
			margin: 30rpx 0;
			background: #FAFAFA;
			border-radius: 20rpx;
			padding: 30rpx;
			height: 480rpx;
			box-sizing: border-box;
			:deep(.uni-easyinput){
				.uni-easyinput__content{
					.uni-easyinput__content-textarea{
						height: 420rpx;
						overflow-y: auto;
						padding: 0;
					}
				}
			}
			
		}
	}
	.group_btn{
		display: flex;
		align-items: center;
		.item_btn{
			flex: 1;
			height: 104rpx;
			line-height: 104rpx;
			border-radius: 40rpx;
			text-align: center;
			font-weight: bold;
			font-size: 32rpx;
			color: #FFFFFF;
			margin-left: 18rpx;
		}
		.item_btn:first-child{
			margin-left: 0;
		}
		.cancel_btn{
			background: #CCCCCC;
		}
		.confirm_btn{
			background: #222222;
		}
		.logout-btn{
			background: #FF4E4E;
		}
	}
}
</style>