/**
 * 信息采集
*/
import { httpConfig } from '../../../../utils/httpConfig';
import { $http } from "../../../../utils/https";
const app = getApp()
Page({
  data: {
    navbarData: {
      isGoHome: true,
      isGoBack: true,
      title: '信息采集单', //导航栏 中间的标题
    },
    imgHost: httpConfig && httpConfig.imgHost,
    windowHost: httpConfig && httpConfig.ipDeault ? httpConfig.ipDeault : "",
    navHeight: app.globalData.navHeight,
    spaceHeight: app.globalData.spaceHeight,
    navTitleHeight: app.globalData.navTitleHeight,
    statusBarHeight: app.globalData.statusBarHeight,
    TempHtmlObj:{}, //病历信息OBJ
    formDataSource:[],   //病历解析后的表单内容
    formData:[],   //病历解析后的表单内容（下拉菜单数组调整为一维数组，没有id）
    dataKeyObj:{},  //存值对象
    userData: wx.getStorageSync('userData'),  
    birthDate: '',   //出生日期
    admID:''
  },
  onLoad (options) {
    this.setData({admID:options.admID})
    this.parseBirthDate();
    this.getTempHtml();
  },

  ///调接口获取病历模板html
  getTempHtml: function () {
    let data = {
      params: [{
        templateID:'72'  //初次到院信息采集单
      }]
    }
    $http.post("urlS", this, {
      code: "17050038",
      namespace: "Y",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setData({TempHtmlObj:res.result});
          this.getPageItems(res.result.templateHtmlUrl);
        } else {
          wx.showToast({ title: '请求异常：'+res.errorCode+res.errorMessage })
        }
      }
    });
  },

  // 获取页面有哪些组件及配置
  getPageItems (url) {
    let that = this;
    wx.request({
      // todo html模板链接
      url: 'https://hlwyy.scsmysgkyy.cn' + '/EMRFile/download/emr_html/' + url,
      method: 'GET',
      success: function (res) {
        const htmlStr = res.data;
        const regex = /<span[^>]*data-obj="([^"]*)"/ig;
        let match;
        let dataObjs = [];
        while ((match = regex.exec(htmlStr)) !== null) {
          const dataObjStr = match[1];
          const decodedDataObjStr = decodeURIComponent(dataObjStr);
          try {
            const dataObj = JSON.parse(decodedDataObjStr);
            dataObjs.push(dataObj);
          } catch (error) {
            console.error('JSON解析错误:', error);
          }
        }
        let newDataObjs = JSON.parse(JSON.stringify(dataObjs));
        newDataObjs = that.setSelectRange(newDataObjs);
        // console.log(dataObjs);
        // console.log(newDataObjs);
        that.setData({
          formDataSource:dataObjs,
          formData:newDataObjs
        });
      },
      fail: function (error) {
        console.error("请求远程HTML文件失败：", error);
      }
    });
  },

  //调整选择项数组内容
  setSelectRange (datas) {
    let newDatas = datas;
    for(let i=0;i<newDatas.length;i++){
      let newItems = newDatas[i].datas;
      if(newDatas[i].type === "select" || newDatas[i].type === "radio"){
        let newAry = [];
        for(let j=0;j<newItems.length;j++){
          newAry.push(newItems[j].label)
        }
        newDatas[i].datas = newAry;
      }
    }
    return newDatas;
  },

  //根据身份证号解析出生日期
  parseBirthDate() {
    let idCard = this.data.userData.idCardNo;
    // 提取身份证号中的出生日期部分
    let birthDate = idCard.substring(6, 14);
    // 解析出生日期
    let year = birthDate.substring(0, 4);
    let month = birthDate.substring(4, 6);
    let day = birthDate.substring(6, 8);
    // 返回出生日期对象
    this.setData({
      birthDate: year+'-'+month+'-'+day
    })
  },

  //picker选择器选择事件监听
  pickerChange (e){
    let newDataKeyObj = this.data.dataKeyObj;
    newDataKeyObj[e.target.dataset.key] = e.detail.value;
    newDataKeyObj[e.target.dataset.key+'text'] = e.target.dataset.ranges ? e.target.dataset.ranges[e.detail.value] : e.detail.value;
    this.setData({
      dataKeyObj : newDataKeyObj
    })
  },

  //form表单提交事件
  formSubmit(e) {
    // console.log('form发生了submit事件，携带数据为：', e.detail.value)
    //病历解析后的表单内容
    const formDataSource = this.data.formDataSource;
    //所有下拉选择组件选中的值封装的数组
    const dataKeyObj = this.data.dataKeyObj;
    //一个新的空数组，作为病历保存提交入参
    let submitObjAry = [];
    //form表单中获取的键值数组
    const submitArray = Object.entries(e.detail.value).map(([key, value]) => ({ key, value }));
    // console.log('form表单中获取的键值数组',submitArray)
    for (let i = 0; i < submitArray.length; i++) {
      let obj = {};
      obj.metaDataCode = submitArray[i].key;
      obj.filedText = submitArray[i].value;
      obj.filedHtml = submitArray[i].value;
      for(let j = 0; j < formDataSource.length; j++){
        if(formDataSource[j].key == submitArray[i].key){
          obj.filedType = formDataSource[j].type;
          obj.value = formDataSource[j].id;
          obj.uniqueID = formDataSource[j].id;
          obj.label = formDataSource[j].label;
          //处理type为 select 时 filedCode的赋值
          if(formDataSource[j].type === 'select' || formDataSource[j].type === 'radio'){
            const targetObj = formDataSource[j].datas.filter(obj => obj.label === dataKeyObj[formDataSource[j].key+'text']).map(obj => obj);
            // console.log('返回值：',targetObj)
            if(targetObj.length > 0){
              obj.filedCode = targetObj[0].value+'';
              obj.filedText = targetObj[0].label;
              obj.filedHtml = formDataSource[j].type === 'select' ? targetObj[0].label : '';
            }
          }
        }
      }
      submitObjAry.push(obj);
    }
    this.creatEmrRecord(submitObjAry);
  },

  //创建病历
  creatEmrRecord (submitObjAry) {
    let TempObj = this.data.TempHtmlObj;
    let userData = this.data.userData;
    let that = this;
    let data = {
      params: [{
        admID:that.data.admID,
        templateVersionID:TempObj.templateVersionID,
        patID:userData.patID,
        patName:userData.patDesc,
        courseRecordID:'' //主病程ID，这里不用传
      }]
    }
    $http.post("urlS", this, {
      code: "17050039",
      namespace: "Y",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          that.saveEmrAction(submitObjAry,res.result);
        } else {
          wx.showToast({ title: '请求异常：'+res.errorCode+res.errorMessage })
        }
      }
    });
  },

  //保存病历
  saveEmrAction (submitObjAry,emrResult) {
    let TempObj = this.data.TempHtmlObj;
    let data = {
      params: [{
        admID:this.data.admID,
        courseList: [],
        recordID:emrResult.recordID,
        templateID:emrResult.templateID,
        templateVersionID:emrResult.templateVersionID,
        imagePath: TempObj.pageImage,
        data:submitObjAry
      }]
    }
    $http.post("urlS", this, {
      code: "17050040",
      namespace: "Y",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          wx.showToast({ title: '提交成功'})
          setTimeout(() => {
            wx.switchTab({
              url: '../../../tabBar/index/index',
            })
          }, 1500)
        } else {
          wx.showToast({ title: '请求异常：'+res.errorCode+res.errorMessage })
        }
      }
    });
  }
})
