<template>
	<view class="bg">
		<view class="title_wrap"><text class="title">基本信息</text></view>
		<car-number-input @numberInputResult="carNumber" :defaultStr="state.form.vehiclePlate"></car-number-input>
		<u-form label-width="230" :model="state.form" ref="uForm" :label-style='labelStyle'>
			<u-form-item label="车牌颜色" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
					<u-input v-model="state.vehiclePlateColorStr" type="select" @click="show1 = true" input-align='right'/>
			</u-form-item>
			<u-form-item label="姓名" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
				<u-input placeholder='请输入姓名' v-model="state.form.customerName" maxlength="18"
					inputAlign="right" />
			</u-form-item>
			<u-form-item label="联系方式" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
				<u-input placeholder='请输入手机号码' type="number" v-model="state.form.customerTel" maxlength="11"
					inputAlign="right" />
			</u-form-item>
		</u-form>
	</view>
	<view class="bg">
		<view class="title">工单信息</view>
        <u-form label-width="230" :model="state.form" ref="uForm" :label-style='labelStyle' borderBottom>
			<u-form-item label="工单类型" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
					<u-input v-model="state.questionTypeStr" type="select" @click="show2 = true" input-align='right'/>
			</u-form-item>
			<u-form-item label="是否ETC用户" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
					<u-input v-model="state.etcUserStr" type="select" @click="show3 = true" input-align='right'/>
			</u-form-item>
			<u-form-item label="事件发生日期" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
				<picker mode="date" @change="bindDateChange">
					<view class="picker" v-if="!state.form.eventOccurrenceTime">
					  请选择日期
					</view>
					<view class="data">
						{{state.form.eventOccurrenceTime}}
					</view>
			  </picker>
			</u-form-item>
			<u-form-item label="客户诉求" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
				borderBottom>
			</u-form-item>
			<textarea v-model="state.form.appeal" style="border: 1rpx dashed rgb(192, 196, 204);min-height: 200rpx; width: 100%;border-radius: 18rpx;padding: 20rpx;box-sizing: border-box;" placeholder="请输入述求" auto-height adjust-position></textarea>
		   <u-form-item label="其他佐证材料" :left-icon='`${$imgUrl}issuance/point-form.png`' :left-icon-style='leftIcon'
		   	borderBottom>
		   		<text class="common-word">(不限于图片、文件、不超过5个。)</text>
		   </u-form-item>
		   <view class="down-wrap" v-for="(item,index) in state.supportingMaterialsUrlShow" :key="index">
			   <text>附件{{index+1}}</text>
			   <view>
				   <text class="down" @click="down(item,index)">预览</text>
				   <text class="down" @click="deleteFile(index)">删除</text>
			   </view>
		   </view>
		   <button type="default" class="ui-btn-another" @click="addFile()">+添加附件</button>
		</u-form>
	</view>
	<view class="action">
		<button type="default" class="ui-btn" @click="savaHandle()">
			提交
		</button>
	</view>
	<!-- 选择车牌颜色 -->
	<u-select v-model="show1" :list="state.colorRange" @confirm="changeColor"></u-select>
	<!-- 工单类型 -->
	<u-select v-model="show2" :list="state.questionTypeRange" @confirm="changeQuestionType"></u-select>
	<!--  -->
	<u-select v-model="show3" :list="state.etcUserRange" @confirm="changeEtcUser"></u-select>

</template>

<script setup lang="ts">
	import { navTo,msg,uploadFile, getFullImageUrl } from "@/utils/utils";
	import { reactive,ref } from "vue";
	import carNumberInput from "@/components/car-number-input/car-number-input.vue";
	import { onLoad } from "@dcloudio/uni-app";
	import { getItem } from "@/utils/storage.ts"
    import {requestNew} from "@/utils/network/request.js";
	import {selfServiceUserAdd} from "@/utils/network/api.js";
	import { getCodeName } from '@/datas/queryKey.js'
	
	interface uploadResponce {
		imageUrl: string
	}
	
	const labelStyle = {
		color: "#004576",
		fontSize: "28rpx",
	}
	const leftIcon = {
		height: '100%',
		width: '8rpx',
		display: 'flex',
		'align-items': 'center',
		'margin-right': '4rpx',
	}
	const show1 = ref(false)
	const show2 = ref(false)
	const show3 = ref(false)
	const state = reactive({
		form: {
			customerName: "",
			customerTel: "",
			vehiclePlate: "",
			vehiclePlateColor: "",
			questionType:"",
			etcUser:"",
			eventOccurrenceTime:"", //2016-09-01 00:00:00
			appeal:"",
			supportingMaterialsUrl:"",
		},
		supportingMaterialsUrlShow:[],
		etcUserStr: '',
		vehiclePlateColorStr: '',
		questionTypeStr:"",
		colorRange: [],
		questionTypeRange:[],
		etcUserRange:[
			{value: 1, label: "是"},
			{value: 0, label: "否"},
		],
	})
	onLoad((option : any) => {
		state.colorRange = setDicCode('VEHICLE_COLOR_TYPE')
		state.questionTypeRange = setDicCode('SELF_SERVICE_TYPE')
	});
	
	// 设置字典
	const setDicCode = (codeName:string) => {
		let dic = getItem('key')[codeName];
		if (!dic) return []
		let arr = []
		for (var k = 0; k < dic.length; k++) {
			let obj = {};
			obj['value'] = dic[k]['code']
			obj['label'] = dic[k]['name']
			arr.push(obj)
		}
		return arr
	}
	
	const getCarColorName = (code: string) => {
		return getCodeName('VEHICLE_COLOR_TYPE', code)
	}
	
	const getSelfTypeName = (code: string) => {
		return getCodeName('SELF_SERVICE_TYPE', code)
	}

	//车牌号输入
	const carNumber = (val : any) => {
		state.form.vehiclePlate = val.trim();
	};
	
	const changeColor = (item) => {
			state.form.vehiclePlateColor = item[0].value
			state.vehiclePlateColorStr = item[0].label
			console.log(item)
		}
	const changeQuestionType = (item) => {
			state.form.questionType = item[0].value
			state.questionTypeStr = item[0].label
			console.log(item)
		}
    const changeEtcUser = (item) => {
    		state.form.etcUser = item[0].value
    		state.etcUserStr = item[0].label
    		console.log(item)
    	}
