<template>
  <view class="main">
    <div class="pageHeader">
      <div class="hederContent">
        <img :src="user.Membership_Headimage" alt="" />
        <div>
          <p>{{ user.Membership_Name || "" }}</p>
          <p class="fs12">巡查人员</p>
        </div>
      </div>
    </div>

    <div class="addressBox">
      <div class="contentBox">
        <image
          src="/static/images/publicity/dingwei.png"
          mode="aspectFit"
          class="addressIcon"
        ></image>
        <div>
          <p class="xuncha address">{{ detailObj.title || "-" }}</p>
          <div>
            <span>巡查时间：</span><span>{{ now_time }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="formBox">
      <ul>
        <li>
          <span
            :class="
              inputfocus
                ? 'circle circleActive circle-first '
                : 'circle circle-first'
            "
          ></span>
          <div class="examineContent">
            <div class="titleBox">
              <i :class="inputfocus ? 'img-zds activezds' : 'img-zds'"></i>
              <div
                :class="inputfocus ? 'titleTextActive' : 'titleText'"
                style="display: flex"
              >
                <i style="color: red; margin-right: 5px">*</i>巡查内容
              </div>
            </div>

            <div class="inputBox">
              <textarea
                auto-height
                v-model="uploadResult"
                placeholder="请输入巡查内容"
                focus="true"
                @focus="inputfocus = true"
                @blur="inputfocus = false"
              ></textarea>
            </div>

            <div class="tagList" v-for="(tags, i) in tagList" :key="i">
              <div class="tagName">
                <span
                  style="display: inline-block; max-width: calc(100% - 10rpx)"
                >
                  {{ tags.question.title || "" }}
                </span>
                <span v-if="tags.isRequired" style="color: red">*</span>
              </div>
              <div class="tagsBox">
                <div
                  v-for="(tag, s) in tags.question.options"
                  :key="s"
                  @tap="selectTag(tag, tags.question)"
                  :class="tag.ischecked ? 'tagUnit active ' : 'tagUnit'"
                >
                  {{ tag.text }}
                </div>
              </div>
            </div>
          </div>
        </li>

        <li>
          <span :class="imgfocus ? 'circleActive' : 'circle'"></span>
          <div class="examineContent">
            <div class="titleBox">
              <i
                :class="imgfocus ? 'img-upload activeupload' : 'img-upload'"
              ></i>
              <div
                style="display: flex"
                :class="imgfocus ? 'titleTextActive' : 'titleText'"
              >
                <i style="color: red; margin-right: 5px">*</i>请上传现场图片
              </div>
            </div>
            <div class="uploadBox">
              <div
                class="uploadList"
                v-for="(item, index) in imgsList"
                :key="index"
              >
                <span
                  class="upload-file-remove"
                  @click.stop="deleteImgFunc(item, index)"
                  >×</span
                >
                <image :src="item" @tap="showImg2(index)" mode="aspectFill" />
              </div>
              <div class="uploadAdd" @click="submitImg">
                <div class="upload-file-add-container">
                  <span class="walk-manage-plus">+</span>
                </div>
              </div>
            </div>
          </div>
        </li>

        <li>
          <span
            :class="
              radiofocus
                ? 'circle circleActive circle-last'
                : 'circle circle-last'
            "
          >
          </span>
          <div class="examineContent">
            <radio-group
              @change="radioChange"
              style="display: flex"
              @click="radioFocus"
              @blur="radiofocus = false"
            >
              <label
                class="uni-list-cell"
                v-for="(item, index) in options"
                :key="item.value"
              >
                <view>
                  <radio
                    :value="item.value"
                    color="#409eff"
                    :checked="index === current"
                    style="transform: scale(0.8)"
                  />
                </view>
                <view>{{ item.name }}</view>
              </label>
            </radio-group>
          </div>
        </li>
      </ul>

      <button v-if="!submit" class="btn" @click="submitUpload">提交</button>
    </div>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
  data() {
    let nowTime = this.$util.cutDate(new Date(), "hh:mm:ss");
    return {
      now_time: nowTime,
      inputfocus: true, // 是否聚焦
      uploadResult: "", // 巡查内容
      tagList: [], // 当前显示的巡查内容
      imgfocus: false, // 是否聚焦图片
      radiofocus: false, // 类型的聚焦
      options: [
        {
          name: "情况正常",
          value: "0",
        },
        {
          name: "急需处理",
          value: "1",
        },
      ],
      value: "0",
      current: 0,
      selectAnwersList: [], // 选择的答案列表
      selectAnwersObj: {}, // 已经选择答案的实际对象格式  问题的id: [选项1，选项2]
      detailObj: {}, //点位详情
      imgsList: [],
      submit: false, // 是否提交成功了
      requiredList: [], // 必填项的数组
    };
  },
  computed: {
    ...mapGetters({
      user: "getUser",
    }),
  },
  onLoad(query) {
    this.handleGetModalData(query.id);
  },
  methods: {
 
    // 删除图片
    deleteImgFunc(item, index) {
      this.imgsList.splice(index, 1);
    },
    // 提交表单内容
    async submitUpload() {
      console.log("user", this.user);
      console.log("this.detailObj", this.detailObj);

      if (!this.uploadResult) {
        uni.showToast({
          title: "请输入巡查内容！",
          icon: "none",
        });
        return;
      }
      console.log("selectAnwersList", this.selectAnwersList);
      console.log("selectAnwersObj", this.selectAnwersObj);
      console.log("requiredList", this.requiredList);

      if (this.selectAnwersList && this.selectAnwersList.length > 0) {
        let isAllRequired = true;
        if (this.requiredList && this.requiredList.length > 0) {
          this.requiredList.forEach((item) => {
            if (
              this.selectAnwersObj[item] &&
              this.selectAnwersObj[item][0].ischecked
            ) {
            } else {
              isAllRequired = false;
            }
          });
        }
        console.log("isAllRequired", isAllRequired);

        if (!isAllRequired) {
          uni.showToast({
            title: "考核结果未填写完全！",
            icon: "none",
          });
          return;
        }

        // if (this.selectAnwersList.length !== this.tagList.length) {
        //   uni.showToast({
        //     title: "考核结果未填写完全！",
        //     icon: "none",
        //   });
        //   return;
        // }
      } else {
        uni.showToast({
          title: "请选择考核结果！",
          icon: "none",
        });
        return;
      }

      if (!(this.imgsList && this.imgsList.length > 0)) {
        uni.showToast({
          title: "请上传现场照片！",
          icon: "none",
        });
        return;
      }

      let extendObj = {
        uploadResult: this.uploadResult,
        imgsList: this.imgsList,
        situation: this.current, // 0 正常 1 紧急
      };

      const req = {
        templateId: this.detailObj.id,
        userId: this.user.UserId,
        userName: this.user.UserName,
        extend: extendObj ? JSON.stringify(extendObj) : "",
        completed: true,
        placeId: 0,
        placeName: this.detailObj.title,
        provinceId: this.user.ProvinceCode,
        provinceName: "",
        serverPartId: this.detailObj.serverPartId,
        serverPartName: this.detailObj.serverPartName,
        questionResponses: this.selectAnwersList,
      };
      const data = await this.$request.$webNodePOST(
        `questionnaire-responses`,
        req
      );
      console.log("data", data);
      if (data.code === 200) {
        this.submit = true;
        uni.showToast({
          title: data.message,
          icon: "none",
        });
        this.$util.toNextRoute(
          "redirectTo",
          `/pages/walkAroundManager/statusPage?id=${data.data.id}`
        );
      } else {
        uni.showToast({
          title: data.message,
          icon: "error",
        });
      }
    },
    // 选中的考核内容
    selectTag(item, detailItem) {
      // 判断当前里面有没有自己选中的答案
      let have = false;
      if (this.selectAnwersList && this.selectAnwersList.length > 0) {
        let haveList = this.selectAnwersList.filter(
          (item) => item.questionId === detailItem.id
        );

        if (haveList && haveList.length > 0) {
          have = true;
        }
      }

      // 当have为true的时候 这个问题已经作答过了
      if (have) {
        // 判断这个问题 是不是多选的
        let [type, questionType] = detailItem.type.split("_");
        // 单选
        if (type === "radio") {
          // 那么要去除它之前的答案
          if (detailItem.options && detailItem.options.length > 0) {
            detailItem.options.forEach((itemOption) => {
              if (itemOption.text === item.text) {
                itemOption.ischecked = true;
              } else {
                itemOption.ischecked = false;
              }
            });
          }
          // 这一次选的答案
          let res = {
            questionId: detailItem.id,
            textResponse: "",
            choiceResponse: [item.text],
            imageResponse: "",
            score: item.mark ? item.mark : 0,
          };
          this.selectAnwersObj[detailItem.id] = [item];

          let newList = [];
          if (this.selectAnwersList && this.selectAnwersList.length > 0) {
            this.selectAnwersList.forEach((listItem) => {
              if (listItem.questionId === detailItem.id) {
                newList.push(res);
              } else {
                newList.push(listItem);
              }
            });
          }
          this.selectAnwersList = newList;
        } else {
          // 判断点击的这个是不是已经选中了
          if (item.ischecked) {
            // 已经选中的话 再次点击应该去除
            let old = JSON.parse(
              JSON.stringify(this.selectAnwersObj[detailItem.id])
            );
            let newList = [];
            if (old && old.length > 0) {
              old.forEach((olditem) => {
                if (olditem.text === item.text) {
                } else {
                  newList.push(olditem);
                }
              });
            }
            this.selectAnwersObj[detailItem.id] = newList;

            let newselectAnwersList = [];
            if (this.selectAnwersList && this.selectAnwersList.length > 0) {
              this.selectAnwersList.forEach((listItem) => {
                if (listItem.questionId === detailItem.id) {
                  let old = JSON.parse(JSON.stringify(listItem.choiceResponse));
                  let newList = [];
                  if (old && old.length > 0) {
                    old.forEach((olditem) => {
                      if (olditem === item.text) {
                      } else {
                        newList.push(olditem);
                      }
                    });
                  }
                  listItem.choiceResponse = newList;
                  if (newList && newList.length > 0) {
                    newselectAnwersList.push(listItem);
                  }
                  // listItem.choiceResponse.push(item.text);
                }
              });
            }
            this.selectAnwersList = newselectAnwersList;
            item.ischecked = false;
          } else {
            item.ischecked = true;
            let old = JSON.parse(
              JSON.stringify(this.selectAnwersObj[detailItem.id])
            );
            old.push(item);
            this.selectAnwersObj[detailItem.id] = old;

            if (this.selectAnwersList && this.selectAnwersList.length > 0) {
              this.selectAnwersList.forEach((listItem) => {
                if (listItem.questionId === detailItem.id) {
                  listItem.choiceResponse.push(item.text);
                }
              });
            }
          }
        }
      } else {
        // have为false 说明第一次作答 记录他点击的答案
        let res = {
          questionId: detailItem.id,
          textResponse: "",
          choiceResponse: [item.text],
          imageResponse: "",
          score: item.mark ? item.mark : 0,
        };
        this.selectAnwersObj[detailItem.id] = [item];
        this.selectAnwersList.push(res);
        item.ischecked = true;
      }
      this.$forceUpdate();
    },
    // 获取单个的模版数据
    async handleGetModalData(id) {
      const data = await this.$request.$webNodeGet(
        `questionnaire-templates/${id}`
      );
      let obj = data.data;
      console.log("obj", obj);
      this.detailObj = obj;

      let list = [];
      if (
        obj.questionnaireTemplateQuestions &&
        obj.questionnaireTemplateQuestions.length > 0
      ) {
        obj.questionnaireTemplateQuestions.forEach((item) => {
          if (item.isRequired) {
            list.push(item.questionId);
          }
        });
      }
      this.requiredList = list;
      this.tagList = obj.questionnaireTemplateQuestions;
    },
    radioFocus() {
      this.radiofocus = true;
      this.imgfocus = false;
    },
    radioChange(evt) {
      this.value = evt.target.value;
      for (let i = 0; i < this.options.length; i++) {
        if (this.options[i].value === evt.target.value) {
          this.current = i;
          break;
        }
      }
    },
    submitImg(e) {
      this.imgfocus = true;
      let _this = this;
      uni.chooseImage({
        count: 9, //默认9
        sizeType: ["original", "compressed"],
        sourceType: ["camera"],
        // "album",
        success: function (rs) {
          console.log("rs", rs);

          let quality = 100;
          if (rs.tempFiles[0].size > 1024 * 200) {
            quality = ((1024 * 200) / rs.tempFiles[0].size) * 100;
          }
          if (quality < 100 && rs.tempFiles[0].path.indexOf(".jpg") > -1) {
            uni.compressImage({
              src: rs.tempFilePaths[0], // 图片路径
              quality: quality, // 压缩质量
              success(res) {
                console.log("res", res);
                let data = {};
                if (res.data) {
                  data = JSON.parse(res.data);
                }
                console.log("data", data);
                uni.showLoading({
                  title: "图片上传中...",
                });
                uni.uploadFile({
                  // url: "https://user.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=MBWA",
                  url: "https://es.robot-z.cn/oss/upload",
                  filePath: res.tempFilePath,
                  header: {
                    "Content-Type": "multipart/form-data",
                  },
                  formData: {},
                  fileType: "image",
                  name: "file",
                  success(res) {
                    console.log("res", res);
                    let data = {};
                    if (res.data) {
                      data = JSON.parse(res.data);
                    }
                    console.log("data", data);
                    uni.hideLoading();
                    _this.imgsList.push(
                      `https://es.robot-z.cn/${data.data.path}`
                    );
                  },
                  fail(error) {
                    console.log("error", error);
                    _this.noPost = true;
                  },
                });
              },
              fail(error) {
                _this.noPost = true;
              },
            });
          } else {
            uni.showLoading({
              title: "图片上传中...",
              // mask: true
            });
            uni.uploadFile({
              // url: "https://user.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=MBWA",
              url: "https://es.robot-z.cn/oss/upload",
              filePath: rs.tempFilePaths[0],
              fileType: "image",
              header: {
                "Content-Type": "multipart/form-data",
              },
              name: "file",
              success(res) {
                console.log("res", res);
                let data = {};
                if (res.data) {
                  data = JSON.parse(res.data);
                }
                console.log("data", data);
                uni.hideLoading();
                _this.imgsList.push(`https://es.robot-z.cn/${data.data.path}`);
                // path;
              },
              fail(error) {
                console.log("error", error);
                _this.noPost = true;
              },
            });
          }
          //   uni.uploadFile({
          //     url: "https://user.eshangtech.com/Coop.Merchant/Handler/handler_ajax.ashx?action_type=UploadFile&folder=MBWA",
          //     filePath: imageSrc,
          //     fileType: "image",
          //     name: "data",
          //     success: (res) => {
          //       let _data = JSON.parse(res.data);

          //       uni.hideLoading();
          //       _this.imgsList.push(imageSrc);
          //       _this.imgData.push(_data.Data.IMAGE_PATH);
          //     },
          //     fail: (err) => {
          //       uni.showModal({
          //         content: err.errMsg,
          //         showCancel: false,
          //       });
          //     },
          //   });
        },
        fail: function (err) {},
      });
    },
  },
};
</script>

