<template>
  <div class="home">
    <nav-bar/>
    <van-form @submit="postFrom" ref="testForm">
      <div v-for="(item, questionId) in indexData" :key="questionId">
        <!-- 先处理单选 -->
        <div class="radio_dx" v-if="item.questionType === '01'">
          <p><label>*</label>{{ item.questionTitle }}</p>
          <van-field :rules="formRyles.rulesRadio">
            <template #input>
              <van-cell>
                <van-radio-group
                    v-for="(itemV, itemK) in JSON.parse(item.questionContent)"
                    :key="itemK"
                    v-model="result[questionId].value"
                >
                  <van-cell>
                    <van-radio :name="itemK">{{ itemV }}</van-radio>
                    <span v-if="itemV === '其他'">
                      <van-field
                          v-if="result[questionId].value === itemK"
                          type="text"
                          border
                          placeholder="请输入"
                          v-model="result[questionId].other"
                          :rules="formRyles.rulesField"
                      ></van-field>
                    </span>
                  </van-cell>
                </van-radio-group>
              </van-cell>
            </template>
          </van-field>
        </div>

        <!-- 再处理多选 -->
        <div class="radio_dx" v-if="item.questionType === '02'">
          <p><label>*</label>{{ item.questionTitle }}</p>
          <van-field :rules="formRyles.rulesRadio">
            <template #input>
              <van-cell>
                <van-checkbox-group
                    v-for="(itemV, itemK) in JSON.parse(item.questionContent)"
                    :key="itemK"
                    v-model="result[questionId].value"
                    :max="3"
                >
                  <van-cell>
                    <van-checkbox :name="itemK">{{ itemV }}</van-checkbox>
                    <span v-if="itemV === '其他'">
                    <van-field
                        v-if="result[questionId].value.includes(itemK)"
                        type="text"
                        border
                        placeholder="请输入"
                        v-model="result[questionId].other"
                        :rules="formRyles.rulesField"
                    ></van-field>
                  </span>
                  </van-cell>
                </van-checkbox-group>
              </van-cell>

            </template>
          </van-field>
        </div>

        <!-- 再处理联动情况 联动情况需要注意，父问题必为单选，子问题可为多种类型的问题，单选，多选，文本都有。注意问题需要同级显示。-->
        <div class="radio_dx" v-if="item.questionType === '04'">
          <p><label>*</label>{{ item.questionTitle }}</p>
          <van-field :rules="formRyles.rulesRadio">
            <template #input>
              <van-cell>
                <van-radio-group
                    v-for="(itemV, itemK) in JSON.parse(item.questionContent)"
                    :key="itemK"
                    v-model="result[questionId].value"
                >
                  <van-cell>
                    <van-radio
                        v-model="result[questionId].value"
                        :name="itemK"
                    >{{ itemV }}
                    </van-radio
                    >
                  </van-cell>
                </van-radio-group>
              </van-cell>
            </template>
          </van-field>

          <div class="radio_dx" v-if="result[questionId].value === '2'">
            <p><label>*</label>{{ item.children.questionTitle }}</p>

            <div v-if="item.children.questionType === '01'">
              <van-field :rules="formRyles.rulesRadio">
                <template #input>
                  <van-cell>
                    <van-radio-group
                        v-for="(itemV, itemK) in JSON.parse(
                        item.children.questionContent
                      )"
                        :key="itemK"
                        v-model="result[questionId].children.value"
                    >
                      <van-cell>
                        <van-radio :name="itemK">{{ itemV }}</van-radio>
                        <span v-if="itemV === '其他'">
                          <van-field
                              v-if="result[questionId].children.value === itemK"
                              type="text"
                              border
                              placeholder="请输入"
                              v-model="result[questionId].children.other"
                              :rules="formRyles.rulesField"
                          ></van-field>
                        </span>
                      </van-cell>
                    </van-radio-group>
                  </van-cell>
                </template>
              </van-field>
            </div>
            <div v-else-if="item.children.questionType === '02'">
              <van-field :rules="formRyles.rulesRadio">
                <template #input>
                  <van-cell>
                    <van-checkbox-group
                        v-for="(itemV, itemK) in JSON.parse(
                        item.children.questionContent
                      )"
                        :key="itemK"
                        v-model="result[questionId].children.value"
                        :max="3"
                    >
                      <van-cell>
                        <van-checkbox :name="itemK">{{ itemV }}</van-checkbox>
                        <span v-if="itemV === '其他'">
                          <van-field
                              v-if="
                              result[questionId].children.value.includes(itemK)
                            "
                              type="text"
                              border
                              placeholder="请输入"
                              v-model="result[questionId].children.other"
                              :rules="formRyles.rulesField"
                          ></van-field>
                        </span>
                      </van-cell>
                    </van-checkbox-group>
                  </van-cell>
                </template>
              </van-field>
            </div>
          </div>
        </div>

        <!-- 再处理文本问题 -->
        <div class="radio_dx" v-if="item.questionType === '03'">
          <p>{{ item.questionTitle }}</p>
          <van-field
              v-if="
              item.questionType === '03' &&
                !item.questionTitle.includes('就诊卡号')
            "
              type="text"
              placeholder="请输入"
              v-model="result[questionId].value"
          ></van-field>
          <van-field
              v-else-if="
              item.questionType === '03' &&
                item.questionTitle.includes('就诊卡号')
            "
              type="number"
              placeholder="请输入"
              v-model="result[questionId].value"
          ></van-field>
        </div>
      </div>
      <div style="margin: 16px;">
        <van-button
            round
            block
            type="info"
            native-type="submit"
            @click="goVanFieldControl"
        >提交
        </van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import Vue from "vue";