const bindDateChange=(e)=>{
    console.log('picker发送选择改变，携带值为', e.detail.value)
	state.form.eventOccurrenceTime= e.detail.value
  }
	const savaHandle = () => {
		if(!state.form.vehiclePlate){
			msg('请输入车牌号');
			return;
		}
		if(!state.form.vehiclePlateColor){
			msg('请选择车牌颜色');
			return;
		}
		if(!state.form.customerName){
			msg('请输入姓名');
			return;
		}
		if(!state.form.customerTel){
			msg('请输入手机号码');
			return;
		}
		if(!state.form.questionType){
			msg('请选择工单类型');
			return;
		}
		if(!state.form.etcUser){
			msg('请选择是否ETC用户');
			return;
		}
		if(!state.form.eventOccurrenceTime){
			msg('请选择事件发生日期');
			return;
		}
		if(!state.form.appeal){
			msg('请输入述求');
			return;
		}
		if(state.supportingMaterialsUrlShow && state.supportingMaterialsUrlShow.length === 0){
			msg('请上传其他佐证材料');
			return;
		}
		let params = JSON.parse(JSON.stringify(state.form))
		params.eventOccurrenceTime = state.form.eventOccurrenceTime+" 00:00:00"
		params.supportingMaterialsUrl = state.supportingMaterialsUrlShow.toString()
		const options = {
			type: 2,
			data: params,
			method: "POST",
			showLoading: true,
		};
		requestNew(selfServiceUserAdd, options).then((res) => {
			msg("新增自助工单成功")
			setTimeout(()=>{
				uni.navigateBack()
			},1500)
		});
	}
	const addFile=()=>{
		const count = 5 - state.supportingMaterialsUrlShow.length
		uni.chooseMessageFile({
		  count: count,
		  type: 'all',
		  success (res) {
		    // tempFilePath可以作为img标签的src属性显示图片
		    console.log("res",res)
			var files=res.tempFiles
			for(var i = 0;i < files.length; i++){
				uploadFile(files[i]['path']).then((data: uploadResponce) => {
					state.supportingMaterialsUrlShow.push(data.imageUrl);
				})
			}
			
		  }
		})
	}
	const down=(item,index)=>{
		const lastDotIndex = item.lastIndexOf(".");
		const result = item.substring(lastDotIndex+1);
		if(result=='jpg' || result=='png'){
			uni.previewImage({
				urls:[getFullImageUrl(item)],
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function(data) {
						console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					},
					fail: function(err) {
						console.log(err.errMsg);
					}
				}
			});
		}else{
			uni.downloadFile({
				url: getFullImageUrl(item),
				success(res) {
					console.log("下载",res)
					const filePath = res.tempFilePath
					uni.openDocument({
						filePath: filePath,
						showMenu: true, // 关键点
						success: function (res) {
							msg("打开文档成功");
						},
						fail: function (err) {
							msg("打开文档失败");
						}
					});
				},
				fail: function (err) {
					msg("下载文档失败");
					console.log("err", err)
				},
				complete(res) {
			
				}
			})
		}
	
	}
	const deleteFile=(index)=>{
		state.supportingMaterialsUrlShow.splice(index,1)
	}
</script>

<style lang="scss" scoped>
	.bg {
		background-color: white;
		width: 88%;
		margin: 0 auto;
		margin-top: 20rpx;
		border-radius: 12px;
		border: 1px solid #FFFFFF;
		padding: 20rpx;
		overflow: hidden;

		.title_wrap {
			display: flex;
			font-weight: 400;
			margin-bottom: 40rpx;

			.title {
				font-size: 30rpx;
				color: #01243A;
			}
		}

		.des {
			font-weight: 400;
			font-size: 28rpx;
			color: #01243A;
			line-height: 56rpx;
			margin-top: 10rpx;
			text-indent: 1rem;
		}
	}

	.action {
		position: absolute;
		left: 0;
		height: 188rpx;
		background-color: #fff;
		border-radius: 30rpx 30rpx 0 0;
		width: 100vw;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		margin-top: 20rpx;
	}
	.picker{
		text-align: right;
		color: rgb(192, 196, 204);
	}
	.data{
		text-align: right;
	}
	.five{
		color: rgb(195,188,157);
	}
	.down-wrap{
		display: flex;
		justify-content: space-between;
		margin-bottom: 35rpx;
		.down{
			width: 100rpx;
			height: 50rpx;
			border-radius: 20rpx;
			background:linear-gradient(90deg, #CCB375 0%, #E7D398 100%);
			font-weight: 400;
			font-size: 24rpx;
			color: #FFFFFF;
			text-align: center;
			line-height: 50rpx;
			display: inline-block;
			margin-left: 16rpx;
		}
	}
</style>