<template>
	<view class="problemHandleItem">
		<!--		<view class="font-md text-dark">问题处理</view>-->
		<u--form labelPosition="left" :model="problemHandleData" labelWidth="80">
			<u-form-item label="问题处理" prop="dealResult">
				<u-radio-group v-model="problemHandleData.dealResult" placement="column" @change="groupChange">
					<!--					<u-radio label="退回修改" name="2" :disabled="onlyFlag" class="mb-2" @change="radioChange"></u-radio>-->
					<u-radio label="办结" name="3" :disabled="onlyFlag" class="mb-2" @change="radioChange"></u-radio>
					<u-radio label="反馈大走访活动办"
						v-if="typeName == 'question' && (userInfo.enterpriseAreaFlag || userInfo.enterpriseCadreFlag)" name="4"
						:disabled="onlyFlag" @change="radioChange" class="mb-2"></u-radio>
					<u-radio label="正在办理"
						v-if="typeName == 'question' && (userInfo.enterpriseAreaFlag || userInfo.enterpriseCadreFlag || userInfo.assignedDeptFlag)"
						name="10" :disabled="onlyFlag" @change="radioChange" class="mb-2"></u-radio>
					<u-radio label="难以化解"
						v-if="typeName == 'question' && (userInfo.enterpriseAreaFlag || userInfo.enterpriseCadreFlag) || userInfo.assignedDeptFlag"
						name="11" :disabled="onlyFlag" @change="radioChange" class="mb-2"></u-radio>
					<u-radio label="持续跟踪"
						v-if="typeName == 'question' && (userInfo.enterpriseAreaFlag || userInfo.enterpriseCadreFlag) || userInfo.assignedDeptFlag"
						name="12" :disabled="onlyFlag" @change="radioChange" class="mb-2"></u-radio>
					<u-radio label="提请会办"
						v-if="typeName == 'question' && (userInfo.enterpriseAreaFlag || userInfo.enterpriseCadreFlag) || userInfo.assignedDeptFlag"
						name="13" :disabled="onlyFlag" @change="radioChange" class="mb-2"></u-radio>
					<u-radio label="交办" v-if="typeName == 'question' && userInfo.ydGxjLeaderFlag" name="5" :disabled="onlyFlag"
						@change="radioChange">
					</u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item label="预计办结时间：" @click="choosePreTime" prop="preTime"
				v-if="!onlyFlag || ((problemHandleData.preTime && !outCharge) || outCharge)" labelWidth="120">
				<u--input v-model="problemHandleData.preTime" readonly :border="onlyFlag ? 'none' : 'surround'"
					:placeholder="'请选择预计办结时间'">
				</u--input>
				<view class="icon-clear" @click.stop="clearIcon" v-if="!onlyFlag">
					<uni-icons type="clear" color="#e1e1e1" size="24"></uni-icons>
				</view>
			</u-form-item>
			<!-- <view class="error-tip" v-if="!problemHandleData.dealResult openAssignPick&& errorTip">
				请选择处理结果
			</view> -->
			<u-form-item label="交办单位：" prop="assignedDeptName" v-if="problemHandleData.dealResult == '5'"
				@click.native="openAssignPick">
				<slot>
					<view class="d-flex j-sb a-center">
						<text v-show="problemHandleData.assignedDeptName"
							class="text-secondary">{{problemHandleData.assignedDeptName}}</text>
						<text v-show="!problemHandleData.assignedDeptName" class="font-md"
							style="color: rgb(192, 196, 204);">请选择交办单位</text>
						<u-icon v-if="!onlyFlag" name="arrow-down" color="#303133" size="15">
						</u-icon>
					</view>
				</slot>
			</u-form-item>
			<u-form-item label="退回单位：" prop="backDept" v-if="problemHandleData.dealResult == '2'&&roleLevel=='4'">
				<song-data-picker style="width: 100%;" @click.native="songClick" :readonly="onlyFlag" :clearIcon="false"
					:localdata="columns" :placeholder="!onlyFlag ? '请选择退回单位' : ''" popup-title="请选择退回单位"
					@nodeclick="onnodeclick2">
					<slot name="data">
						<view class="d-flex j-sb a-center border p-1 rounded8" style="border-color: rgb(218, 219, 222, 0.5);">
							<view class="text-secondary">
								<text v-show="problemHandleData.backDeptName">{{problemHandleData.backDeptName}}</text>
								<text v-show="!problemHandleData.backDeptName" style="color: rgb(192, 196, 204);"
									class="font-md">请选择退回单位</text>
							</view>
							<u-icon v-if="!onlyFlag" name="arrow-down" color="#303133" size="15">
							</u-icon>
						</view>
					</slot>
				</song-data-picker>
			</u-form-item>
			<u-form-item :label="labelTitle" prop="dealSuggestion">
				<u--textarea v-model="problemHandleData.dealSuggestion" :disabled="onlyFlag"
					:border="onlyFlag ? 'none' : 'surround'" :placeholder="!onlyFlag ? '请填写处理建议' : ''">
				</u--textarea>
			</u-form-item>
			<u-form-item label="附件：" prop="file" v-if="!qiYeFlag">
				<u-upload accept="file" :disabled="onlyFlag" @afterRead="afterRead" name="1" multiple :maxCount="10">
					<u-button type="primary" icon="plus" text="上传附件"></u-button>
				</u-upload>
			</u-form-item>
			<u-form-item label=" " prop="">
				<view class="d-flex flex-wrap">
					<view class="w-100 d-flex" v-for="(item,index) in problemHandleData.fileList" :key="index">
						<u--text type="primary" :text="item.name" @tap="downloadFile(index)"></u--text>
						<u-icon class="ml-1" name="close-circle" color="#F56C6C" size="16" v-if="!onlyFlag"
							@tap="deletePic(index)"></u-icon>
					</view>
				</view>
			</u-form-item>
			<!-- <view class="error-tip" v-if="!problemHandleData.dealSuggestion && errorTip">
				请填写处理建议
			</view> -->

		</u--form>
		<m-multiple-picker ref="multiplePicker" :pickerTitle="{text: '交办单位',color:'#101010',fontSize:'32rpx'}"
			:cancelBtn="{text: '取消',color:'#666666',fontSize:'32rpx'}"
			:confirmBtn="{text: '确定',color:'#2f77f1',fontSize:'32rpx'}" :mapKeys="{ label: 'label', value: 'value' }"
			searchPlaceholder="筛选交办单位" :openSearch="true" textAlign="left" :dataList="radarOverlyingList"
			:checkedVals="radarOverVals" @mulConfirm="multipleConfirm"></m-multiple-picker>
		<u-datetime-picker :show="preTimeShow" :confirmDisabledText=" '请选择预计办结时间'" closeOnClickOverlay mode="date"
			@confirm="preTimeConfirm" @cancel="preTimeShow=false" @close="preTimeShow=false" :minDate="1704038400000">
		</u-datetime-picker>
	</view>
