<script setup>
import DraggableButton from "@/pages/components/goHome.vue";
/**
 * name：
 * user：myddc
 * date：2024年9月14日 20:05:05
 */
import { ref, computed } from "vue";
import { $image, $api, $response } from "@/api";
import { onShow } from "@dcloudio/uni-app";
import { useStore } from "@/store";
// import { a } from "unocss-preset-weapp/dist/shared/unocss-preset-weapp.79312335.js";
const $store = useStore();

// const content =  [{name: "男", isInput: "为什么选这个选项", },{name: "女", isInput: "", }]

let topicList = ref([]); // 题目列表
let topicIndex = ref(0); // 题目索引


const tabPatients = () => {
  uni.navigateTo({
    url: "/pages/user/choose/choose",
  });
};

const getmyddcSelect = async () => {
  uni.showLoading();
  const response = await $api("QuestionGetList", {
    hospital_id: $store.save.hospital,
    q_type: 2,
  }); //目前请求的套餐 头的接口
  $response(response, () => {
    uni.hideLoading();
    topicList.value = response.data.list.map((val) => {
			let answer = val.type != 1 ? [] : ""
			let content = val.content
			if(val.type === 1){
				if(val.content === '${name}'){
					console.log('myddc_list.value',$store.user)
					answer = $store.user.name
					content = ''
				}
				if(val.content === '${phone}'){
					answer =  $store.user.phone
					content = ''
				}
			}
      return {
        ...val,
				content: content,
        answer: answer,
        more: val.type == 1 ? "" : Array(val.content.length).fill(""),
        isInputList: val.type == 1 ? "" : Array(val.content.length).fill(""),
        index: [],
      };
    });
    getComboList();
  });
};

const getContent = (item) => {
  // 格式化 单选/多选 数据
  let contentArr = item?.content.map((val) => {
    if (val.includes("{{MORE}}")) {
      let valParse = val.split("{{MORE}}");
      return {
        text: valParse[0],
        value: valParse[0],
        isInput: valParse[1],
      };
    }
    return { text: val, value: val, isInput: "" };
  });
  return contentArr;
};

const checkItem = (val, index) => {
  console.log(val);
  let items = topicList.value[topicIndex.value];
  console.log(items);
  if (items.type == 2) {
    // 单选
    items.answer = [];
    items.index = [];
    items.more = Array(items.content.length).fill("");
    items.isInputList = Array(items.content.length).fill("");
    if (items.answer[0] != val.value) {
      items.answer = [val.value];
      items.index = [index];
      items.isInputList[index] = val.isInput;
    }
  } else {
    // 多选
    if (items.answer.includes(val.value)) {
      items.answer = topicList.value[topicIndex.value].answer.filter(
        (item) => item != val.value
      );
      items.index = topicList.value[topicIndex.value].index.filter(
        (item) => item != index
      );
      items.more[index] = ""; // 清空对应的多余的说明
      items.isInputList[index] = "";
    } else {
      items.answer.push(val.value);
      items.index.push(index);
      items.isInputList[index] = val.isInput;
    }
  }
  console.log(topicList.value);
};

const myddc_list = ref({
  list: [],
  hospital: {
    id: 0,
  },
  doctor: {
    id: 0,
  },
  info: {
    name: "",
  },
});

const getComboList = async () => {
  uni.showLoading();
  const response = await $api("ComboList", {
    doctor: $store.save.doctor,
    hospital: hospital_active.value,
  });
  uni.hideLoading();

  $response(response, () => {
    myddc_list.value = response.data;
  });
};

const next = () => {
  // 下一步
  let val = topicList.value[topicIndex.value];
  if (!val?.answer.length) {
    uni.showToast({
      title: "请完成当前问题",
      icon: "none",
    });
    return;
  }
  for (let i = 0; i < val.index.length; i++) {
    let indexItem = val.index[i];
    if (!val.more[indexItem] && val.isInputList[indexItem]) {
      uni.showToast({
        title: "请完成当前问题",
        icon: "none",
      });
      return;
    }
  }
  topicIndex.value++;
};

const hospital_active = ref(0);
const checkHospital = () => {
  let hospital_id = $store.save.hospital;
  if (!hospital_id) {
    hospital_id = $store.config.hospital[0].id;
  }
  hospital_active.value = hospital_id;

  getUserInfo();
};
	const getUserInfo = async () => {
		const response = await $api('UserInfo')
		$response(response, () => {
			$store.setUser(response.data.info);
			getmyddcSelect();
		})
	}

