import { connect } from "herculex";
import { checkPhone, checkIdCard } from "./check";
import {
  editCard,
  createCard,
  createPatient,
  patientUpdate,
  getPatientList,
  getLoginUserCardList,
} from "./service";
import doLogin from "../../utils/doLogin";
import history from "../../utils/history";
import loadOcr from "../../utils/loadOcr";
import getEncryptStr from "../../utils/getEncryptStr";
import { reportCmPV_YL } from "../../utils/cloudMonitorHelper";
import { getSubscribeAuth } from "../../../../core/utils/ywtService";
const caIcon =
  "https://gw.alipayobjects.com/mdn/rms_373ab8/afts/img/A*w6MrS5tmnFAAAAAAAAAAAAAAARQnAQ";
const bookIcon =
  "https://gw.alipayobjects.com/mdn/rms_373ab8/afts/img/A*nta9QpHSTvkAAAAAAAAAAAAAARQnAQ";

const getDefaultForm = () => ({
  id: "",
  name: "",
  sex: "男",
  idCardNo: "",
  relationShip: "",
  phoneNumber: "",
  idCardType: "中国大陆居民身份证",

  /* 新增卡字段 */
  type: "",
  cardNum: "",
  defaultCard: "",
  phoneRsa: "",
  fullNameRsa: "",
  idcardNoRsa: "",
  isInsu: undefined,
});

const cardTypeMap = {
  中国大陆居民身份证: "1",
  港澳台身份证: "9",
};

const copy = (data) => JSON.parse(JSON.stringify(data));

