import { getTestTimeList, getQuestionnaire, getItemList, nucleicOrderConfirm } from '../../service/common';
import { getPatientList } from '../edit-patient/service';
import history from '../../utils/history';
import { tradePay } from '../../utils/tradePay';
import { reportCmPV_YL } from '../../utils/cloudMonitorHelper';
Component({
  data: {
    personItem: {},
    hospitalDistrictId: '',
    projects: [],
    personList: [],
    timeList: {},
    disabled: true,
    isFinish: false,
    finishForm: {},
    formList: [],
    questionList: [],
    loading: false,
    hospitalName: '',
    personIndex: undefined,
    showPerson: false,
    timer: null,
    setShowTime: false,
    setShowForm: false,
    setDayTime: '半天',
    onlinePay: false
  },
  props: {
    componentData: {}
  },

  async didMount() {
    const {
      personItem,
      hospitalDistrictId,
      hospitalName,
      componentExtInfo,
      personIndex
    } = this.$page.data.query ? this.$page.data.query : {};
    this.setData({
      hospitalDistrictId
    });
    await this.getProject();
    await this.getPatientLists();
    let setInfo = {}; // 是否直接进入核酸预约页面

    if (this.props.componentData.componentExtInfo) {
      setInfo = this.props.componentData.componentExtInfo;
      this.onShowPerson();
    } else {
      setInfo = componentExtInfo ? JSON.parse(componentExtInfo) : {};
      this.setData({
        personItem: personItem ? JSON.parse(personItem) : {},
        personIndex: Number(personIndex)
      });
    }

    const {
      setShowTime,
      setShowForm,
      setDayTime,
      onlinePay,
      hospitalNameInput
    } = setInfo; // personItem可能参数过长，先decode

    this.setData({
      hospitalName: hospitalName || hospitalNameInput,
      setShowTime: setShowTime === 'true',
      setShowForm: setShowForm === 'true',
      setDayTime,
      onlinePay: onlinePay === 'true'
    });
    /* 服务预警，核酸预约 */

    reportCmPV_YL({
      title: '核酸预约'
    });
  },

  didUnmount() {
    clearTimeout(this.data.timer);
  },

  methods: {
    async getProject() {
      const {
        hospitalDistrictId
      } = this.data;
      const timeList = await getTestTimeList({
        hospitalDistrictId
      });
      const {
        questionList: formList
      } = await getQuestionnaire({
        hospitalDistrictId
      });
      const projects = await getItemList({
        hospitalDistrictId
      });
      this.setData({
        projects,
        timeList,
        formList,
        questionList: formList
      });
    },

    // 选择就诊人部分
    async getPatientLists() {
      const personList = await getPatientList();
      this.setData({
        personList
      });
    },

    onShowPerson() {
      const {
        personList
      } = this.data; // 判就诊人列表三种情况

      if (personList.length === 0) {
        // 没有就诊人信息
        my.alert({
          content: '您还未添加就诊人，无法进行核酸预约',
          buttonText: '去新增',
          success: () => {
            // 没有就诊人信息
            history.replace({
              title: '添加就诊人',
              pageType: 'edit-patient'
            });
          }
        });
      } else if (personList.length === 1) {
        this.setData({
          personItem: personList[0]
        });
      } else {
        // 选择就诊人
        this.setData({
          showPerson: true
        });
      }
    },

    onOpenPerson() {
      this.setData({
        showPerson: true
      });
    },

    onClosePerson() {
      if (!this.data.personItem.name) {
        my.showToast({
          content: '请选择就诊人'
        });
        return;
      }

      this.setData({
        showPerson: false
      });
    },

    onPersonChange(item, index) {
      // 如果有流调表，重置表单
      if (this.data.formList) {
        this.onReset();
      }

      this.setData({
        personItem: item,
        showPerson: false,
        personIndex: index
      });
    },

    // 项目其他部分
    onReset() {
      const {
        formList
      } = this.data;
      this.setData({
        finishForm: {},
        formList: []
      });
      this.onFinishForm();
      this.data.timer = setTimeout(() => {
        this.setData({
          formList
        });
      }, 100);
    },

    onChangeProject(e) {
      const {
        item
      } = e.target.dataset;
      this.setData({
        projectItem: item
      });
      this.onDisableButton();
    },

    onCloseTime(item) {
      this.setData({
        timeItem: item
      });
      this.onDisableButton();
    },

    onRadioChange(e) {
      const {
        name
      } = e.target.dataset;
      const {
        value
      } = e.detail;
      this.data.finishForm[name] = value;
      this.setData({
        finishForm: this.data.finishForm
      });
      this.onFinishForm();
    },

    onFinishForm() {
      const {
        finishForm
      } = this.data;
      const arr = Object.getOwnPropertyNames(finishForm);
      this.setData({
        isFinish: arr.length === this.data.questionList.length
      });
      this.onDisableButton();
    },

    onDisableButton() {
      const {
        projectItem,
        timeItem,
        isFinish,
        setShowTime,
        setShowForm
      } = this.data;
      this.setData({
        disabled: !projectItem || !timeItem && setShowTime || !isFinish && !!setShowForm
      });
    },

    async onSubmit(e) {
      // 是否需要检验表单 && 校验表单是否符合要求
      let isTrue = true;

      if (this.data.setShowForm) {
        isTrue = this.onJudgeForm(e.detail.value);
      }

      if (isTrue) {
        const {
          projectItem,
          timeItem,
          personItem,
          hospitalDistrictId,
          setShowTime,
          onlinePay
        } = this.data; // 获取订单ID

        const res = await nucleicOrderConfirm({
          cardNum: personItem.bindCardNum,
          nucleicItemId: projectItem.nucleicItemId,
          hospitalDistrictId,
          testTimeId: setShowTime && timeItem ? timeItem.testTimeId : ''
        }); // 区分支持线上支付 和 不支持线上支付

        if (res.amount && onlinePay) {
          // const orderRes = await tradeNoQuery({
          //   type: 1,
          //   idNum: res.orderId,
          //   amount: res.amount,
          // });
          // my.tradePay({
          //   tradeNO: orderRes.tradeNo,
          //   success: ({ resultCode }) => {
          //     if (resultCode === '9000') {
          //       history.replace({
          //         query: {
          //           hospitalDistrictId,
          //           orderId: res.orderId,
          //           type: '已支付',
          //         },
          //         title: '预约详情',
          //         pageType: 'booking-detail',
          //       });
          //     }
          //   },
          // });
          this.setData({
            loading: true
          });
          tradePay({
            type: 2,
            amount: res.amount,
            idNum: res.orderId
          }, {
            tradeType: 'Appointment'
          }).then(() => {
            history.replace({
              query: {
                hospitalDistrictId,
                orderId: res.orderId,
                type: '已支付'
              },
              title: '预约详情',
              pageType: 'booking-detail'
            });
          }).finally(() => {
            this.setData({
              loading: false
            });
          });
        } else {
          history.replace({
            query: {
              hospitalDistrictId,
              orderId: res.orderId,
              type: '未支付'
            },
            title: '预约详情',
            pageType: 'booking-detail'
          });
        }
      }
    },

    onJudgeForm(result) {
      const arr = Object.getOwnPropertyNames(result); // 校验表单答案

      const isFalse = arr.some(item => item.split('&')[1] !== result[item]);

      if (isFalse) {
        my.alert({
          title: '您的情况不支持预约',
          content: '请前往医院发热门诊接受筛查'
        });
        return false;
      }

      return true;
    }

  }
});