const config_ref = ref(null);
const configRef = (e) => {
  if (!config_ref.value) {
    config_ref.value = e;
    checkHospital();
  }
};

const popup_ref = ref(null);
const popupRef = (e) => {
  console.log(e, "e");
  if (!popup_ref.value) {
    popup_ref.value = e;
  }
};

const sumbilt = async () => {
  console.log(topicList.value);
  let content = [];
  for (let i = 0; i < topicList.value.length; i++) {
    let val = topicList.value[i];
    if (!val.answer.length) {
      // 第一层拦截
      uni.showToast({
        title: "请完成当前问题",
        icon: "none",
      });
      return;
    }

    for (let j = 0; j < val.index.length; j++) {
      let indexItem = val.index[j];
      if (!val.more[indexItem] && val.isInputList[indexItem]) {
        uni.showToast({
          title: "请完成当前问题",
          icon: "none",
        });
        return;
      }
    }

    content.push({
      question: val.question,
      answer: val.answer,
      more: val.more
    })
  }
  console.log(content);
  console.log(JSON.stringify(content));

  uni.showLoading();
  const response = await $api("QuestionSubmitAnswer", {
    content: content,
    q_type: 2,
  });
  uni.hideLoading();

  $response(response, () => {
    popup_ref.value.open();
  });
};
const closePop = () => {
  popup_ref.value.close();
  uni.navigateBack();
};

onShow(() => {
  if (!!config_ref.value) {
    checkHospital();
  }
});
</script>
<template>
  <DraggableButton />
  <view>
    <view v-if="!!$store.config">
      <view :ref="configRef"></view>
    </view>

    <view class="header_wrapper">
      <view v-if="!!myddc_list.hospital.id" class="hospital_wrapper">
        <view class="hospital_icon_wrapper">
          <image src="@/static/assets/dingwei@2x.png"></image>
        </view>
        <view class="hospital_name_wrapper">{{
          myddc_list.hospital.name
        }}</view>
        <view class="hospital_select_wrapper">
          <image src="@/static/assets/gengduo@2x.png"></image>
        </view>
      </view>
      <view v-if="!!myddc_list.info.name" class="user_wrapper" @click="tabPatients()">
        <view class="user_title_wrapper">就诊人：</view>
        <view class="user_name_wrapper">{{ myddc_list.info.name }}</view>
        <view v-if="myddc_list.info.count > 1" class="user_choose_wrapper">
          <image src="@/static/assets/qiehuan@2x.png"></image>
        </view>
      </view>
    </view>

    <view class="center px-80rpx box-border pt-40rpx">
      <image
        src="@/static/assets/slices/slices@3x.png"
        class="w-82rpx mr-38rpx"
        mode="widthFix"
      ></image>
      <view class="">
        <view class="text-#3F3A3A text-32rpx">满意度调查</view>
        <view class="text-#898989 text-22rpx mt-25rpx">
          尊敬的{{ myddc_list.info.name
          }}{{
            myddc_list?.info?.sex == 1 ? "先生" : "女士"
          }}，为了能够更好地为您进行健康评估，请您认真填写以下问卷。
        </view>
      </view>
    </view>
    <view class="text-#0E0E0E mt-10rpx text-26rpx px-80rpx box-border text-right">
      共 <text class="text-#239ea3">{{ topicList.length }}</text> 题
    </view>
    <view class="px-30rpx box-border mt-40rpx" v-if="topicList.length">
      <view
			v-for="(i,topicIndex) in topicList" :key="k"
        class="bg-#fff mb-4 shadow-[0rpx_0rpx_10rpx_0rpx_rgba(0,0,0,0.04)] px-45rpx py40rpx box-border rounded-15rpx"
      >
        <view class="text-#000000 text-30rpx"
          >{{ topicList[topicIndex]?.question }}</view
        >
        <view class="my-35rpx b-0">
          <uni-easyinput
            v-if="topicList[topicIndex]?.type == 1"
            type="textarea"
            v-model="topicList[topicIndex].answer"
            :placeholder="topicList[topicIndex]?.content"
          />
          <view v-if="topicList[topicIndex]?.type != 1">
            <view v-for="(val, index) in getContent(topicList[topicIndex])" :key="index">
              <view
                class="flex items-center mt-30rpx"
                @click="checkItem(val, index)"
              >
                <uni-icons
                  v-if="topicList[topicIndex]?.type == 2"
                  :type="
                    val.value == topicList[topicIndex].answer
                      ? 'circle-filled'
                      : 'circle'
                  "
                  size="20"
                  color="#db991c"
                ></uni-icons>
                <view v-if="topicList[topicIndex]?.type == 3">
                  <uni-icons
                    v-if="topicList[topicIndex].answer.includes(val.value)"
                    type="checkmarkempty"
                    size="18"
                    color="#fff"
                    class="bg-#db991c rounded-5rpx box-border w-36rpx h-36rpx"
                  ></uni-icons>
                  <view
                    v-else
                    class="b-1 b-solid b-#db991c rounded-5rpx box-border w-36rpx h-36rpx"
                  ></view>
                </view>
                <text class="ml-15rpx">{{ val.text }}</text>
              </view>
              <uni-easyinput
                class="mt-20rpx"
                v-if="
                  val.isInput &&
                  topicList[topicIndex].answer.includes(val.value)
                "
                v-model="topicList[topicIndex].more[index]"
                :placeholder="getContent()[index]?.isInput"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <view
      @click="sumbilt()"
      class="bg-#239EA3 text-34rpx center rounded-full w-515rpx h-94rpx mx-auto mt-33rpx text-#fff"
      >提交</view
    >

    <uni-popup :ref="popupRef" type="center">
      <view
        class="w-95% mx-auto bg-#fff px-52rpx pt-60rpx pb-40rpx box-border pt-66rpx rounded-15rpx"
      >
        <view
          class="p-65rpx pb-60rpx text-#000000 text-30rpx box-border mb-40rpx text-center bg-#f4f4f4"
        >
          您的反馈我们已经收到，感谢您参与满意度调查！
        </view>
        <view
          @click="closePop"
          class="w270rpx h74rpx center mx-auto bg-#239EA3 text-#F8F8F8 text-30rpx rounded-10rpx"
          >确定</view
        >
      </view>
    </uni-popup>
  </view>
