<template>
	<u-popup :show="show" @close="cancel" :closeable="false">
		<view style="width: 750rpx;">

			<u--form ref="uForm" labelPosition="left" :model="form" labelWidth="180" labelAlign="left" :rules="rules">

				<u-form-item label="文档位置" prop="directoryName">
					<u--input placeholder="请选择" border="surround" v-model="form.directoryName"
						@click.native="directoryIdOpen">
					</u--input>
				</u-form-item>

				<u-form-item label="编码分类" prop="codeTypeName">
					<u--input placeholder="请选择" border="surround" v-model="form.codeTypeName"
						@click.native="codeTypeOpen">
					</u--input>
				</u-form-item>


				<u-form-item label="编码方案" prop="businessCodeId">
					<zxz-uni-data-select :localdata="options" v-model="form.businessCodeId" dataValue='id'
						dataKey="name"></zxz-uni-data-select>
				</u-form-item>




				<!-- 	<u-cell title="编码方案">
					<uni-data-picker :map="{text:'name',value:'id'}" v-model="form.businessCodeId" slot="value"
						placeholder="请选择" :localdata="options">
					</uni-data-picker>
				</u-cell> -->


				<!-- 	<u-cell title="文档类型">
						<uni-data-picker v-model="form.type" slot="value" placeholder="请选择" :localdata="doc_type">
					</uni-data-picker>
					

					</u-cell> -->


				<u-form-item label="文档类型" prop="type">
					<zxz-uni-data-select :localdata="doc_type" v-model="form.type" dataValue='value'
						dataKey="text"></zxz-uni-data-select>
				</u-form-item>


				<!-- <u-form-item :label="文档类型" prop="form.type">
					<zxz-uni-data-select :localdata="doc_type" v-model="form.type" dataValue='value'
						dataKey="text"></zxz-uni-data-select>
				</u-form-item> -->

				<u-cell title="文档">
					<fileSelector class="fileList" slot="value" @filesChanged="onFilesChanged" />
				</u-cell>


				<view class="btn">
					<u-button type="primary" @click="cancel" text="返回"></u-button>
					<u-button @click="save" text="保存"></u-button>
				</view>

			</u--form>


		</view>
		<u-toast ref="uToast"></u-toast>
		<ba-tree-picker ref="directoryIdRef" :multiple="false" title="选择文档位置" :localdata="folderList" valueKey="id"
			textKey="name" childrenKey='sonDirectoryList' @select-row="directoryIdBack" />

		<ba-tree-picker ref="codeTypeRef" key="verify" :multiple="false" @select-row="codeTypeBack" title="选择编码分类"
			:localdata="list" valueKey="id" textKey="name" childrenKey='sonDirectoryList' />

	</u-popup>
</template>

