<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="check-items" v-for="(item, index) in list" :key="item.ID">
        <view class="title">设备名称:{{ item.EQUIP_TYPE_NAME }}</view>
        <view class="title">检查内容:{{ item.CHECK_ITEMS }}</view>
        <view class="title">检查标准:{{ item.CHECK_STANDARD }}</view>
        <view class="check-items-select">
          <radio-group class="block">
            <view class="flex justify-between padding-sm">
              <view class="select">
                <view @click="checkTrue(index, '1')" class="flex align-center">
                  <radio class='mr10' :class="item.CHECK_CONCLUSION === '1' ? 'checked' : ''" :checked="item.CHECK_CONCLUSION === '1'">
                  </radio>
                  <text>合格</text>
                </view>
              </view>
              <view class="select">
                <view @click="checkTrue(index, '2')" class="flex align-center">
                  <radio class='red mr10' :class="item.CHECK_CONCLUSION === '2' ? 'checked' : ''" :checked="item.CHECK_CONCLUSION === '2'">
                  </radio>
                  <text>不合格</text>
                </view>
              </view>
            </view>
          </radio-group>
        </view>
        <!-- 问题描述 -->
        <view class="cu-form-textarea margin-top">
          <view class="cu-form-title">问题描述</view>
          <textarea maxlength="-1" v-model="item.CHECK_DESCRIBE" placeholder="请对问题进行详细描述(必填项)"></textarea>
        </view>
        <!-- 上传图片 -->
        <view class="cu-form-textarea margin-top flex-box">
          <view class="action cu-form-title">上传图片</view>
          <view class="action">{{ item.imgList.length }}/1</view>
        </view>
        <view class="cu-form-group">
          <view class="grid col-4 grid-square flex-sub">
            <view class="bg-img" v-for="(img, imgIndex) in item.imgList" :key="imgIndex" @tap="viewImage(img.filePath)">
              <image :src="img.filePath" mode="aspectFill"></image>
              <view class="cu-tag bg-red" @tap.stop="delImg(index, imgIndex)">
                <text class='cuIcon-close'></text>
              </view>
            </view>
            <view class="solids" @tap.stop="chooseImage(index)" v-if="item.imgList.length < 1">
              <text class='cuIcon-cameraadd'></text>
            </view>
          </view>
        </view>
      </view>
      <view class="cu-tabbar-height"></view>
    </scroll-view>
    <view class="bottom-fixed" @tap.stop="goNext">
      <button :loading="buttonloading" class="cu-btn bg-green">下一步</button>
    </view>
    <yk-authpup ref="authpup" type="top" @changeAuth="$noMultipleClicks(save)"
      :permissionID="permissionID"></yk-authpup>
  </view>
</template>

<script>
import { basePath, loginUser, loginSession } from '@/common/tool.js';
import { baseImgPath } from '../../../common/tool'
import ykAuthpup from "@/components/yk-authpup/yk-authpup";

