<template>
	<view class="patrolAdd">
		<head-view :title="title" url="/pages/shipWork/patrol"></head-view>
		<view class="container contentFixed">
			<view class="ul">
				<view class="li">
					<p>船名：</p>
					<text>{{shipInfo.vslCnname}}</text>
				</view>
				<view class="li">
					<p><text class="required" v-if="obj.state != 'look'">*</text>航次：</p>
					<uni-data-select v-model="vvyId" :localdata="hcList" @change="hcChange"
						v-if="obj.state != 'look'"></uni-data-select>
					<text v-else>{{patrolRow.vvyName}}</text>
				</view>
				<view class="li">
					<p>进出口：</p>
					<text>{{importExportName}}</text>
				</view>
				<view class="li">
					<p>贸易类型：</p>
					<text>{{spmTradeName}}</text>
				</view>
				<view class="li">
					<p><text class="required" v-if="obj.state != 'look'">*</text>类型：</p>
					<uni-easyinput v-if="obj.state != 'look'" v-model="type" placeholder="请输入"></uni-easyinput>
					<text v-else>{{patrolRow.type}}</text>
				</view>
				<view class="li tpLi">
					<p><text class="required" v-if="obj.state != 'look'">*</text>图片上传：</p>
					<template v-if="obj.state != 'look'">
						<view class="picture">
							<uni-file-picker limit="9" v-model="urlList2" fileMediatype="image" @select="select"
								@delete="delUrl" title="最多选择9张图片"></uni-file-picker>
						</view>
					</template>
					<view class="pictureLook" v-else>
						<view v-for="(item,index) in urlList2" :key="index">
							<image :src="item.url" mode="widthFix" @click="clickImg(urlList2,index)">
						</view>
					</view>
				</view>
				<view class="li wLi">
					<p><text class="required" v-if="obj.state != 'look'">*</text>描述：</p>
					<uni-easyinput type="textarea" autoHeight v-model="remark" placeholder="请输入任务描述(200字以内)"
						maxlength="200" v-if="obj.state != 'look'"></uni-easyinput>
					<text v-else>{{patrolRow.remark}}</text>
				</view>
			</view>
			<uni-popup ref="popup" type="dialog">
				<uni-popup-dialog type="error" confirmText="确定" title="通知" content="是否删除此条数据"
					@confirm="delConfirm"></uni-popup-dialog>
			</uni-popup>
			<view class="btnList">
				<van-button type="default" @click="cancel">取消</van-button>
				<van-button type="danger" v-if="obj.state == 'look'" @click="del">删除</van-button>
				<van-button type="info" v-if="obj.state == 'add' || obj.state == 'edit'" @click="save">保存</van-button>
				<van-button type="info" v-if="obj.state == 'look'" @click="toGo('edit')">编辑</van-button>
			</view>
		</view>
	</view>
</template>