<style lang="less" scoped>
.main {
  width: 100%;
  // height: 100vh;
  background-color: #fff;
  box-sizing: border-box;
  padding-bottom: env(safe-area-inset-bottom); /* 兼容 iOS 11.2+ */
  padding-bottom: constant(safe-area-inset-bottom);
  .pageHeader {
    height: 120rpx;
    width: 100%;
    background-color: rgb(246, 246, 246);
    box-shadow: rgb(214, 207, 207) 4rpx 0px 20rpx;
    background: url("../../static/images/mbwa/bj_logo.png") no-repeat bottom
      right;
    background-size: 34%;
    padding-left: 30rpx;
    box-sizing: border-box;
    .hederContent {
      display: flex;
      align-items: center;
      img {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-top: 10rpx;
        margin-right: 20rpx;
      }
    }
  }

  .addressBox {
    color: #727272;
    padding: 30rpx;
    .contentBox {
      display: flex;
      .addressIcon {
        display: inline-block;
        width: 49rpx;
        height: 48rpx;
        border-radius: 10rpx;
        margin-right: 6rpx;
      }
      .xuncha {
        font-size: 26rpx;
        color: #1b1c20;
      }
    }
  }

  .formBox {
    position: relative;
    margin-left: 24rpx;
    box-sizing: border-box;
    ul {
      li {
        width: 100%;
        position: relative;
        margin-top: 16rpx;

        .circle {
          background-color: #b2b2b2;
          height: 16rpx;
          width: 16rpx;
          border-radius: 50%;
          position: absolute;
          top: 16rpx;
          left: 1rpx;
        }
        .circle-first {
          top: 14rpx;
        }
        .circle-last {
          top: 46rpx;
        }
        .circleActive {
          height: 16rpx;
          width: 16rpx;
          border-radius: 50%;
          position: absolute;
          left: 1rpx;
          background-color: #409eff;
        }

        .examineContent {
          width: 100%;
          box-sizing: border-box;
          padding-left: 40rpx;
          .titleBox {
            display: flex;
            align-items: center;

            .img-zds {
              display: inline-block;
              width: 32rpx;
              height: 32rpx;
              background: url("../../static/images/mbwa/content_img_gray.png")
                no-repeat center;
              background-size: contain;
              margin-right: 6rpx;
            }

            .img-upload {
              display: inline-block;
              width: 32rpx;
              height: 32rpx;
              background: url("../../static/images/mbwa/pic_img_gray.png")
                no-repeat center;
              background-size: contain;
              margin-right: 6rpx;
            }

            .activezds {
              background-image: url("../../static/images/mbwa/zdsgl_sm_nr.png");
            }

            .activeupload {
              background-image: url("../../static/images/mbwa/zdsgl_sm_pic.png");
            }

            .titleText {
              font-size: 26rpx;
              color: #7a7a7a;
            }
            .titleTextActive {
              font-size: 26rpx;
              color: #409eff;
            }
          }

          .inputBox {
            color: #939393;
            font-size: 24rpx;
            padding-bottom: 40rpx;
            width: 100%;
            box-sizing: border-box;
            textarea {
              min-height: 50rpx;
              font-size: 24rpx;
              line-height: 1.8;
              border-bottom: 1rpx solid #eee;
              margin-top: 20rpx;
              color: #727272;
            }
          }

          .tagList {
            display: flex;
            font-size: 24rpx;
            color: #606266;
            width: 100%;
            box-sizing: border-box;
            .tagName {
              width: 200rpx;
              margin-right: 16rpx;
              font-size: 22rpx;
              line-height: 2.9;
            }
            .tagsBox {
              width: calc(100% - 200rpx);
              // width: 546rpx;
              padding: 0 24rpx 0 12rpx;
            }
            .tagUnit {
              padding: 4rpx 16rpx;
              background-color: #f4f4f4;
              color: #606266;
              border-radius: 24rpx;
              margin: 8rpx;
              font-size: 22rpx;
              display: inline-block;
              vertical-align: middle;
            }
            .active {
              color: #ed7043;
              background-color: #fdf1ec;
            }
          }

          .uploadBox {
            display: flex;
            flex-flow: row wrap;
            justify-content: flex-start;
            align-items: flex-start;
            width: 100%;
            box-sizing: border-box;
            padding: 20rpx 0;
            /* padding-left: 54rpx; */
            min-height: 160rpx;
            .uploadList {
              position: relative;
              display: flex;
              flex-flow: row nowrap;
              justify-content: center;
              align-items: center;
              background-color: #f1f1f1;
              box-sizing: border-box;
              width: 160rpx;
              height: 160rpx;
              border-radius: 6rpx;
              margin-top: 16rpx;
            }
            .uploadList:nth-child(3n-1) {
              margin-left: 16rpx;
              margin-right: 16rpx;
            }
            .uploadList image {
              width: 160rpx;
              height: 160rpx;
              border-radius: 6rpx;
            }

            .uploadAdd {
              width: 26%;
              box-sizing: border-box;
              .upload-file-add-container {
                display: flex;
                flex-flow: column nowrap;
                justify-content: center;
                align-items: center;
                border: 1rpx dashed #c6c6c6;
                height: 160rpx;
                width: 160rpx;
                margin-top: 15rpx;
                border-radius: 6rpx;
                margin-left: 12rpx;
                .walk-manage-plus {
                  line-height: 60rpx;
                  width: 62rpx;
                  height: 62rpx;
                  text-align: center;
                  border-radius: 50%;
                  background-color: #409eff;
                  color: #ffffff;
                  font-size: 48rpx;
                  box-shadow: 0 2rpx 6rpx 0 #eee;
                }
              }
            }
          }

          .uni-list-cell {
            justify-content: unset;
            margin-top: 28rpx;
          }

          .uni-list-cell:after {
            background-color: #f9f9f9;
          }
        }
      }

      .active .img-zds {
        background-image: url("../../static/images/mbwa/zdsgl_sm_nr.png");
      }
    }

    .btn {
      width: 80%;
      margin: 0 auto;
      margin-top: 50rpx;
      background-color: #409eff;
      border-radius: 10rpx;
      color: #fff;
      font-size: 28rpx;
      line-height: 2.8;
      margin-top: 96rpx;
    }
  }
}
</style>