</template>

<script>
	import {Global} from "@/common/Global.js";
	import {Store} from "@/common/store.js";
	import {formatDate} from "@/common/util2.js"
	export default {
		props: {
			problemType: {
				type: String,
				default: ''
			},
			roleLevel: {
				type: String,
				default: ''
			},
			problemHandleData: {
				type: Object,
				default: () => {}
			},
			userInfo: {
				type: Object,
				default: () => {}
			},
			readOnlyFlag: {
				type: Boolean,
				default: false
			},
			showErrorTip: {
				type: Boolean,
				default: false
			},
			column: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				preTimeShow: false,
				outCharge: false,
				radarOverVals: [],
				num: 0, //用于区分是否是重复选中,
				show: false,
				columns: [{
						text: "企业",
						value: "10"
					},
					{
						text: "挂钩干部",
						value: "20"
					},
					{
						text: "属地干部",
						value: "30"
					},
				],
				qiYeFlag: true,
				labelTitle: '处理建议 '
			}
		},
		watch: {
			'problemHandleData.assignedDept': {
				handler(newVal, oldVal) {
					if (!newVal) return
					this.column.forEach(ele => {
						if (ele.enCode === newVal) {
							this.$set(this.problemHandleData, 'assignedDeptName', ele.fullName)
						}
					})
				}
			}
		},
		computed: {
			onlyFlag() {
				return this.readOnlyFlag
			},
			errorTip() {
				return this.showErrorTip
			},
			typeName() {
				return this.problemType
			},
			unitColumn() {
				const column = (this.column || []).map(ele => {
					const obj = {}
					obj.text = ele.fullName
					obj.value = ele.enCode
					return obj
				})
				return column
			},
			radarOverlyingList() {
				const column = (this.column || []).map(ele => {
					const obj = {}
					obj.label = ele.fullName
					obj.value = ele.enCode
					return obj
				})
				console.log("radarOverlyingList: ", column)
				return column
			}
		},

		mounted() {
			const userInfo = Store.getUser() ? JSON.parse(Store.getUser()) : {}
			this.qiYeFlag = userInfo?.roleLevel === '1'
			this.outCharge = userInfo?.roleLevel === '5'
			if (userInfo?.roleLevel === '4') {
				this.labelTitle = '交办要求'
			}

			console.log("userInfo?.roleLevel: ", userInfo?.roleLevel)
		},
		methods: {
			clearIcon(e) {
				this.$set(this.problemHandleData, 'preTime', null)
			},
			choosePreTime() {
				// if (!(this.problemHandleData.status == '4' && this.outCharge) || this.onlyFlag) return
				if (this.onlyFlag) return
				this.preTimeShow = true;
				uni.hideKeyboard()
			},
			preTimeConfirm(e) {
				this.preTimeShow = false
				this.$set(this.problemHandleData, 'preTime', formatDate(e.value, 'yyyy-MM-dd'))
			},
			songClick() {
				uni.hideKeyboard()
			},
			onnodeclick2(ele) {
				this.$set(this.problemHandleData, 'backDeptName', ele.text)
				this.$set(this.problemHandleData, 'backDept', ele.value)
			},
			downloadFile(index) {
				const downloadLink = Global.baseUrl + this.problemHandleData.fileList[index].url;
				window.open(downloadLink, '_blank'); //h5直接进行跳转页面打开就可以了
				uni.downloadFile({ //调用uni中的下载方法
					url: Global.baseUrl + this.problemHandleData.fileList[index].url, //后端返回的完整路径
					success: (res) => {
						console.log(res.tempFilePath, "下载");
						if (res.statusCode === 200) {
							const tempFilePath = res.tempFilePath;
							// 显示文件
							uni.openDocument({
								filePath: tempFilePath,
								success: (res) => {
									console.log(res, '打开文件成功');
								},
							});
						}
					},
					fail: (err) => {
						console.log('下载文件失败', err);
					}
				});
			},
			deletePic(index) {
				this.problemHandleData.fileList.splice(index, 1)
			},
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log('lists', lists)
				let fileListLen = this.problemHandleData.fileList ? this.problemHandleData.fileList.length : 0
				lists.map((item) => {
					if (!this.problemHandleData.fileList) {
						this.problemHandleData.fileList = [{
							...item,
							status: 'uploading',
							message: '上传中'
						}]
					} else {
						this.problemHandleData.fileList.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					}
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.problemHandleData.fileList[fileListLen]
					this.problemHandleData.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				console.log('全部上传完了', this.problemHandleData.fileList)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: Global.baseUrl + '/api/file/Uploader/chain', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							console.log('upload', res)
							if (res.data) {
								let response = JSON.parse(res.data)
								if (response.data) {
									setTimeout(() => {
										resolve(response.data.url)
									}, 1000)
								}
							}

						}
					});
				})
			},
			// 交办单位检索
			mySearchFn(searchList, searchWord) {
				return searchList.filter(x => x.text.includes(searchWord));
			},
			// 交办单位选择变化操作
			onnodeclick(ele) {
				console.log("ele: ", ele)
				this.$set(this.problemHandleData, 'assignedDeptName', ele.text)
				this.$set(this.problemHandleData, 'assignedDept', ele.value)
			},
			openAssignPick() {
				this.$refs.multiplePicker.openMulpicker()
			},

			multipleConfirm(item) {
				const selectItems = item.value
				const objValues = item.objValue
				this.radarOverVals = selectItems
				this.$set(this.problemHandleData, 'assignedDept', selectItems.toString())
				if (objValues.length > 0) {
					const labelName = objValues.map(t => t.label)
					this.$set(this.problemHandleData, 'assignedDeptName', labelName.toString())
				}
			},
			// 处理结果点击确认
			groupChange(ele) {
				if (ele == this.problemHandleData.dealResult && this.num == 0) {
					this.num++ // 第一次相等即执行以下代码
				} else {
					// 第一次后相等即执行以下代码 --> 置空 radioGroupValue 即取消选中的值
					this.problemHandleData.dealResult = ''
					this.num = 0 // 初始化 num
				}
				if (this.problemHandleData.dealResult != '5') {
					this.problemHandleData.assignedDeptName = ''
					this.problemHandleData.assignedDept = ''
					this.problemHandleData.dealSuggestion = ''
				} else {
					this.problemHandleData.assignedDeptName = this.column[0].fullName
					this.problemHandleData.assignedDept = this.column[0].enCode
					this.radarOverVals = [this.column[0].enCode]
					this.problemHandleData.dealSuggestion = '请2日内回应，10内反馈办理结果，如办结请上传加盖公章的书面材料'
				}
			},
			radioChange(v) {
				this.problemHandleData.dealResult = v
				this.num = 0 // 切换选项后需要初始化 num
			},
			// 判断是否有必填项为填写
			isRequired() {
				const query = uni.createSelectorQuery().in(this);
				let dataLength = 0
				query.selectAll('.error-tip').boundingClientRect(data => {
					dataLength = data.length
					if (dataLength) {
						uni.$u.toast('请完善必填项内容')
					}
				}).exec();
				return dataLength
			}
		}
	}
</script>

<style lang="scss" scoped>
	.error-tip {
		font-size: 12px;
		color: #f56c6c;
		margin-left: 160rpx;
	}
</style>