<template>
  <view class="project-add">
    <!-- 项目新增表单卡片 -->
    <view class="cc-card form-card">
      <view class="form-title">{{ pageTitle }}</view>

      <view class="form-item">
        <text class="form-label">隐患名称</text>
        <view class="form-content">
          <input v-model="form.hazardName" class="form-input" placeholder="请输入隐患名称" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">项目名称</text>
        <view class="form-content">
          <input v-model="form.entryName" class="form-input" placeholder="请输入项目名称" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">排查计划</text>
        <view class="form-content">
          <input v-model="form.investigationPlan" class="form-input" placeholder="请输入排查计划" type="number" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">检查单位</text>
        <view class="form-content">
          <input v-model="form.inspectionUnit" class="form-input" placeholder="请输入检查单位" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">检查责任人</text>
        <view class="form-content">
          <input v-model="form.personCgeInspection" class="form-input" placeholder="请输入检查责任人" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">检查周期</text>
        <view class="form-content">
          <input v-model="form.inspectionCycle" class="form-input" placeholder="请输入检查周期" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">检查人列表信息</text>
        <view class="form-content">
          <input v-model="form.checkerListInfo" class="form-input" placeholder="请输入检查人列表信息" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">隐患描述</text>
        <view class="form-content">
          <input v-model="form.hazardDescription" class="form-input" placeholder="请输入隐患描述" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">隐患所在区域</text>
        <view class="form-content">
          <input v-model="form.hazardLocationArea" class="form-input" placeholder="请输入隐患所在区域" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">隐患类型</text>
        <view class="form-content">
          <input v-model="form.hazardType" class="form-input" placeholder="请输入隐患类型" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">隐患等级</text>
        <view class="form-content">
          <input v-model="form.hazardLevel" class="form-input" placeholder="请输入隐患等级" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">整改期限</text>
        <view class="form-content">
          <input v-model="form.rectificationDeadline" class="form-input" placeholder="请输入整改期限" />
        </view>
      </view>

      <view class="form-item">
        <text class="form-label">整改责任单位</text>
        <view class="form-content">
          <input v-model="form.rectificationResponsibleUnit" class="form-input" placeholder="请输入整改责任单位" />
        </view>
      </view>
    </view>

    <view class="cc-form-card" style="margin-top: 16px;margin-bottom: 16px;">
      <view class="form-title">
        <view>图片</view>
        <view class="form-tips">支持png、jpg等格式，不大于5M</view>
      </view>

      <view class="form-item" style="margin-bottom: 0;">
        <div class="img-box">
          <div class="img-list">
            <div
              v-for="(item, index) in imgPreviewList"
              :key="index"
              class="img-item"
            >
              <image :src="item" @click="previewImage(index)" />
              <button class="delete-btn" @click="deleteImage(index)">删除</button>
            </div>
            <div class="file-select" @click="chooseAttachment"></div>
          </div>
        </div>
      </view>
    </view>

    <view class="cc-operation-row operation-row">
      <view class="buttons-group">
        <view class="button primary-button" @click="handleConfirm">确定</view>
        <view class="button default-button" @click="handleCancle">取消</view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  listRecord,
  getRecord,
  addRecord,
  updateRecord,
  delRecord,
  exportRecord,
} from "@/api/system/hazardRecord";
import {baseUrl} from "@/config";
import {getToken} from "@/utils/auth";
export default {
  data() {
    return {
      form: {
        id: this.$route.query.monitorId,
        hazardName: '',
        entryName: '',
        investigationPlan: '',
        inspectionUnit: '',
        personCgeInspection: '',
        inspectionCycle: '',
        checkerListInfo: '',
        hazardDescription: '',
        hazardType: '',
        hazardLevel: '',
        rectificationDeadline: '',
        rectificationResponsibleUnit: '',
        hazardAttachment: '',
        proNo: this.$route.query.proNo
      },
      pageTitle: '添加隐患登记信息',
      imagePath: '', // 用于存储选中的图片路径
      proNo: this.$route.query.proNo,
      proCode: this.$route.query.proCode,
      projectName: this.$route.query.projectName,
      headers: {
        jianwei: "jwtech " + getToken(),
      },
      imgList: [],
      imgPreviewList: [],
      // imgPreviewList: ["http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960", "http://gips1.baidu.com/it/u=3874647369,3220417986&fm=3028&app=3028&f=JPEG&fmt=auto?w=720&h=1280"]
    };
  },
  created () {
    this.handleJudgeTitle()
    this.getDetailInfo()
  },
  methods: {
    // 处理标题名称
    handleJudgeTitle() {
      let operateType = this.$route.query.operateType
      if (operateType === 'add') {
        this.pageTitle = '添加隐患登记信息'
      } else {
        this.pageTitle = '编辑隐患登记信息'
      }
    },
    
    getDetailInfo() {
      if (this.form.id) {
        getRecord(this.form.id).then(res => {
          if (res.data.hazardAttachment) {
            this.imgList = JSON.parse(res.data.hazardAttachment)
            this.imgPreviewList = this.imgList.map(item => {
              item.url
            })
          }
          this.form = res.data
        })
      }
    },

    handleConfirm() {
      if (!this.judgeAttrWrite()) {
        return
      }
      uni.showLoading({
        title: '提交中...',
        mask: true
      })
      if (this.imgList && this.imgList.length>0) {
        this.form.hazardAttachment = JSON.stringify(this.imgList)
      }
      if (this.form.id) {
        updateRecord(this.form).then(res => {
          uni.showToast({
            title: '提交成功',
            icon: 'none'
          })
          this.$tab.redirectTo(`/pages/danger/list?operateType=add&proNo=${this.proNo}&proCode=${this.proCode}&menuType=${0}&projectName=${this.projectName}`)
          // uni.navigateTo({
          //   url: '/pages/danger/list?tabNum=1&id=' + this.$route.query.id + '&proNo='
          // })
          uni.hideLoading()
        })
      } else {
        addRecord(this.form).then(res => {
          uni.showToast({
            title: '提交成功',
            icon: 'none'
          })
          uni.hideLoading()
          // uni.navigateTo({
          //   url: '/pages/danger/list?tabNum=1&id=' + this.$route.query.id
          // })
          this.$tab.redirectTo(`/pages/danger/list?operateType=add&proNo=${this.proNo}&proCode=${this.proCode}&menuType=${0}&projectName=${this.projectName}`)
        })
      }
    },

    handleCancle() {
      uni.navigateBack()
    },

    // 判断必填项是否填写
    judgeAttrWrite() {
      const form = this.form
      if (!form.hazardName) {
        uni.showToast({
          title: `隐患名称不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.entryName) {
        uni.showToast({
          title: `项目名称不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.investigationPlan) {
        uni.showToast({
          title: `排查计划不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.inspectionUnit) {
        uni.showToast({
          title: `检查单位不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.personCgeInspection) {
        uni.showToast({
          title: `检查责任人不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.inspectionCycle) {
        uni.showToast({
          title: `检查周期不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.checkerListInfo) {
        uni.showToast({
          title: `检查人列表信息不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.hazardDescription) {
        uni.showToast({
          title: `隐患描述不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.hazardLocationArea) {
        uni.showToast({
          title: `隐患所在区域不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.hazardType) {
        uni.showToast({
          title: `隐患类型不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.hazardLevel) {
        uni.showToast({
          title: `隐患等级不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.rectificationDeadline) {
        uni.showToast({
          title: `整改期限不能为空！`,
          icon: 'none'
        })
        return false
      }
      if (!form.rectificationResponsibleUnit) {
        uni.showToast({
          title: `整改责任单位不能为空！`,
          icon: 'none'
        })
        return false
      }
      return true
    },

    // 选择上传附件
    chooseAttachment() {
      uni.showActionSheet({
        itemList: ['照相机', '图册'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // 选择拍照
            this.takePhoto();
          } else if (res.tapIndex === 1) {
            // 选择从相册选择
            this.chooseFromGallery();
          }
        },
        fail: (err) => {
          console.log('选择附件失败', err);
        }
      });
    },

    // 拍照
    takePhoto() {
      uni.chooseImage({
        count: 1, // 选择1张图片
        sourceType: ['camera'], // 仅允许拍照
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const fileName = res.tempFiles[0].name
          this.uploadFile(tempFilePath, fileName); // 上传文件
        },
        fail: (err) => {
          console.log('拍照失败', err);
        }
      });
    },

    // 从相册选择
    chooseFromGallery() {
      uni.chooseImage({
        count: 1, // 选择1张图片
        sourceType: ['album'], // 仅允许从相册选择
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          const fileName = res.tempFiles[0].name
          this.uploadFile(tempFilePath, fileName); // 上传文件
        },
        fail: (err) => {
          console.log('从相册选择失败', err);
        }
      });
    },

    // 上传文件
    uploadFile(filePath, fileName) {
      console.log('上传成功', fileName)
      let token="jwtech " + getToken()
      // 替换为你的后端接口地址
      const uploadUrl = baseUrl+'/common/upload';
      uni.uploadFile({
        header: {
          'jianwei':token,
        },
        url: uploadUrl, // 你的服务器上传接口
        filePath: filePath,
        name: 'file',
        success: (uploadFileRes) => {
          let imageItem = JSON.parse(uploadFileRes.data)
          // 将选择的图片添加到 imageList
          imageItem.name = fileName
          this.imgList.push(imageItem)
          this.imgPreviewList.push(imageItem.url)
          console.log('上传成功', this.imgPreviewList)
          // 你可以在这里处理返回的数据
        },
        fail: (uploadFileErr) => {
          console.log('上传失败', uploadFileErr);
        }
      });
    },

    // 图片放大查看
    previewImage(index) {
      uni.previewImage({
        current: index, // 当前显示的图片索引
        urls: this.imgPreviewList // 图片列表
      });
    },

    // 删除图片
    deleteImage(index) {
      this.imgPreviewList.splice(index, 1);
      this.imgList.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.project-add {
  padding: 16px 20px 80px;
  .file-select {
    width: 72px;
    height: 72px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e7e7e7;
    border-radius: 4px;
    font-size: 0;
    uni-button {
      display: none;
    }
    &::after {
      content: '+';
      font-size: 38px;
      color: #00B39D;
    }
  }
  .img-box {
    .img-list {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .img-item {
        position: relative;
        image {
          width: 72px;
          // width: calc(calc(100% - 30px) / 4);
          height: 72px;
          border: 1px solid #e7e7e7;
        }
        .delete-btn {
          position: absolute;
          top: 5px;
          right: 5px;
          background-color: #3b3838;
          font-size: 12px;
          color: white;
          border: none;
          padding: 0 2px;
          border-radius: 50%;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
