// module/chats/components/message-select/message-select.ts
import { Get, Post } from "../../../../lib/request/method";
interface Option {
  id: string;
  name: string;
  checked?: boolean;
  options: Option[] | null;
}
interface HandleEvent {
  mark: {
    type: "sub" | "options";
    index: number;
    item: Option;
  };
}
Component({
  properties: {
    payload: {
      type: Object,
      value: { title: "", multiple: false, options: [] },
      result: "",
    },
    active: { type: Boolean, value: false },
    workId: { type: Number, value: 0 },
  },
  data: {
    placeholder: "请输入",
    safeBottomRpx: 0,
    // 键盘逻辑
    inputBoxBottom: 0, //初始华底部的值
    inputText: "",
    messages: [],
    showrePlenish: false,
    inputFocus: false,
    // end
    options: [],
    subOptions: [] as Option[],
    subMultiple: false,
    itemHeight: 48,

    result: "",
    hasSelected: false,
    required: false,
    multiple: true,
    value1: null,
    radioList: [
      {
        id: "Y",
        label: "有",
        value: 0,
      },
      {
        id: "N",
        label: "没有",
        value: 1,
      },
    ],
    symptomResult: "",
    btnDisabled: false,
    followObj: {},
    labelList: [],
    symptomsList: [],
    isHaveNewSyndrome: "",
    isAnalysis: 0,
    InputHeight:0,
  },
  attached() {
    this.setData({
      isAnalysis: wx.getStorageSync("isAnalysis"),
    });
    const systemInfo = wx.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    const safeAreaBottom = systemInfo.safeArea?.bottom ?? windowHeight; // 没有safeArea时，bottom等于windowHeight
    const safeBottom = windowHeight - safeAreaBottom; // 安全区底部距离（px）
    const tabBarHeight = 100; // 底部tabbar的高度
    const safeBottomRpx = (750 / systemInfo.windowWidth) * safeBottom; // rpx
    // 初始的底部bottom   底部安全区的高度+tabbar的高度
    this.setData({
      inputBoxBottom: safeBottomRpx + tabBarHeight,
      safeBottomRpx: safeBottomRpx,
      InputHeight:safeBottomRpx + tabBarHeight,
    });

    this.setData({
      hasSelected: this.data.options
        .filter((option) => !option.hide)
        .some((option) => option.checked),
    });
    this.getContent();
    this.getStatus();
  },
  observers: {
    options(options: AnyArray) {
      this.setData({
        hasSelected: options
          .filter((option) => !option.hide)
          .some((option) => option.checked),
      });
    },
  },

  methods: {
    handleInput(e: any) {
      this.setData({ inputText: e.detail.value });
    },
    // 发送信息
    send() {
      const text = this.data.inputText.trim();
      // 如果输入框内容为空，则不发送信息
      if (!text) {
        wx.showToast({ title: "发送的信息不能为空", icon: "none" });
        if (this.data.inputFocus) {
          this.setData({
            inputFocus: true,
          });
        }
        return;
      }
      const userMessage = {
        id: Date.now().toString(),
        content: text,
        sender: "user",
        timestamp: Date.now(),
        status: "sending",
      };
      this.setData({
        messages: [...this.data.messages, userMessage],
      });
      if (this.data.messages.length === 2 && this.data.symptomResult === "有") {
        this.setData({
          showrePlenish: false,
        });
        this.triggerEvent("nextType", { MessageType: 2 });
        this.triggerEvent("boxBottom", {
          inputBoxBottom: this.data.InputHeight - 60,
        });
      } else if (
        this.data.messages.length === 1 &&
        this.data.symptomResult === "没有"
      ) {
        this.setData({
          showrePlenish: false,
        });
        this.triggerEvent("nextType", { MessageType: 2 });
        this.triggerEvent("boxBottom", {
          inputBoxBottom: this.data.InputHeight - 60,
        });
      } else if (
        this.data.messages.length === 1 &&
        this.data.symptomResult === "有"
      ) {
        this.setData({
          placeholder: "请问还有其他要补充的吗？",
          inputBoxBottom: this.data.InputHeight,
        });
        this.triggerEvent("boxBottom", {
          inputBoxBottom: this.data.InputHeight,
        });
      }
      this.triggerEvent("scroll", { id: "bottom" });
      // 发送信息之后 输入框内容清空
      this.setData({
        inputText: "",
      });
    },
    // 键盘聚焦
    onInputFocus(e: any) {
      const systemInfo = wx.getSystemInfoSync();
      const height = (750 / systemInfo.windowWidth) * e.detail.height; // 转为rpx
      this.setData({
        inputFocus: true,
        inputBoxBottom: height,
      });
      this.triggerEvent("boxBottom", {
        inputBoxBottom: height,
      });
      this.triggerEvent("scroll", { id: "bottom" });
    },
    // 键盘失焦
    onInputBlur(e: any) {
      // 输入框失焦之后 底部高度是tabbar高度+安全区的高度
      this.setData({
        inputFocus: false,
        inputBoxBottom: this.data.InputHeight,
      });
      this.triggerEvent("boxBottom", {
        inputBoxBottom: this.data.InputHeight,
      });
      this.triggerEvent("scroll", { id: "bottom" });
    },
    // 在字典中取症状的状态
    async getStatus() {
      const dict = await Get("/dict/getDicts", {
        transform({ data }: any) {
          return data;
        },
      });
      // 查找出是随访病症的状态
      let statusArr = dict.filter(
        (item: any) => item.dictType === "followup_syndrome_change"
      );
      this.setData({
        labelList: statusArr[0].items,
      });
    },
    // 获取随访任务详情
    async getContent() {
      // 先从字典中获取状态
      await this.getStatus();
      let followArr: any = [];
      try {
        const res = await Post(
          `/followupTaskManage/getFollowupTaskDetail/${this.data?.workId}`,
          {},
          {
            transform({ data }: any) {
              return data;
            },
          }
        );
        this.setData({ followObj: res });
        // 处理数据
        if (res.syndromeList.length > 0) {
          res.syndromeList.forEach((syndrome: any, index: number) => {
            followArr.push({
              name: syndrome,
              id: index + 1,
              checked: false,
              apiChecked: false,
              options: [],
            });
            if (this.data.labelList.length > 0) {
              this.data.labelList.forEach((label: any, lebelIdx: number) => {
                followArr[index].options.push({
                  name: label.dictLabel,
                  id: lebelIdx + index + 1 + index,
                  checked: false,
                  apiChecked: false,
                });
              });
            }
          });
        }
        this.setData({ options: followArr });
      } catch (error: any) {
        wx.showToast({ title: error.errMsg, icon: "error" });
      }
    },
    // 选择有或没有
    onChangeValue(e: any) {
      this.setData({ value1: e.detail.value });
      // 输入框底部的bottom也还是最初的inputBoxBottom就可以了
      this.triggerEvent("boxBottom", {
        inputBoxBottom: this.data.inputBoxBottom,
      });
      this.setData({
        symptomResult: this.data.radioList.find(
          (item: any) => item.value === e.detail.value
        )?.label,
        isHaveNewSyndrome: this.data.radioList.find(
          (item: any) => item.value === e.detail.value
        )?.id,
      });
      let followObj: any = {
        isHaveNewSyndrome: this.data.isHaveNewSyndrome,
        symptomsList: this.data.symptomsList,
      };
      if (this.data.isHaveNewSyndrome === "N") {
        this.setData({ placeholder: "请问还有其他要补充的吗？" });
      } else {
        this.setData({ placeholder: "请描述新的症状？" });
      }
      this.setData({ btnDisabled: true });
      wx.setStorageSync("followObj", followObj);
      this.setData({
        showrePlenish: true,
      });
      this.triggerEvent("scroll", { id: "bottom" });
    },
    handleTop(event: HandleEvent) {
      if (this.data.result) return;
      const {
        mark: { item },
      } = event;
      if (!item) return;
      const index = this.data.options.findIndex(
        (option) => option.id === item.id
      );
      const multiple = this.data.multiple;
      const checked = !item.checked;
      const options = this._handle(this.data.options, item, index, multiple);
      this.setData({ options });
      if (checked && !multiple) {
        this.onSubmit();
      }
    },
    handleSub(event: HandleEvent) {
      const {
        mark: { item },
      } = event;
      if (!item) return;
      const index = this.data.subOptions.findIndex(
        (option) => option.id === item.id
      );
      const multiple = this.data.subMultiple;
      let checked;
      this.data.subOptions.forEach((option: any, index: number) => {
        if (option.id === item.id) {
          checked = option.checked = true;
        } else {
          option.checked = false;
        }
      });
      const subOptions = this._handle(
        this.data.subOptions,
        item,
        index,
        multiple
      );
      this.setData({ subOptions });

      if (checked && !multiple) {
        this.onConfirm();
      }
    },
    _handle(
      options: Option[],
      item: Option,
      index: number,
      multiple?: boolean
    ) {
      const checked = !item.checked;
      if (checked) {
        const fn = () => {
          if (multiple) {
            options[index].checked = checked;
          } else {
            options.forEach((option) => {
              option.checked = option.id === item.id;
            });
          }
          return options;
        };
        if (item.options?.filter((option) => !(<any>option)?.hide).length) {
          this.setData({
            subTitle: item.name,
            subOptions: item.options,
            subMultiple: true,
          });
          this.onCancel = () => {
            this.setData({ subOptions: [] });
          };
          this.onConfirm = () => {
            if (!this.data.subOptions.some((option) => option.checked)) {
              wx.showToast({ title: "请至少选择一项", icon: "error" });
            } else {
              const options = fn();
              options[index].options = this.data.subOptions;
              this.setData({ subOptions: [], options });
            }
          };
        } else {
          return fn();
        }
      } else {
        options[index].checked = !item.checked;
        if (item.options)
          options[index].options = item.options.map((option) => {
            if (!(<any>option)?.hide) option.checked = !item.checked;
            return option;
          });
      }
      return options;
    },
    onSubmit() {
      if (this.data.result) return;
      if (!this.data.hasSelected) {
        wx.showToast({ title: "请至少选择一项", icon: "error" });
      } else {
        const result = this.data.options
          .filter((item: any) => item?.checked && !item?.hide)
          .map((option: any) => {
            const sub = option.options
              ?.filter((item: any) => item?.checked && !item?.hide)
              .map((item: any) => item.name)
              .join(", ");
            return [option.name, sub].filter(Boolean).join(": ");
          })
          .join("; ");
        this.setData({ result });

        let symptomsList: any = [];
        this.data.options.forEach((option: any) => {
          const isCheck = option.options.every((item: any) => {
            return !item.checked;
          });
          if (isCheck) {
            symptomsList.push({ name: option.name, type: "" });
          } else {
            symptomsList.push({
              name: option.name,
              type:
                option.options.find((item: any) => item.checked)?.name || "",
            });
          }
        });
        this.setData({ symptomsList });
        this.triggerEvent("scroll", { id: "bottom" });
      }
    },

    onSkip() {
      if (this.data.result || this.data.hasSelected) return;
      if (!this.data.payload.required) {
        this.setData({ result: "无变化" });
        this.triggerEvent("next", { options: this.data.options });
      }
      this.triggerEvent("scroll", { id: "bottom" });
      this.setData({ placeholder: "请问还有其他要补充的吗？" });
    },
  },
  onUnload() {
    wx.offKeyboardHeightChange(); // 解绑键盘高度变化监听
  },
});