export default {
  components: { ykAuthpup },
  data() {
    return {
      baseImgPath: baseImgPath,
      permissionID: '',
      noClick: true,
      buttonloading: false,
      list: [],
      pd: [],
      CHECKRECORD_ID: '',
      CHECK_ID: '', // 接收的 CHECK_ID
      IDS: [], // 接收的 IDS
      currentIndex: 0, // 当前处理的 ID 索引
      equipType: '',
      currentID: '',
      RecordInfoId: '' // 新增用于接收 RecordInfoId
    };
  },
  onLoad(e) {
    this.CHECK_ID = e.CHECK_ID || ''; // 获取传递过来的 CHECK_ID
    this.IDS = e.IDS ? e.IDS.split(',') : []; // 获取传递过来的 IDS 并转换为数组
    this.equipType = e.equipType;
    this.currentID = e.currentID;
    this.RecordInfoId = e.RecordInfoId; // 获取传递过来的 RecordInfoId
    this.getData(e.currentID);
    loginSession();
  },
  onShow() {
    var _this = this;
    if (_this.initflag) {
      _this.initflag = false;
      _this.$forceUpdate(); // 强制刷新
    }
  },
  methods: {
    getData(id) { // 接受一个 ID 作为参数
      var _this = this;
      uni.showLoading({ title: '请稍候' });
      uni.request({
        url: basePath + '/app/recordItems/goEditStandards',
        method: 'POST',
        dataType: 'json',
        header: { 'Content-type': 'application/x-www-form-urlencoded' },
        data: {
          ID: id, // 使用传入的 ID
          USER_NAME: loginUser.NAME,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data.result === "success" && res.data.pd) {
            _this.pd = res.data.pd;
            // 将数据整理成列表
            _this.list = [{
              ID: _this.pd.ID,
              CHECK_ITEMS: _this.pd.CHECK_ITEMS,
              EQUIP_TYPE: _this.pd.EQUIP_TYPE,
              EQUIP_TYPE_NAME: _this.pd.EQUIP_TYPE_NAME,
              CHECK_STANDARD: _this.pd.CHECK_STANDARD,
              CHECK_CONCLUSION: '0', // 默认值
              CHECK_DESCRIBE: '', // 问题描述
              imgList: [] // 图片列表
            }];
            // 只有在成功获取数据后才调用 getDataByRecordInfoId
            if (_this.RecordInfoId) {
              _this.getDataByRecordInfoId(_this.RecordInfoId);
            }
          } else {
            _this.list = [];
            uni.showToast({
              icon: 'none',
              title: '没有数据',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            icon: 'none',
            title: '请求失败',
            duration: 2000
          });
          console.error(err);
        }
      });
    },
    getDataByRecordInfoId(RecordInfoId) { // 新建方法接受 RecordInfoId 作为参数
      let _this = this;
      uni.showLoading({ title: '请稍候' });
      uni.request({
        url: basePath + '/app/recordinfo/goEdit', // 调用对应接口
        method: 'POST',
        dataType: 'json',
        header: { 'Content-type': 'application/x-www-form-urlencoded' },
        data: {
          ID: RecordInfoId, // 使用传入的 RecordInfoId
          USER_NAME: loginUser.NAME,
          CORPINFO_ID: loginUser.CORPINFO_ID,
          USER_ID: loginUser.USER_ID,
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data.result === "success" && res.data.pd) {
            const { CHECK_CONCLUSION, CHECK_DESCRIBE, CHECK_PIC } = res.data.pd;
            if (_this.list.length > 0) {
              _this.list[0] = {
                ..._this.list[0],
                CHECK_CONCLUSION,
                CHECK_DESCRIBE: CHECK_DESCRIBE || "",
                imgList: CHECK_PIC ? [{
                  filePath: CHECK_PIC,
                  uid: new Date().getTime()
                }] : []
              };
            }
            _this.$forceUpdate();
          } else {
            _this.list = [];
            uni.showToast({
              icon: 'none',
              title: '没有数据',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({
            icon: 'none',
            title: '请求失败',
            duration: 2000
          });
          console.error(err);
        }
      });
    },
    goNext() {
      // 这里执行保存逻辑
      if (this.RecordInfoId === "") {
        this.save(() => {
            uni.navigateBack();
          });
      } else {
        // 这里执行编辑修改逻辑
        this.edit(this.RecordInfoId, () => {
          uni.navigateBack();
        });
      }
    },
    openAuth(permissionID) {
      this.permissionID = permissionID;
      setTimeout(() => {
        this.$refs['authpup'].open();
      }, 200);
    },
    save(callback) {
      var _this = this;
      var item = _this.list[0]; // 只处理第一个表单项

      // 校验必填项
      if (item.CHECK_CONCLUSION === '0') {
        uni.showToast({
          icon: 'none',
          title: '请选择合格/不合格',
          duration: 2000
        });
        return;
      }
      if (!item.CHECK_DESCRIBE) {
        uni.showToast({
          icon: 'none',
          title: '请填写问题描述',
          duration: 2000
        });
        return;
      }
      if (item.imgList.length === 0) {
        uni.showToast({
          icon: 'none',
          title: '请上传图片',
          duration: 2000
        });
        return;
      }

      var postData = {
        CHECK_DESCRIBE: item.CHECK_DESCRIBE, // 添加问题描述
        CHECK_ITEMS: item.CHECK_ITEMS, // 添加 CHECK_ITEMS
        CHECK_PIC: item.imgList.length > 0 ? item.imgList[0].filePath : '',
        CHECK_CONCLUSION: item.CHECK_CONCLUSION,
        LISTMANAGER_ID: _this.listId,
        LIST_NAME: _this.listName,
        CREATOR: loginUser.NAME,
        CHECKRECORD_ID: _this.CHECKRECORD_ID,
        CHECK_ID: _this.CHECK_ID, // 保存 CHECK_ID
        FINISHED: '1',
        tm: new Date().getTime(),
        CORPINFO_ID: loginUser.CORPINFO_ID,
        USER_ID: loginUser.USER_ID
      };
      _this.buttonloading = true;
      uni.request({
        url: basePath + '/app/recordinfo/add',
        xhrFields: { withCredentials: true },
        method: 'POST',
        dataType: 'json',
        header: { 'Content-type': 'application/x-www-form-urlencoded' },
        data: postData,
        success: function (res) {
          _this.buttonloading = false;
          if (res.data.result === "success") {
            uni.showToast({
              icon: 'none',
              title: '提交成功',
              duration: 1500
            });
            if (typeof callback === 'function') {
              callback();
            }
          } else {
            uni.showToast({
              title: "系统错误",
              duration: 2000
            });
          }
        },
        fail: function (err) {
          _this.buttonloading = false;
          uni.showToast({
            title: "提交失败",
            duration: 2000
          });
          console.error(err);
        }
      });
    },
    /** 编辑修改 */
    edit(ID, callback) {
      var _this = this;
      var item = _this.list[0]; // 只处理第一个表单项
      // 校验必填项
      if (item.CHECK_CONCLUSION === '0') {
        uni.showToast({
          icon: 'none',
          title: '请选择合格/不合格',
          duration: 2000
        });
        return;
      }
      if (!item.CHECK_DESCRIBE) {
        uni.showToast({
          icon: 'none',
          title: '请填写问题描述',
          duration: 2000
        });
        return;
      }
      if (item.imgList.length === 0) {
        uni.showToast({
          icon: 'none',
          title: '请上传图片',
          duration: 2000
        });
        return;
      }
      var postData = {
        CHECK_DESCRIBE: item.CHECK_DESCRIBE, // 添加问题描述
        CHECK_PIC: item.imgList.length > 0 ? item.imgList[0].filePath : '',
        CHECK_CONCLUSION: item.CHECK_CONCLUSION,
        ID
      };
      _this.buttonloading = true;
      uni.request({
        url: basePath + '/app/recordinfo/edit',
        xhrFields: { withCredentials: true },
        method: 'POST',
        dataType: 'json',
        header: { 'Content-type': 'application/x-www-form-urlencoded' },
        data: postData,
        success: function (res) {
          _this.buttonloading = false;
          if (res.data.result === "success") {
            uni.showToast({
              icon: 'none',
              title: '提交成功',
              duration: 1500
            });
            if (typeof callback === 'function') {
              callback();
            }
          } else {
            uni.showToast({
              title: "系统错误",
              duration: 2000
            });
          }
        },
        fail: function (err) {
          _this.buttonloading = false;
          uni.showToast({
            title: "提交失败",
            duration: 2000
          });
          console.error(err);
        }
      });
    },
    checkTrue(index, STATUS) {
      this.list[index].CHECK_CONCLUSION = STATUS;
      this.$forceUpdate(); // 强制刷新
    },
    chooseImage(index) {
      var _this = this;
      uni.chooseImage({
        count: 1, // 只允许选择一张图片
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera', 'album'], // 从相册选择
        success: (res) => {
          // 选择图片后立即上传
          _this.uploadImg(res.tempFilePaths[0], index);
        }
      });
    },
    uploadImg(filePath, index) {
      var _this = this;
      uni.showLoading({
        title: '上传中'
      });
      let foreignKey = `${_this.CHECK_ID}-${_this.list[index].EQUIP_TYPE}`;
      uni.uploadFile({
        url: basePath + '/app/imgfiles/add',
        filePath: filePath,
        name: 'FFILE',
        formData: {
          'TYPE': 27,
          'FOREIGN_KEY': foreignKey
        },
        success: (res) => {
          uni.hideLoading();
          let data = JSON.parse(res.data);
          if (data.result === 'success') {
            let img = {
              id: data.id,
              filePath: _this.baseImgPath + data.pd.FILEPATH
            };
            // 将上传成功的图片添加到列表中
            _this.list[index].imgList = [img];
            _this.$forceUpdate();
          } else {
            uni.showToast({
              icon: 'none',
              title: '上传失败',
              duration: 2000
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showModal({
            content: err.errMsg,
            showCancel: false
          });
        }
      });
    },
    viewImage(filePath) {
      uni.previewImage({
        urls: [filePath], // 需要预览的图片链接列表
        current: filePath // 当前显示图片的链接
      });
    },
    delImg(itemIndex, imgIndex) {
      var _this = this;
      uni.showModal({
        title: '',
        content: '确定要删除这张图片吗？',
        cancelColor: "#000000",
        cancelText: '取消',
        confirmText: '确定',
        success: res => {
          if (res.confirm) {
            _this.list[itemIndex].imgList.splice(imgIndex, 1);
            _this.$forceUpdate();
          }
        }
      });
    }
  }
}
</script>

<style>
.select radio {
  transform: scale(0.9);
}

.cu-form-title {
  padding: 20 upx 0;
}

.cu-form-title:before {
  content: '*';
  color: red;
  vertical-align: sub;
  margin-right: 5px;
}

.flex-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.cu-form-textarea {
  background-color: #ffffff;
  border-bottom: none; 
  min-height: 100upx;
}

.cu-form-textarea textarea {
  height: 4.6em;
  width: 100%;
  line-height: 1.2em;
  flex: 1;
  font-size: 28upx;
  padding: 0;
}
</style>