</template>
<style scoped lang="scss">
::v-deep .uni-data-checklist .checklist-group {
  flex-direction: column !important;
}

::v-deep .uni-data-checklist .checklist-group .checklist-box {
  margin: 15rpx 0 !important;
}

// ::v-deep .is-checked {
//   .radio__inner,
//   .checkbox__inner {
//     border-color: #db991c !important;
//   }

//   .radio__inner-icon,
//   .checkbox__inner {
//     background-color: #db991c !important;
//   }
//   .checklist-text {
//     color: #db991c !important;
//   }
// }

.user_choose_wrapper {
  width: 50rpx;
  height: 50rpx;
  margin-left: 30rpx;
}

.user_choose_wrapper image {
  width: 50rpx;
  height: 50rpx;
  display: block;
  object-fit: contain;
}

.user_title_wrapper {
  font-weight: 400;
  font-size: 28rpx;
  color: #239ea3;
  line-height: 1;
}

.user_name_wrapper {
  font-weight: 400;
  font-size: 28rpx;
  color: #0d0d0d;
  line-height: 1;
}

.user_wrapper {
  height: 80rpx;
  padding-left: 40rpx;
  padding-right: 20rpx;
  background: #ffffff;
  border-radius: 40rpx 0 0 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header_wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 750rpx;
  height: 100rpx;
  background: #d8edf2;
  margin: 0 auto;
}

.hospital_wrapper {
  display: flex;
  align-items: center;
  width: 50%;
}

.hospital_icon_wrapper {
  width: 48rpx;
  height: 48rpx;
  margin-left: 20rpx;
}

.hospital_icon_wrapper image {
  width: 48rpx;
  height: 48rpx;
  display: block;
  object-fit: contain;
}

.hospital_name_wrapper {
  font-weight: 400;
  font-size: 28rpx;
  color: #484747;
  margin-left: 9rpx;
  line-height: 1;
}

.hospital_select_wrapper {
  width: 24rpx;
  height: 14rpx;
  margin-left: 19rpx;
}

.hospital_select_wrapper image {
  width: 24rpx;
  height: 14rpx;
  display: block;
  object-fit: contain;
}
</style>