<script>
	import {
		fileSaveAPI,
		selectTreeList,
		listParentId,
		getDocTreeListAPI,
		listCode
	} from './api/index';
	import {
		getByCode
	} from '@/api/pda/common.js'
	import baTreePicker from "@/components/ba-tree-picker/ba-tree-picker.vue"
	// 引入组件
	import fileSelector from '@/uni_modules/zhouquan-fileSelector/components/zhouquan-fileSelector/file-selector.vue';
	export default {
		components: {
			baTreePicker,
			fileSelector
		},
		data() {
			const defaultForm = {
				name: '', //名称
				type: '', //类型
				sizeUnit: '', //大小，
				unit: '', //单位
				remark: '', //备注
				status: '', //状态
				storagePathId: '',
				directoryId: '',
				businessCodeId: '',
				storagePath: [],
				id: '',
				lcyStatus: 1,
				fileType: 0,
				codeTypeName: '',
				directoryName: '',

			};
			return {
				folderList: [],
				files: [],
				// 表单数据
				form: {
					...defaultForm
				},
				list: [],
				options: [],
				show: false,
				doc_type: [],
				rules: {
					'directoryName': {
						type: 'string',
						required: true,
						message: '请选择文档位置',
						trigger: ['blur', 'change']
					},
					'businessCodeId': {
						type: 'string',
						required: true,
						message: '请选择编码方案',
						trigger: ['blur', 'change']
					},
				},
				nodeData: {}

			};
		},

		async created() {
			this.userInfo = uni.getStorageSync('userInfo')
			let query = {
				type: 0,
				currentUserId: this.userInfo.userId
			};
			this.folderList = await getDocTreeListAPI(query);
			const doc_type = await getByCode('doc_type');
			this.doc_type = doc_type.map(item => {
				const key = Object.keys(item)[0]
				return {
					value: key,
					text: item[key]
				}
			})
		},
		methods: {
			async open() {

				this.show = true;
				this.list = await selectTreeList();
				this.options = await listCode();
				if (this.options.length > 0) {
					this.form.businessCodeId = this.options[0].id
				}
				this.setTree(this.list);
			},
			setTree(data) {
				data.forEach((item) => {
					item.sonDirectoryList = item.sonDirectoryList.filter(
						(item) => item.type == 1
					);
					if (item.sonDirectoryList.length > 0) {
						this.setTree(item.sonDirectoryList);
					}
				});
			},

			codeTypeOpen() {
				this.$refs.codeTypeRef._show()
			},
			async directoryIdBack(data) {
				console.log(data);
				this.nodeData.id = data?.id
				this.nodeData.parentId = data.parentId == -1 ? '' : data.parentId

				this.form.directoryName = data.name
				this.form.directoryId = data.id

				this.options = this.nodeData.id ? await listCode(this.nodeData) : [];

				if (this.options.length > 0) {
					this.form.businessCodeId = this.options[0].id;
					this.form.codeType = this.options[0].parentId;
				} else {
					this.form.businessCodeId = '';
				}

				// this.form.directoryName = name
				// this.form.directoryId = data[0]

			},
			async codeTypeBack(data, name) {
				console.log(data);

				let list = await listParentId({
					pageNum: 1,
					size: 100,
					parentId: data.id,
					objId: this.nodeData?.id,
					objParentId: this.nodeData?.parentId
				});
				// this.form.codeTypeName = data.name
				// this.form.codeType = data
				this.options = list.list.filter((item) => item.type == 2);
				this.form.codeType = data.id;
				this.form.codeTypeName = data.name;
				this.form.businessCodeId = '';
			},
			uploadFile(list) {
				let PromiseAll = []
				const apiUrl = this.apiUrl
				const token = uni.getStorageSync("token"); //取存本地的token
				list.forEach(item => {
					PromiseAll.push(
						new Promise((resolve, reject) => {
							uni.uploadFile({
								url: apiUrl + '/main/file/uploadFile',
								filePath: item.path,
								name: 'multiPartFile',
								header: {
									authorization: token
								},
								success: (uploadFileRes) => {
									let data = JSON.parse(uploadFileRes.data)
									resolve(data.data)
								}
							});
						}),
					)
				})
				return Promise.all(PromiseAll)
			},
			directoryIdOpen() {
				this.$refs.directoryIdRef._show()
			},

			// 当文件发生变化时触发
			onFilesChanged(fileList) {
				console.log(fileList);
				this.files = fileList
				this.form.name = fileList[0].name.replace(/\.[^/.]+$/, '');

				// console.log('文件列表：', fileList)
			},
			/* 保存编辑 */
			async save() {


				if (!this.form.directoryName) {
					this.$refs.uToast.show({
						type: "error",
						message: "请选择文档位置",
					})
					return
				}
				if (!this.form.businessCodeId) {
					this.$refs.uToast.show({
						type: "error",
						message: "请选择编码方案",
					})
					return
				}
				uni.showLoading({
					title: '加载中'
				})

				this.form.storagePath = await this.uploadFile(this.files)
				let params = {
					...this.form
				}
				delete params.codeTypeName
				delete params.directoryName

				fileSaveAPI(this.form)
					.then((msg) => {
						uni.hideLoading()
						console.log(msg, 'msg')

						this.$emit('success', msg);
						this.cancel()
					})
					.catch((e) => {
						uni.hideLoading()
						this.cancel()

					});







			},

			cancel() {
				this.form = {
					...this.defaultForm
				};
				this.files = []
				this.show = false;
			}
		}
	};
</script>
<style scoped lang="scss">
	.aaa {
		width: 100%;

		::v-deep .upload-demo {
			width: 100%;

			.el-upload--text {
				width: 100%;

				button {
					width: 100%;
					background: #ffffff;
					border: 1px solid #dbdbdb;
					border-radius: 5px;
				}
			}

			.el-upload-list {
				transform: translate(10px, -39px);
				position: absolute;
			}
		}
	}

	.fileList {
		padding: 0;

		/deep/.upload-area {
			height: 90rpx;
			width: 140rpx;
		}

		/deep/.file-item {
			padding: 0;
			margin-bottom: 8rpx;
		}
	}

	.btn {
		margin-top: 16rpx;
		margin-bottom: 10rpx;
		display: flex;

		uni-bottom {
			width: 160rpx;
		}

	}

	// /deep/.u-form-item__body {
	// 	padding: 16rpx 0
	// }

	/deep/ .u-form {
		padding: 30rpx;
	}
</style>