<template>
	<view>
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">安全例会详情</block>
		</cu-custom>
		<scroll-view scroll-y>
			<view class="dy-card">
				<view class="dy-card-title">
					<text>{{pd.MEETING_TITLE}}</text>
				</view>
				<view class="dy-card-content">
					<view class="dy-card-content-item">
						<text>主持人:</text>
            <text>{{pd.HOST_PERSON}}</text>
					</view>
          <view class="dy-card-content-item">
            <text>记录人:</text>
            <text>{{pd.RECORDER}}</text>
          </view>
          <view class="dy-card-content-item">
            <text>会议开始时间:</text>
            <text>{{pd.MEETING_DATE_START}}</text>
          </view>
          <view class="dy-card-content-item">
            <text>会议结束时间:</text>
            <text>{{pd.MEETING_DATE_END}}</text>
          </view>
          <view class="dy-card-content-item">
            <text>会议类型:</text>
            <text>{{pd.MEETING_TYPE === '1' ? '安全生产例会' : pd.MEETING_TYPE === '2' ? '安全生产委员会会议' : ''}}</text>
          </view>
          <view class="dy-card-content-item">
            <text>会议内容:</text>
            <rich-text :nodes="pd.MEETING_CONTENT"></rich-text>
          </view>
				</view>
			</view>
			<view class="cu-tabbar-height"></view>
		</scroll-view>
    <canvas style="width: 300px; height: 150px; position: absolute; top: -9999px;" canvas-id="watermarkCanvas"></canvas>
    <uni-drawer ref="showHiddenWindow" mode="right" :mask-click="true">
      <scroll-view scroll-y="true" style="height: 100vh;">
        <view class="de-drawer">
          <view class="cu-bar bg-white">
            <view class="action">实时照片</view>
          </view>
          <view class="cu-form-group">
            <view class="grid col-4 grid-square flex-sub">
              <view class="bg-img" v-if="liveImgs.length > 0"
                    :data-url="liveImgs[0].FILEPATH">
                <image :src="liveImgs[0].IMGFILES_ID ? (baseImgPath + liveImgs[0].FILEPATH) : liveImgs[0].FILEPATH" mode="aspectFill"></image>
                <!-- 删除图片按钮 -->
                <view class="cu-tag bg-red" @tap.stop="DelImg" data-type="0">
                  <text class='cuIcon-close'></text>
                </view>
              </view>
              <!-- 上传图片按钮,仅当没有图片时显示 -->
              <view class="solids" @tap="ChooseImage"
                    v-if="liveImgs.length === 0">
                <text class='cuIcon-cameraadd'></text>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-form-group" style="border: none;">
          <view class="title">签字</view>
          <button class="cu-btn bg-green shadow" @tap="modalShow = true" data-target="Modal">手写签字</button>
        </view>
        <view class="cu-bar bg-white" v-show="signImgList && signImgList.length > 0">
          <view class="action">
            签字照片
          </view>
        </view>
        <view class="cu-form-group" v-show="signImgList && signImgList.length > 0">
          <view class="grid col-4 grid-square flex-sub">
            <view style="width: 60%;" class="bg-img" v-for="(item,index) in signImgList" :key="index" @tap="ViewImage" data-type="0" :data-url="signImgList[index].filePath">
              <image :src="signImgList[index].filePath" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="delImg" data-type="0" :data-index="index">
                <text class='cuIcon-close'></text>
              </view>
            </view>
          </view>
        </view>
        <view class="cu-modal" :class="{'show':modalShow}">
          <sign @confirm="subCanvas" @cancel="modalShow = false"></sign>
        </view>
        <view class="cu-form-group" style="margin-top: 20px; ">
          <button class="cu-btn block bg-blue margin-tb-sm" @click="submitMeetingAttendance('ACCESS_FINE_LOCATION')">提交当前位置</button>
        </view>
        <yk-authpup ref="authpup" type="top" @changeAuth="$noMultipleClicks(editLocation)" :permissionID="permissionID"></yk-authpup>
      </scroll-view>
    </uni-drawer>
    <view class="cu-form-group" v-if="pd.ATTENDANCE_STATUS === '0'">
      <view class="title">是否参会:</view>
      <button class="cu-btn round bg-blue" @click="addMeeting">参会</button>
    </view>
	</view>
</template>