<script>
	import sqlite from "../../common/sqlite.js"
	import api from "../../common/api.js";
	import {
		pathToBase64,
		base64ToPath
	} from '../../js_sdk/mmmm-image-tools/index.js'
	import {
		compressImgBySize
	} from '@/common/compressImg'
	import {
		v4 as uuidv4
	} from 'uuid';
	let that;
	export default {
		data() {
			return {
				title: "",
				vtpId: "",
				portObj: {},
				loginObj: {},
				shipInfo: {},
				obj: {},
				importExportName: "",
				spmTradeName: "",
				patrolRow: {},
				// 航次下拉框
				vvyId: "",
				vvyName: "",
				hcList: [],
				// 类型
				type: "",
				// 图片
				urlList: [],
				urlList2: [],
				delUrlList: [],
				// 描述
				remark: "",

				// 下拉数据
				optionData: [],
			}
		},
		onLoad(options) {
			if ('params' in options) {
				// 获取传递的对象参数，使用decodeURIComponent解码，并转为对象
				this.obj = JSON.parse(decodeURIComponent(options.params))
			}
		},
		mounted() {
			that = this
			this.portObj = uni.getStorageSync('portObj')
			this.loginObj = uni.getStorageSync('loginObj')
			this.vtpId = uni.getStorageSync('vtpId')
			this.executeSql1('shipOption')
			this.executeSql1("shipInfoTable")
			this.executeSql1("voyageScheduleDataDetailRespDTOList")
			if (this.obj.state == 'edit' || this.obj.state == 'look') {
				this.getRow();
			}
			if (this.obj.state == "edit") {
				this.title = "编辑安全巡检"
			} else if (this.obj.state == "look") {
				this.title = "查看安全巡检"
			} else {
				this.title = "新增安全巡检"
			}
		},
		methods: {
			// 查
			executeSql1(tableName) {
				let sql = `select * from ${tableName} WHERE vtpId = '${this.vtpId}'`
				sqlite.executeSqlCeshi(sql).then((value) => {
					// 在resolve时执行的回调函数
					if (tableName == 'shipOption') {
						this.optionData = value
						this.getShip()
					} else if (tableName == 'shipInfoTable') {
						this.shipInfo = value[0]
					} else if (tableName == 'voyageScheduleDataDetailRespDTOList') {
						this.vvyInfo = value
						this.hcList = []
						value.forEach((v, index) => {
							this.hcList.push({
								text: v.vvyName,
								value: v.vvyId
							})
						})
					}
				}).catch((error) => {
					// 在reject时执行的回调函数
					console.error(error);
				});
			},
			// 获取船只信息
			getShip() {
				// this.shipInfo = uni.getStorageSync('shipInfo')
				// 航次下拉数据
				let hcOption = []
				this.optionData.forEach((v, index) => {
					if (v.dictionariesName == 'vvyList') {
						hcOption.push(v)
					}
				})
				hcOption.forEach((v, index) => {
					this.hcList.push({
						text: v.ptrDesc,
						value: v.ptrCode
					})
				})
			},
			// 获取当前行信息
			getRow() {
				uni.request({
					url: `${this.$local}/api/safetyInspection/details/${this.obj.id}`,
					header: {
						'Content-Type': 'application/json', //自定义请求头信息
						'Authorization': `Bearer ${this.loginObj.access_token}`
					},
					method: 'GET', //请求方式，必须为大写
					success: (res) => {
						this.patrolRow = res.data.data
						this.vvyId = this.patrolRow.vvyId
						this.vvyName = this.patrolRow.vvyName
						this.importExportName = this.patrolRow.importExportName
						this.spmTradeName = this.patrolRow.tradeTypeName
						this.type = this.patrolRow.type
						this.remark = this.patrolRow.remark
						if (this.patrolRow.url != null) {
							this.urlList = this.patrolRow.url
						} else {
							this.urlList = []
						}
						if (this.patrolRow.url.length > 0 || this.patrolRow.url != null) {
							this.patrolRow.url.forEach(v => {
								this.initImg(v)
							})
						}
					},
					fail: (error) => {}
				})
			},
			initImg(fileName) {
				uni.request({
					url: `${this.$local}/api/file/url/?fileName=${fileName}`,
					header: {
						'Content-Type': 'application/json', //自定义请求头信息
						'Authorization': `Bearer ${this.loginObj.access_token}`
					},
					method: 'GET', //请求方式，必须为大写
					success: (res) => {
						if (res.statusCode == 200) {
							this.urlList2.push(res.data)
						}
					}
				})
			},
			// 航次下拉
			hcChange(e) {
				this.vvyId = e;
				this.hcList.forEach(v => {
					if (v.value == e) {
						this.vvyName = v.text
					}
				})
				this.vvyInfo.forEach(v => {
					if (v.vvyId == e) {
						this.importExportName = v.importExportFlagName
						this.spmTradeName = v.tradeTypeName
					}
				})
			},
			// 图片上传
			select(e) {
				uni.uploadFile({
					url: `${this.$local}/api/file/upload`, //上传图片api
					header: {
						'Authorization': `Bearer ${this.loginObj.access_token}`
					},
					filePath: e.tempFilePaths[0],
					name: 'file',
					success: (res) => {
						this.urlList2.push(e.tempFiles[0])
						let data = JSON.parse(res.data).data
						this.urlList.push(data.filePath)
					},
					fail(e) {
						uni.showToast({
							title: `${e.errMsg}`,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			// 移除图片
			delUrl(e) {
				let delIndex = 0
				this.urlList2.forEach((v, index) => {
					if (v.uuid == e.tempFile.uuid) {
						delIndex = index
					}
				})
				this.urlList.splice(delIndex, 1)
				this.urlList2.splice(delIndex, 1)
			},
			// 点击图片放大
			clickImg(urlList, index) {
				uni.previewImage({
					current: index,
					urls: urlList,
				})
			},
			// 取消
			cancel() {
				uni.navigateTo({
					url: '/pages/shipWork/patrol'
				})
			},
			// 弹框删除
			delConfirm() {
				uni.request({
					url: `${this.$local}/api/safetyInspection/${this.obj.id}`,
					header: {
						'Content-Type': 'application/json', //自定义请求头信息
						'Authorization': `Bearer ${this.loginObj.access_token}`
					},
					method: 'DELETE', //请求方式，必须为大写
					success: (res) => {
						console.log(res)
						if (res.statusCode == 200) {
							uni.navigateTo({
								url: '/pages/shipWork/patrol'
							})
						}
					},
					fail: () => {}
				})
			},
			// 删除
			del() {
				this.$refs.popup.open()
			},
			// 保存
			save() {
				let spmTradeName = ""
				if (this.spmTradeName == "内贸") {
					spmTradeName = "N"
				} else {
					spmTradeName = "W"
				}
				let importExportName = ""
				if (this.importExportName == "进口") {
					importExportName = "I"
				} else {
					importExportName = "E"
				}
				let dto = {
					"importExport": importExportName,
					"remark": this.remark,
					"spmId": this.vtpId,
					"tradeType": spmTradeName,
					"type": this.type,
					"uploadStatus": "",
					"url": this.urlList,
					"vsiId": this.obj.id,
					"vvyId": this.vvyId
				}
				if (this.obj.state == "add") {
					uni.request({
						url: `${this.$local}/api/safetyInspection`,
						data: dto,
						header: {
							'Content-Type': 'application/json', //自定义请求头信息
							'Authorization': `Bearer ${this.loginObj.access_token}`
						},
						method: 'POST', //请求方式，必须为大写
						success: (res) => {
							if (res.statusCode == 200) {
								uni.navigateTo({
									url: '/pages/shipWork/patrol'
								})
							}
						},
						fail: (e) => {
							console.log(e)
						}
					})
				} else if (this.obj.state == 'edit') {
					uni.request({
						url: `${this.$local}/api/safetyInspection/${this.obj.id}`,
						data: dto,
						header: {
							'Content-Type': 'application/json', //自定义请求头信息
							'Authorization': `Bearer ${this.loginObj.access_token}`
						},
						method: 'PUT', //请求方式，必须为大写
						success: (res) => {
							if (res.statusCode == 200) {
								uni.navigateTo({
									url: '/pages/shipWork/patrol'
								})
							}
						},
						fail: (e) => {
							console.log(e)
						}
					})
				}
			},
			// 编辑
			toGo(state) {
				this.obj.state = state;
				const params = encodeURIComponent(JSON.stringify(this.obj));
				uni.navigateTo({
					url: `/pages/shipWork/patrolAdd?params=${params}`
				})
			},
			executeSql(sql) {
				sqlite.executeSqlCeshi(sql).then((value) => {
					// 在resolve时执行的回调函数
					// console.log(value);
				}).catch((error) => {
					// 在reject时执行的回调函数
					console.error(error);
				});
			},
		}
	}
</script>

<style lang="less" scoped>
	.patrolAdd {
		.container {
			padding: 30px 20px;

			.ul {
				display: flex;
				flex-wrap: wrap;
				justify-content: space-between;

				.wLi {
					width: 100% !important;
				}

				.tpLi {
					width: 100% !important;
					display: block !important;

					p {
						text-align: left !important;
					}
				}

				.li {
					width: 44%;
					border-top: 1px solid #ccc;
					border-bottom: 1px solid #ccc;
					display: flex;
					padding: 10px 20px;
					line-height: 35px;
					margin-bottom: 20px;

					.required {
						color: red;
						margin-right: 5px;
					}

					p {
						min-width: 85px;
						text-align: right;
					}

					.picture {
						/deep/.file-picker__box {
							width: 120px !important;
							height: 120px !important;
							padding-top: 0;
						}
					}

					.pictureLook {
						display: flex;
						flex-wrap: wrap;

						image {
							width: 120px;
							height: 120px;
							margin: 10px;
						}
					}
				}
			}

			.btnList {
				display: flex;
				justify-content: center;

				/deep/ .van-button {
					margin: 30px 20px;
					width: 120px;
					height: 50px;
				}
			}
		}
	}
</style>