Component(
  connect({
    mapStateToProps: {
      userInfo: ({ $global }) => $global.userInfo || {},
    },
  })({
    props: {
      componentData: {},
    },
    data: {
      caIcon,
      bookIcon,
      show: false,
      routeState: null,
      medicCardsList: [],
      isAuthSuccess: false,
      editForm: getDefaultForm(),
      genders: [
        {
          label: "男",
          value: "男",
        },
        {
          label: "女",
          value: "女",
        },
      ],
      certTypes: [
        {
          id: 1,
          name: "中国大陆居民身份证",
        },
        {
          id: 2,
          name: "港澳台身份证",
        },
      ],
    },

    didMount() {
      const { componentData } = this.props;
      const { editForm, routeState } = componentData || {};
      const state = {};

      if (routeState) {
        state.routeState = routeState;
      }
      /* 编辑 */

      if (editForm) {
        state.editForm = this.initData(editForm);
      }

      this.setData(state);
      /* 埋点服务预警 */

      reportCmPV_YL({
        title: "在线建档",
      });
    },

    methods: {
      isEditCard() {
        const { $routeConfig } = this.$page;
        const { query } = $routeConfig;
        return query.editType === "card";
      },

      initData(data) {
        const _data = {};
        const defaultData = getDefaultForm();
        Object.keys(defaultData).forEach((key) => {
          const value = data[key] || defaultData[key];
          if (value) _data[key] = value;
        });
        return _data;
      },

      onClosePopup() {
        this.setData({
          show: false,
        });
      },

      onTap() {
        this.onClosePopup();
      },

      async onRelationChange({ id, name }) {
        let isAuthSuccess = false;
        const { editForm: _editForm } = this.data;
        let editForm = copy(_editForm);
        /* 如果是从本人切换到其他关系上的需要清空数据 */

        if (_editForm.relationShip === "本人" && id !== 1) {
          editForm = getDefaultForm();
        }

        editForm.relationShip = name;
        /* 如果为本人,唤起授权 */

        if (id === 1) {
          const { userInfo } = this.data; // 判断用户是否已经登陆
          if (userInfo.isLogin) {
            isAuthSuccess = true;
          } else {
            isAuthSuccess = await doLogin.call(this, {
              scopes: "auth_user",
            });
          }

          isAuthSuccess = await doLogin.call(this, {
            scopes: "auth_user",
          });

          if (isAuthSuccess) {
            const {
              phone,
              gender = "m",
              idCardNo,
              fullName,
              phoneRsa,
              fullNameRsa,
              idcardNoRsa,
              isInsu,
            } = this.data.userInfo;
            editForm.name = fullName;
            editForm.idCardNo = idCardNo;
            editForm.phoneNumber = phone;
            editForm.phoneRsa = phoneRsa;
            editForm.fullNameRsa = fullNameRsa;
            editForm.idcardNoRsa = idcardNoRsa;
            editForm.sex = gender === "m" ? "男" : "女";
            editForm.isInsu = isInsu || undefined;
          }
        }

        this.setData({
          isAuthSuccess,
          editForm: { ...editForm },
        });
      },

      checkedInsuChange({ detail }) {
        this.setData({
          "editForm.isInsu": detail.value ? "1" : undefined,
        });
      },

      checkedNoInsuChange({ detail }) {
        this.setData({
          "editForm.isInsu": detail.value ? "0" : undefined,
        });
      },

      checkedTextInsuChange() {
        const { editForm } = this.data;
        const { isInsu } = editForm;
        this.setData({
          "editForm.isInsu": isInsu === "1" ? undefined : "1",
        });
      },

      checkedTextnoInsuChange() {
        const { editForm } = this.data;
        const { isInsu } = editForm;
        this.setData({
          "editForm.isInsu": isInsu === "0" ? undefined : "0",
        });
      },

      /* 一键清除 */
      clearInput(value, key) {
        // eslint-disable-next-line no-param-reassign
        value = value || "";
        const { editForm } = this.data;
        const oldValue = editForm[key] || "";
        return oldValue.indexOf("*") < 0 ? value : "";
      },

      /* 输入姓名 */
      onNameInput({ detail }) {
        this.setData({
          "editForm.name": this.clearInput(detail.value, "name"),
        });
      },

      /* 选择性别 */
      onSexChange(item) {
        this.setData({
          "editForm.sex": item,
        });
      },

      /* 选择证件类别 */
      onCertTypeChange({ detail }) {
        const { value } = detail;
        const { certTypes = [] } = this.data;
        const { name = "" } = certTypes[value];
        this.setData({
          "editForm.idCardType": name,
        });
      },

      /* 输入身份证 */
      onCardNoInput({ detail }) {
        this.setData({
          "editForm.idCardNo": this.clearInput(detail.value, "idCardNo"),
        });
      },

      /* 输入电话号码 */
      onPhoneInput({ detail }) {
        this.setData({
          "editForm.phoneNumber": this.clearInput(detail.value, "phoneNumber"),
        });
      },

      async onCardChange({ cardNum }) {
        this.resolveFn && this.resolveFn(cardNum);
      },

      showTip(msg) {
        my.showToast({
          content: msg,
          duration: 3000,
        });
        return false;
      },

      showSuccess(msg) {
        my.showToast({
          type: "success",
          content: msg,
          duration: 1500,
        });
      },

      showError(msg) {
        my.showToast({
          type: "fail",
          content: msg,
          duration: 1500,
        });
      },

      vailForm(form) {
        const { idCardNo = "", phoneNumber = "" } = form;
        const { sex, name, idCardType, relationShip, isInsu } = form;
        const rest = {
          // sex,
          name,
          idCardType,
          relationShip,
        };
        const values = Object.values(rest);

        if (values.filter((v) => !!v).length !== values.length) {
          return this.showTip("将页面上的信息填写完整!");
        }

        if (idCardType === "中国大陆居民身份证" && !checkIdCard(idCardNo)) {
          return this.showTip("身份证格式不正确!");
        }

        if (!checkPhone(phoneNumber)) {
          return this.showTip("手机号格式不正确!");
        }

        if (!isInsu) {
          return this.showTip("请选择是否医保");
        }

        return true;
      },

      /*
       * 获取非脱敏的字段
       * */
      restForm(form) {
        const _form = {};
        Object.keys(form).forEach((key) => {
          const value = form[key] || "";
          if (value.indexOf("*") < 0) _form[key] = value;
        });
        return _form;
      },

      //  保存就诊人
      async patientSave() {
        const { editForm, isAuthSuccess } = this.data;
        /* 如果不是本人,校验字段 */

        if (!isAuthSuccess) {
          if (!this.vailForm(editForm)) return;
        }
        /* 获取非脱敏的字段 */

        const form = this.restForm(editForm);
        /* 不是编辑的情况,才需要选择就诊卡 */
        if (!editForm.id && !this.isEditCard()) {
          form.bindCardNum = await this.onCheckCard(form);
        }
        await this.onSubmit(this.initData(form));
      },

      /* 提交 */
      async onSubmit(_form) {
        const { routeState } = this.data;
        const { idCardType } = _form;
        /* 加密数据 */

        const form = {
          ..._form,
          idCardNo: await getEncryptStr(_form.idCardNo),
          phoneNumber: await getEncryptStr(_form.phoneNumber),
          idCardType: cardTypeMap[idCardType],
        };
        let msg = "";
        if (form.isInsu !== "1") {
          form.isInsu = "";
        }
        try {
          my.showLoading();
          const isEditCard = this.isEditCard();
          /* 如果有id 或者绑定的卡id为编辑 */
          if (form.id || form.cardNum) {
            if (isEditCard) {
              msg = "就诊卡编辑成功";
              await editCard(form);
            } else {
              msg = "就诊人编辑成功";
              await patientUpdate(form);
            }
          } else if (isEditCard) {
            msg = "就诊卡添加成功";
            await createCard(form);
          } else {
            msg = "就诊人添加成功";
            await createPatient(form);
          }
          this.goNav(routeState);
          this.showSuccess(msg);
        } catch (e) {
          this.showError(e.msg);
        }
        my.hideLoading();
      },

      goNav(state) {
        if (state) {
          const { routeType = "push", ...rest } = state;
          /* routeType push/replace */

          if (history[routeType]) {
            history[routeType](rest);
          }
        } else {
          my.navigateBack();
        }
      },

      /* 获取就诊卡 */
      async onCheckCard() {
        console.log("onCheckCard");
        const { editForm, isAuthSuccess } = this.data;
        my.showLoading();
        const { idCardNo } = editForm;
        return new Promise(async (resolve) => {
          const medicCardsList = isAuthSuccess
            ? await getLoginUserCardList()
            : await this.getCardByIdCardNo(idCardNo);
          /* 如果卡大于一张 */

          if (medicCardsList.length <= 1) {
            return resolve("");
          }

          my.hideLoading();
          this.resolveFn = resolve;
          this.setData({
            show: true,
            medicCardsList,
          });
        });
      },

      /* 根据idCardNo查询某个就诊人的就诊卡 */
      async getCardByIdCardNo(idCardNo) {
        const value = await getEncryptStr(idCardNo);
        const list = await getPatientList({
          idCardNo: value,
        });
        if (!list.length) return [];
        const { medicCards = [] } = list[0];
        return medicCards;
      },

      choosePhoneContact() {
        my.choosePhoneContact({
          success: ({ mobile }) => {
            this.setData({
              "editForm.phoneNumber": mobile.replace(/(\s|-|\+)/g, ""),
            });
          },
        });
      },

      async onLaunchOcr() {
        const { readIDCard, IDCardTypes } = await loadOcr();
        readIDCard({
          bizId: "ocr_01",
          type: IDCardTypes.FRONT,
        })
          .then((res) => {
            if (res.error) {
              return Promise.reject(res.error);
            }

            const {
              num: { data: idCardNo },
              name: { data: realName },
              sex: { data: userSex },
            } = res.data;
            this.setData({
              "editForm.sex": userSex,
              "editForm.name": realName,
              "editForm.idCardNo": idCardNo,
            });
          })
          .catch((e) => {
            this.showTip(e.message || "识别身份证失败");
          });
      },
    },
  })
);