import {Tab, Tabs, Toast} from "vant";
import {Form} from "vant";
import {Field} from "vant";
import {sendZYData, getQuestions, getAllQuestionNew} from "@/request/api";

export default {
  name: "mz_test.vue",
  data() {
    return {
      indexData: [],
      result: [],
      check_jqmz: [],
      xxx: "",
      formRyles: {
        mobile: [
          {required: true, message: "请填正确的手机号"},
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/,
            message: "手机格式错误",
          },
        ],
        rulesRadio: [{required: true, message: "请选择选项"}],
        rulesField: [{required: true, message: "请输入内容"}],
      },
    };
  },
  beforeCreate() {
    let title = this.$route.query.title;
    this.$route.meta.title = title;
  },
  mounted() {
    let type_id = this.$route.query.type_id;
    // let type_id = 101;
    let params = {
      type_id: type_id,
    };
    getAllQuestionNew(params).then((res) => {
      if (res.code === 200) {
        this.indexData = res.data;
        let result = [];
        if (!this.indexData.length) {
          result = [{}];
        } else {
          for (let i = 0; i < this.indexData.length; i++) {
            if (this.indexData[i].questionType === "02") {
              result.push({
                questionId: this.indexData[i].questionId,
                value: [],
                other: "",
              });
            } else if (this.indexData[i].questionType === "04") {
              if (this.indexData[i].children.questionType === "02") {
                result.push({
                  questionId: this.indexData[i].questionId,
                  value: [],
                  other: "",
                  children: {
                    questionId: this.indexData[i].children.questionId,
                    value: [],
                    other: "",
                  },
                });
              } else {
                result.push({
                  questionId: this.indexData[i].questionId,
                  value: [],
                  other: "",
                  children: {
                    questionId: this.indexData[i].children.questionId,
                    value: "",
                    other: "",
                  },
                });
              }
            } else {
              result.push({
                questionId: this.indexData[i].questionId,
                value: "",
                other: "",
              });
            }
          }
        }
        this.result = result;
      } else {
        Toast(res.message);
      }
    });
  },
  methods: {
    //定位未填写的必填项第一项
    goVanFieldControl() {
      //延迟获取error标签数据组，放外面会导致获取过快导致null
      setTimeout(() => {
        console.log("开始校验");
        let isError = document.getElementsByClassName("van-field--error"); // 获取错误内容标签
        if (isError.length !== 0) {
          isError[0].scrollIntoView({
            behavior: "smooth",
            block: "start",
            inline: "start",
          }); // 只定位到第一个必填项位置
        }
      }, 500);
    },
    // dydata(val) {
    //   console.log(val);
    //   console.log(this.result);
    // },
    postFrom(value) {
      let formData = [];

      this.result.forEach((e) => {
        var newData = this.indexData.find(
            (a) => a.questionId + "" === e.questionId + ""
        );
        let obj = [];
        if (newData.questionType === "04") {
          if (e.value === "1") {
            //如果选中的否，则正常保存
            var str = newData.questionContent;
            var jsonObj = JSON.parse(str.trim());
            console.log(jsonObj);
            var str = e.value.toString();
            var s = str.split(",");
            for (var key in s) {
              obj.push(jsonObj[s[key]]);
            }
            let data = {
              question_id: e.questionId + "",
              question_title: obj.toString(),
              question_answer: e.value.toString(),
              question_comment: e.other,
              type_id: newData.typeId,
              question_type: newData.questionType,
              tenant_id: "1",
              deleted: "0",
              updater: localStorage.getItem("userid"),
              username: this.result[this.result.length - 2].value,
              usertel: this.result[this.result.length - 1].value,
            };
            formData.push(data);
            return;
          } else {
            //如果选中的是“是”，保存children数据
            var str_content = newData.questionContent;
            var jsonObj = JSON.parse(str_content.trim());
            var str = e.value.toString();
            var s = str.split(",");
            for (var key in s) {
              obj.push(jsonObj[s[key]]);
            }
            let data = {
              question_id: e.questionId + "",
              question_title: obj.toString(),
              question_answer: e.value.toString(),
              question_comment: e.other,
              type_id: newData.typeId,
              question_type: newData.questionType,
              tenant_id: "1",
              deleted: "0",
              updater: localStorage.getItem("userid"),
              username: this.result[this.result.length - 2].value,
              usertel: this.result[this.result.length - 1].value,
            };
            formData.push(data);
            obj = [];
            var chlidStr_content = newData.children.questionContent;
            var childJsonObj = JSON.parse(chlidStrContent.trim());
            var childStr = e.children.value.toString();
            var p = childStr.split(",");
            for (var key in p) {
              obj.push(childJsonObj[p[key]]);
            }
            let childData = {
              question_id: e.children.questionId + "",
              question_title: obj.toString(),
              question_answer: e.children.value.toString(),
              question_comment: e.children.other,
              type_id: newData.children.typeId,
              question_type: newData.children.questionType,
              tenant_id: "1",
              deleted: "0",
              updater: localStorage.getItem("userid"),
              username: this.result[this.result.length - 2].value,
              usertel: this.result[this.result.length - 1].value,
            };
            formData.push(childData);
            return;
          }
          // newData.children.
        }
        if (newData.questionType !== "03") {
          var str_content = newData.questionContent;
          var jsonObj = JSON.parse(str_content.trim());
          // console.log(jsonObj);
          var str = e.value.toString();
          var s = str.split(",");
          for (var key in s) {
            obj.push(jsonObj[s[key]]);
          }
        }

        // console.log(this.result[this.result.length] - 1);
        let data = {
          question_id: e.questionId + "",
          question_title: obj.toString(),
          question_answer: e.value.toString(),
          question_comment: e.other,
          type_id: newData.typeId,
          question_type: newData.questionType,
          tenant_id: "1",
          deleted: "0",
          updater: localStorage.getItem("userid"),
          username: this.result[this.result.length - 2].value,
          usertel: this.result[this.result.length - 1].value,
        };
        formData.push(data);
      });
      // console.log(formData)
      let tempData = {
        wqdas: formData,
        userId: localStorage.getItem("userid"),
        token: localStorage.getItem("token")
      }
      sendZYData(tempData).then((res) => {
        if (res.code === 200) {
          Toast(res.message);
          this.$router.push({path: "/Succ"});
        }
      });
      // console.log(formData); //连接后端接口，发送数据
    },
  },
};
</script>

<style scoped>
.radio_dx {
  margin: 0.2rem 0.2rem 0.2rem 0.2rem;
  width: 100%;
}

p {
  background-color: #e5f4fb;
  padding: 0.3rem 0.3rem 0.3rem 0.3rem;
  font-size: large;
  color: #333333;
}

p label {
  color: red;
}
</style>