<script>
	import {
		basePath,loginUser
	} from '@/common/tool.js';
  import sign from '@/components/sign/sign.vue';
  import ykAuthpup from "@/components/yk-authpup/yk-authpup"
  import {baseImgPath} from "../../../common/tool";
	export default {
    components: {
      sign,
      ykAuthpup
    },
		data() {
			return {
        baseImgPath: baseImgPath,
        modalShow: false,
        permissionID:'',
        SAFETY_MEETING_ID : '',
				varList:[],
				pd:[],
				noClick:true,
				ACCIDENTS_NAME:"",
        MEETING_TITLE:"",
        MEETING_TYPE:"",
        MEETING_ADDRESS:"",
        HOST_PERSON:"",
        MEETING_CONTENT:"",
        RECORDER:"",
        MEETING_DATE_START:"",
        MEETING_DATE_END:"",
        liveImgs: [],
        signImgList: [],
        LIVEPHOTOS: '',
        SIGNATUREPICTURE: '',
        ATTENDANCE_STATUS: '',
			}
		},
		onLoad(e){
			var _this = this;
			_this.SAFETY_MEETING_ID=e.id;
			_this.getData();

		},
		methods: {
			//跳转事件
			goToEdit(e) {
				uni.navigateTo({
					url: '/pages/application/basic-info-manage/basic-information/basic-information-edit'
				});
			},
			getData() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/safetymeeting/goEdit',
					method: 'POST',
					dataType: 'json',
					header:{
							'Content-type':'application/x-www-form-urlencoded'
					},
					data: {
            SAFETY_MEETING_ID: _this.SAFETY_MEETING_ID,
            USER_ID:loginUser.USER_ID,
					},
					success: (res) => {
						if (res.data != null) {
							uni.hideLoading();
              _this.pd = res.data.pd;
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},
      ChooseImage() {
        var _this = this;
        uni.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['camera'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            uni.getLocation({
              type: 'gcj02',
              geocode: true,
              success: function (locationRes) {
                const locationAddress = `${locationRes.address.province}${locationRes.address.city}${locationRes.address.district}${locationRes.address.street}${locationRes.address.streetNum}${locationRes.address.poiName}`;
                // 创建画布
                const ctx = uni.createCanvasContext('watermarkCanvas', _this);
                ctx.drawImage(tempFilePath, 0, 0, 300, 150); // 图片大小
                ctx.setFontSize(20); // 水印字体大小
                ctx.setFillStyle('red'); // 水印字体颜色
                ctx.setFontSize(10); // 调整字体大小,适应位置信息
                // 绘制水印
                ctx.fillText(`用户名: ${loginUser.NAME}`, 10, 120); // 根据实际情况调整位置
                ctx.fillText(`当前位置: ${locationAddress}`, 10, 130); // 根据实际情况调整位置
                // 获取并格式化当前时间
                const now = new Date();
                const formattedTime = `${now.getFullYear()}-${now.getMonth()+1}-${now.getDate()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
                ctx.fillText(`当前时间: ${formattedTime}`, 10, 140); // 绘制时间水印
                ctx.draw(false, () => {
                  // 将画布内容保存为图片
                  uni.canvasToTempFilePath({
                    canvasId: 'watermarkCanvas',
                    success: function(res) {
                      let img = {
                        IMGFILES_ID: '',
                        FILEPATH: res.tempFilePath // 使用带有水印的图片路径
                      };
                      _this.liveImgs = [img];
                      _this.uploadFilePromise(img.FILEPATH, 'livePhoto', locationAddress)
                          .then(() => {
                            uni.showToast({
                              title: '实时照片上传成功',
                              icon: 'success'
                            });
                          }).catch(error => {
                        uni.showToast({
                          title: '实时照片上传失败: ' + error,
                          icon: 'none'
                        });
                      });
                    }
                  }, _this);
                });
              },
              fail: function () {
                uni.showToast({
                  title: '获取位置信息失败',
                  icon: 'none'
                });
              }
            });
          }
        });
      },

      DelImg() {
        var _this = this;
        uni.showModal({
          content: '确定要删除这张图片吗?',
          cancelColor: "#000000",
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              _this.liveImgs = [];
            }
          }
        })
      },
      subCanvas (e) {
        this.signImgList.splice(0, this.signImgList.length);
        this.signImgList.push(e);
        this.SIGNATUREPICTURE = e.filePath;
        this.modalShow = false;
      },
      delImg (e) {
        var _this = this;
        let i = e.currentTarget.dataset.index
        uni.showModal({
          content: '确定要删除这张图片吗?',
          cancelColor: "#000000",
          cancelText: '取消',
          confirmText: '确定',
          success: res => {
            if (res.confirm) {
              _this.signImgList.splice(i, 1)
            }
          }
        })
      },
      submitMeetingAttendance(permissionID) {
        var _this = this;
        if (this.signImgList.length === 0) {
          uni.showToast({
            title: '请上传签字图片',
            icon: 'none'
          });
          return;
        }
        this.permissionID = permissionID;
        uni.getLocation({
          type: 'gcj02',
          geocode: true,
          success: function (res) {
            const locationAddress = `${res.address.province}${res.address.city}${res.address.district}${res.address.street}${res.address.streetNum}${res.address.poiName}`;
            _this.longitude = res.longitude;
            _this.latitude = res.latitude;
            // 循环上传签字图片
            const uploadTasks = [];
            _this.signImgList.forEach(signImg => {
              uploadTasks.push(_this.uploadFilePromise(signImg.filePath, 'signPhoto', locationAddress));
            });
            Promise.all(uploadTasks).then(() => {
              // 所有图片上传完成后的处理
              uni.showToast({
                title: '全部上传成功',
                icon: 'success'
              });
              // 重新加载或更新页面数据等
              _this.getData();
              _this.$refs.showHiddenWindow.close();
            }).catch(error => {
              uni.showToast({
                title: '上传出错: ' + error,
                icon: 'none'
              });
            });
          },
          fail: function () {
            uni.showToast({
              title: '获取位置信息失败',
              icon: 'none'
            });
          }
        });
      },
      uploadFilePromise(filePath, name, locationAddress) {
        return new Promise((resolve, reject) => {
          uni.uploadFile({
            url: basePath + '/app/safetymeeting/edit',
            filePath: filePath,
            name: name,
            formData: {
              SAFETY_MEETING_ID: this.SAFETY_MEETING_ID,
              ATTENDANCE_STATUS: '1',
              LATITUDE: this.latitude,
              LONGITUDE: this.longitude,
              LOCATIONADDRESS: locationAddress
            },
            success: uploadRes => {
              const data = JSON.parse(uploadRes.data);
              if (data.result === 'success') {
                resolve(data);
              } else {
                reject(data.message);
              }
            },
            fail: () => {
              reject('上传失败');
            }
          });
        });
      },
      // 封装一个上传数据的函数,包括位置信息、实时照片和签字图片
      // formData(latitude, longitude) {
      //   uni.showLoading({
      //     title: '提交中...'
      //   });
      //   const livePhotoPath =baseImgPath + this.liveImgs[0].FILEPATH;
      //   const signPhotoPath = this.signImgList[0].filePath;
      //
      //   uni.uploadFile({
      //     url: basePath + '/app/safetymeeting/edit',
      //     filePath: livePhotoPath,
      //     name: 'livePhoto',
      //     formData: {
      //       SAFETY_MEETING_ID: this.SAFETY_MEETING_ID,
      //       SIGNATUREPICTURE: this.SIGNATUREPICTURE,
      //       ATTENDANCE_STATUS: '1',
      //     },
      //     success: uploadRes => {
      //       const data = JSON.parse(uploadRes.data);
      //       uni.hideLoading();
      //       if (data.result === 'success') {
      //         uni.showToast({
      //           title: '提交成功',
      //           icon: 'success'
      //         });
      //         this.$refs.showHiddenWindow.close();
      //       } else {
      //         uni.showToast({
      //           title: '提交失败: ' + data.message,
      //           icon: 'none'
      //         });
      //       }
      //     },
      //     fail: () => {
      //       uni.hideLoading();
      //       uni.showToast({
      //         title: '上传失败',
      //         icon: 'none'
      //       });
      //     }
      //   });
      // },
      addMeeting() {
        if (this.$refs.showHiddenWindow) {
          // 清空实时照片和签字图片数组
          this.liveImgs = [];
          this.signImgList = [];
          this.$refs.showHiddenWindow.open();
        }
        this.creatorList = [{
          NAME: loginUser.NAME,
          USER_ID: loginUser.USER_ID
        }]
        this.$refs['showHiddenWindow'].open()
        this.showHiddenWindow = true
        this.hiddenIsEdit = true
      },

      openAuth(permissionID){
        this.permissionID = permissionID;
        setTimeout(()=>{
          this.$refs['authpup'].open();
        },200)
      },
		}
	}
</script>

<style>
.dy-card {
  background-color: #fff;
  border-radius: 10upx;
  margin: 30upx;
}

.dy-card-title {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
  min-height: 80upx;
  line-height: 80upx;
  padding: 0 30upx;
}

.dy-card-content {
  padding: 0upx 30upx 30upx;
}

.dy-card-content-item {
  margin-top: 10upx;
}

.dy-card-content-item .title {
  display: flex;
  align-items: center;
}

/* 注释掉未使用的样式 */
/* .dy-card-content-item .title .l {
  width: 10upx;
  height: 30upx;
  border-radius: 20upx;
  background-color: #666;
  margin-right: 10upx;
} */

.dy-card-content-item .content,
.dy-card-content-item .name text {
  background-color: #F1F1F1;
  padding: 10upx 14upx;
  margin-top: 14upx;
  line-height: 1.6;
  display: inline-block; /* 如果需要显示为inline-block */
}

.delete-icon text {
  color: white; /* 图标颜色为白色 */
  font-size: 14px; /* 图标大小,根据需要调整 */
}

</style>