import 'antd/es/button/style';
import _Button from 'antd/es/button';
import 'antd/es/message/style';
import _message from 'antd/es/message';
import 'antd/es/form/style';
import _Form from 'antd/es/form';
import _set from 'lodash/set';
import _get from 'lodash/get';
import { b as __awaiter, c as __generator, d as __assign, a as __spreadArray } from './index.js';
import { ALLOW_CALC_EDD_BASED_ON_IVF, getBMI, GetAgeByBirthDay, useObisDoctorWs, BaseEditPanelFormFC } from '@lm_fe/components_m';
import { mchcLogger, mchcUtils, mchcEnv, mchcEvent, mchcDriver } from '@lm_fe/env';
import { SLocal_History, SMchc_Common, SLocal_Calculator, SLocal_State, get_preset_form_config, SMchc_Nurse } from '@lm_fe/service';
import { formatDate, getSearchParamsValue, request } from '@lm_fe/utils';
import React__default, { useRef, useEffect, useState } from 'react';
import _values from 'lodash/values';
import _size from 'lodash/size';
import _keys from 'lodash/keys';
import _includes from 'lodash/includes';
import { mchcModal__, BF_Wrap2 } from '@lm_fe/pages';
import 'antd/es/tabs/style';
import 'antd/es/tabs';
import 'lodash/orderBy';
import 'lodash/map';
import '@lm_fe/components';
import 'antd/es/collapse/style';
import 'antd/es/collapse';
import 'antd/es/badge/style';
import 'antd/es/badge';
import 'lodash/assign';
import '@ant-design/icons';
function archivalInformation_onValuesChange(changedValues, allValues, form, setRequiredKeys) {
  return __awaiter(this, void 0, void 0, function () {
    var _a, __key, __value, is是否缴费, is身份证, is出生日期, is末次月经, is预产期, is受孕方式, is婚姻状况, is转入登记整体, is转入登记原单位id, is孕前体重, is孕前身高, is丈夫身份证, is丈夫出生日期, paymentDate, _b, computedData, computedData, lmp, pregnancyInfo, edd, value, bmi, organization, currentOrganization, selectGrade, currentGrade, direction, keys_1, data, checkedValues, textArr, 移植时间, 天数, isIVF, value_1;
    var _c, _d, _e, _f, _g, _h, _j;
    return __generator(this, function (_k) {
      switch (_k.label) {
        case 0:
          _a = getKeyAndValue(changedValues), __key = _a.__key, __value = _a.__value;
          mchcLogger.log('vv changedValues', __key, __value, changedValues);
          is是否缴费 = __key === 'baseInfo.payment';
          is身份证 = __key === 'baseInfo.idNO';
          is出生日期 = __key === 'baseInfo.dob';
          is末次月经 = __key === 'pregnancyInfo.lmp';
          is预产期 = __key === 'pregnancyInfo.edd';
          is受孕方式 = __key === 'pregnancyInfo.conceiveMode__';
          is婚姻状况 = __key === 'baseInfo.maritalStatus';
          is转入登记整体 = __key === 'referralInInfo';
          is转入登记原单位id = __key === 'referralInInfo.organizationId';
          is孕前体重 = __key === 'pregnancyInfo.preweight';
          is孕前身高 = __key === 'pregnancyInfo.preheight';
          is丈夫身份证 = __key === 'partnerInfo.partnerIdNO';
          is丈夫出生日期 = __key === 'partnerInfo.partnerDob';
          if (!is是否缴费) return [3, 4];
          if (!__value) return [3, 2];
          return [4, SMchc_Common.currentTime()];
        case 1:
          _b = _k.sent();
          return [3, 3];
        case 2:
          _b = undefined;
          _k.label = 3;
        case 3:
          paymentDate = _b;
          form.setFieldsValue({
            baseInfo: {
              paymentDate: paymentDate
            }
          });
          _k.label = 4;
        case 4:
          if (is身份证 && _get(allValues, 'baseInfo.idType') === 1 && _size(__value === null || __value === void 0 ? void 0 : __value.replace(/\s*/g, '')) === 18) {
            computedData = mchcUtils.checkIdNo_new(__value);
            if (computedData) {
              form.setFieldsValue({
                baseInfo: {
                  dob: computedData.birth,
                  nationality: computedData.nationality,
                  nativeplace: computedData.province,
                  age: computedData.age
                }
              });
            } else {
              _message.error('请输入符合规范的身份证号码！');
            }
          }
          if (is出生日期 && __value) {
            form.setFieldsValue({
              baseInfo: {
                age: GetAgeByBirthDay(__value)
              }
            });
          }
          if (is丈夫身份证 && _get(allValues, 'partnerInfo.partnerIdType') === 1 && _size(__value === null || __value === void 0 ? void 0 : __value.replace(/\s*/g, '')) === 18) {
            computedData = mchcUtils.checkIdNo_new(__value);
            if (computedData) {
              form.setFieldsValue({
                partnerInfo: {
                  partnerDob: computedData.birth,
                  partnerNationality: computedData.nationality,
                  partnerNativeplace: computedData.province,
                  partnerAge: computedData.age
                }
              });
            } else {
              _message.error('请输入符合规范的身份证号码！');
            }
          }
          if (is丈夫出生日期 && __value) {
            form.setFieldsValue({
              partnerInfo: {
                age: GetAgeByBirthDay(__value)
              }
            });
          }
          if (!(is末次月经 && _get(allValues, "pregnancyInfo.conceiveMode.key") !== 1)) return [3, 6];
          lmp = formatDate(_get(changedValues, 'pregnancyInfo.lmp'));
          return [4, SLocal_Calculator.lmp_计算_edd_gestationalWeek(lmp)];
        case 5:
          pregnancyInfo = _k.sent();
          form.setFieldsValue({
            pregnancyInfo: pregnancyInfo
          });
          _k.label = 6;
        case 6:
          if (is预产期) {
            edd = formatDate(_get(changedValues, 'pregnancyInfo.edd'));
            value = SLocal_Calculator.calGestationalWeekBySureEdd(edd);
            form.setFieldsValue({
              pregnancyInfo: {
                gestationalWeek: value
              }
            });
          }
          if (is孕前体重 && __value && _get(allValues, 'pregnancyInfo.preheight') || is孕前身高 && __value && _get(allValues, 'pregnancyInfo.preweight')) {
            bmi = getBMI(_get(allValues, 'pregnancyInfo.preweight'), _get(allValues, 'pregnancyInfo.preheight'));
            form.setFieldsValue({
              pregnancyInfo: {
                bmi: bmi
              }
            });
          }
          if (is转入登记整体 && __value) {
            __value.recorder = __value.recorder || ((_c = SLocal_State.getUserData()) === null || _c === void 0 ? void 0 : _c.firstName);
            __value.referralDate = __value.referralDate || formatDate();
            form.setFieldsValue({
              referralInInfo: __value
            });
          }
          if (!is转入登记原单位id) return [3, 9];
          return [4, SMchc_Common.getReferralOrganizations({
            id: __value
          })];
        case 7:
          organization = _k.sent();
          return [4, SMchc_Common.getCurrReferralOrganization()];
        case 8:
          currentOrganization = _k.sent();
          selectGrade = (_d = organization[0]) === null || _d === void 0 ? void 0 : _d.grade;
          currentGrade = currentOrganization === null || currentOrganization === void 0 ? void 0 : currentOrganization.grade;
          direction = currentGrade === selectGrade ? 1 : currentGrade > selectGrade ? 2 : 3;
          form.setFieldsValue({
            referralInInfo: {
              referralDirection: direction
            }
          });
          _k.label = 9;
        case 9:
          if (is婚姻状况) {
            keys_1 = ['partnerInfo.partnerName', 'partnerInfo.partnerTelephone', 'partnerInfo.partnerTelephone'];
            if (_includes([1, 4], __value)) {
              setRequiredKeys(keys_1.reduce(function (s, k) {
                var _a;
                return __assign(__assign({}, s), (_a = {}, _a[k] = true, _a));
              }, {}));
            } else {
              setRequiredKeys(keys_1.reduce(function (s, k) {
                var _a;
                return __assign(__assign({}, s), (_a = {}, _a[k] = false, _a));
              }, {}));
            }
          }
          if (!is受孕方式) return [3, 11];
          data = __value;
          checkedValues = (_e = data === null || data === void 0 ? void 0 : data[0]) === null || _e === void 0 ? void 0 : _e.value;
          textArr = (_g = (_f = data === null || data === void 0 ? void 0 : data[0]) === null || _f === void 0 ? void 0 : _f.text) !== null && _g !== void 0 ? _g : [];
          移植时间 = textArr[0];
          天数 = (_h = textArr[1]) !== null && _h !== void 0 ? _h : 0;
          (_j = textArr[2]) !== null && _j !== void 0 ? _j : 0;
          isIVF = checkedValues === 1;
          if (!(isIVF && 移植时间)) return [3, 11];
          return [4, SLocal_Calculator.calcEddBasedOnIVF(移植时间, 天数)];
        case 10:
          value_1 = _k.sent();
          console.log('vv is受孕方式', value_1);
          mchcModal__.confirmOnce({
            title: '根据胚胎移植时间，是否调整预产期B超时间？',
            storeKey: ALLOW_CALC_EDD_BASED_ON_IVF,
            cb: function cb() {
              return form === null || form === void 0 ? void 0 : form.setFieldsValue({
                pregnancyInfo: {
                  sureEdd: value_1
                }
              });
            }
          });
          _k.label = 11;
        case 11:
          return [2];
      }
    });
  });
}
function getKeyAndValue(changedValues) {
  var key1 = _keys(changedValues)[0];
  var value1 = _values(changedValues)[0];
  var value1KeysArr = _keys(value1);
  if (value1KeysArr.length > 1) {
    return {
      __key: key1,
      __value: value1
    };
  }
  var key2 = value1KeysArr[0];
  var __key = [key1, key2].filter(function (_) {
    return _;
  }).join('.');
  var __value = _get(changedValues, __key);
  return {
    __key: __key,
    __value: __value
  };
}
function archivalInformation_onPrint(id) {
  mchcModal__.open('print_modal', {
    modal_data: {
      requestData: {
        url: '/api/pdf-preview',
        resource: 'prenatalVisit',
        template: '',
        version: '',
        note: '',
        id: id
      }
    }
  });
}
function archivalInformation_onClose() {
  SLocal_History.closeAndReplace('/prenatal-visit/pregnancy/list');
}
function preset_config() {
  var preset = get_preset_form_config('门诊_建档');
  return preset;
}
function load_form_config_nurse_end() {
  if (mchcEnv.is('建瓯')) return import('./nurse-end.archival-information.form_new.js');
  return import('./nurse-end.archival-information.form2.js');
}
var getDoctorEndId = mchcUtils.getDoctorEndId;
function Ws() {
  var pid = getDoctorEndId();
  var dataCache = useRef([]);
  var modalId = useRef(1);
  var ins = useRef();
  useObisDoctorWs(pid);
  useEffect(function () {
    var rm = mchcEvent.on_rm('ws_event', function (e) {
      if (e.type !== 'obis-doctor') return;
      ins.current = e.ins;
      if (e.event === 'message' && e.data) {
        e.ins;
        var data = e.data;
        if (data.type === 'RiskMark' || data.type === 'DiagnosisRemind') {
          dataCache.current = __spreadArray(__spreadArray([], dataCache.current, true), [data], false);
        }
        if (e.data.type === 'clean-msg') {
          mchcLogger.log('ssbb', e.data, dataCache.current);
          e.data.isShow && setTimeout(openModal, 800);
        }
      }
    });
    return rm;
  }, []);
  function openModal() {
    mchcModal__.openOne(modalId.current, '预警提醒_高危快讯', {
      modal_data: {
        makeSure: function makeSure(data) {
          var _a;
          (_a = ins.current) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(data));
        },
        websocketDataSum: dataCache.current,
        websocketData: dataCache.current,
        id: getDoctorEndId()
      }
    });
    dataCache.current = [];
  }
  return /*#__PURE__*/React__default.createElement("div", null);
}
function Pregnancies(props) {
  var id = props.id;
  props.toAdd;
  var toCheck = props.toCheck;
  var _a = useState();
  _a[0];
  _a[1];
  var _b = useState({
      pregnancyInfo: {
        validateDate: formatDate()
      }
    }),
    formData = _b[0],
    setFormData = _b[1];
  var form = _Form.useForm()[0];
  var _c = useState({}),
    requiredKeys = _c[0],
    setRequiredKeys = _c[1];
  var searchId = getSearchParamsValue('id');
  var _id = id !== null && id !== void 0 ? id : searchId;
  var _d = useState(false),
    loading = _d[0],
    setLoading = _d[1];
  var isUnCheck = !(formData === null || formData === void 0 ? void 0 : formData.recordstate) || formData.recordstate === '0';
  var _e = BF_Wrap2({
      default_conf: {
        tableColumns: load_form_config_nurse_end,
        title: '孕册管理-编辑'
      }
    }),
    config = _e.config,
    Wrap = _e.Wrap;
  useEffect(function () {
    if (_id) {
      setTimeout(function () {
        SMchc_Nurse.getOutpatientDocument(_id).then(function (remoteData) {
          var _a, _b, _c, _d, _e, _f, _g, _h, _j;
          if (!remoteData) return;
          mchcLogger.log('Pregnancies remote', remoteData);
          var validateDate = (_a = remoteData === null || remoteData === void 0 ? void 0 : remoteData.pregnancyInfo) === null || _a === void 0 ? void 0 : _a.validateDate;
          _set(remoteData, 'pregnancyInfo.validateDate', validateDate !== null && validateDate !== void 0 ? validateDate : formatDate());
          var idNO = (_b = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _b === void 0 ? void 0 : _b.idNO;
          var idType = (_c = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _c === void 0 ? void 0 : _c.idType;
          var checkData = mchcUtils.checkIdNo_new(idNO, idType);
          var dob = (_d = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _d === void 0 ? void 0 : _d.dob;
          var nationality = (_e = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _e === void 0 ? void 0 : _e.nationality;
          var nativeplace = (_f = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _f === void 0 ? void 0 : _f.nativeplace;
          var age = (_g = remoteData === null || remoteData === void 0 ? void 0 : remoteData.baseInfo) === null || _g === void 0 ? void 0 : _g.age;
          _set(remoteData, 'baseInfo.dob', dob !== null && dob !== void 0 ? dob : checkData === null || checkData === void 0 ? void 0 : checkData.birth);
          _set(remoteData, 'baseInfo.nationality', nationality !== null && nationality !== void 0 ? nationality : checkData === null || checkData === void 0 ? void 0 : checkData.nationality);
          _set(remoteData, 'baseInfo.nativeplace', nativeplace !== null && nativeplace !== void 0 ? nativeplace : checkData === null || checkData === void 0 ? void 0 : checkData.province);
          _set(remoteData, 'baseInfo.age', age !== null && age !== void 0 ? age : checkData === null || checkData === void 0 ? void 0 : checkData.age);
          _set(remoteData, 'auditorName', (_h = remoteData.auditorName) !== null && _h !== void 0 ? _h : (_j = SLocal_State.userData) === null || _j === void 0 ? void 0 : _j.login);
          setFormData(remoteData);
        });
      }, 1000);
    }
  }, []);
  var preset = preset_config();
  useEffect(function () {
    return mchcDriver.on_rm('data', function (e) {
      if (e.type === 'ReadCard') {
        var res = e.data;
        var baseInfo = {
          name: res.name,
          idNO: res.idNO,
          idType: res.idType,
          dob: res.dob,
          age: res.age,
          nationality: res.nationality,
          nativeplace: res.nativeplace,
          validateDate: formatDate()
        };
        setFormData({
          baseInfo: baseInfo
        });
      }
    });
  }, []);
  useEffect(function () {
    form.setFieldsValue(formData);
    return function () {};
  }, [formData]);
  function onValuesChange(changedValues, allValues) {
    preset === null || preset === void 0 ? void 0 : preset.handler(changedValues, allValues, form);
    archivalInformation_onValuesChange(changedValues, allValues, form, function (obj) {
      return setRequiredKeys(__assign(__assign({}, requiredKeys), obj));
    });
  }
  function onPrint() {
    if (formData === null || formData === void 0 ? void 0 : formData.id) {
      archivalInformation_onPrint(formData.id);
    }
  }
  function onFinish() {
    return __awaiter(this, arguments, void 0, function (isContinue) {
      var recordstate;
      var _this = this;
      if (isContinue === void 0) {
        isContinue = false;
      }
      return __generator(this, function (_a) {
        recordstate = isContinue ? '0' : isUnCheck ? '1' : formData.recordstate;
        setLoading(true);
        return [2, form.validateFields().then(function (v) {
          return __awaiter(_this, void 0, void 0, function () {
            var fn, remoteData, ok;
            return __generator(this, function (_a) {
              switch (_a.label) {
                case 0:
                  mchcLogger.log('vvv', {
                    v: v,
                    formData: formData
                  });
                  fn = (formData === null || formData === void 0 ? void 0 : formData.id) ? SMchc_Nurse.updateOutpatientDocument : SMchc_Nurse.newOutpatientDocument;
                  return [4, fn(__assign(__assign(__assign({}, formData), v), {
                    recordstate: recordstate
                  }))];
                case 1:
                  remoteData = _a.sent();
                  setLoading(false);
                  _message.success('操作成功！');
                  if (isContinue) {
                    form.resetFields();
                  } else {
                    ok = isUnCheck && toCheck ? confirm('是否前往编辑孕册?') : false;
                    if (ok) {
                      SLocal_History.closeAndReplace("/prenatal-visit/pregnancy/nurse-end?id=".concat(remoteData.id));
                    }
                    mchcEvent.emit('outpatient', {
                      type: '刷新头部',
                      pregnancyId: remoteData.id
                    });
                  }
                  if (mchcEnv["in"](['郫都'])) {
                    if (_get(v, 'pregnancyInfo.reportNow') == '1') {
                      request.post('/api/dataReport/reportPregnancy', {
                        ids: [_get(formData, 'id')]
                      });
                    }
                  }
                  return [2];
              }
            });
          });
        })["catch"](function (e) {
          _message.warning('请完善表单项！');
          mchcLogger.log('error', e);
          setLoading(false);
        })];
      });
    });
  }
  return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, /*#__PURE__*/React__default.createElement(Wrap, {
    style: {
      background: '#fff',
      padding: 12,
      height: '100%',
      overflow: 'scroll'
    }
  }, /*#__PURE__*/React__default.createElement(BaseEditPanelFormFC, {
    requiredKeys: requiredKeys,
    form: form,
    formDescriptions: config === null || config === void 0 ? void 0 : config.tableColumns,
    onValuesChange: onValuesChange,
    renderBtns: function renderBtns() {
      return /*#__PURE__*/React__default.createElement(React__default.Fragment, null, _id ? /*#__PURE__*/React__default.createElement(_Button, {
        type: "primary",
        size: "large",
        onClick: onPrint
      }, "\u6253\u5370") : null, /*#__PURE__*/React__default.createElement(_Button, {
        loading: loading,
        type: "primary",
        size: "large",
        onClick: function onClick() {
          return onFinish();
        }
      }, isUnCheck ? '保存并审核' : '保存'), searchId ? null : /*#__PURE__*/React__default.createElement(_Button, {
        loading: loading,
        type: "primary",
        size: "large",
        onClick: function onClick() {
          return onFinish(true);
        }
      }, "\u4FDD\u5B58\u5E76\u7EE7\u7EED\u6DFB\u52A0\u5B55\u518C"), /*#__PURE__*/React__default.createElement(_Button, {
        size: "large",
        onClick: archivalInformation_onClose
      }, "\u5173\u95ED"));
    }
  })), /*#__PURE__*/React__default.createElement(Ws, null));
}
export { Pregnancies as default };
//# sourceMappingURL=pregnancy.nurse-end.archival-information.js.map
