<template>
  <div class="form-wrap">
    <!--渲染不同的模块表单-->
    <div  v-if="canRender" v-for="(item, index) in addComponents">
      <div v-if="item.showModule" class="content-box" >
        <div v-if="!item.hideTitle" class="title">{{item.title}}</div>
        <el-form
          :ref="'form' + index"
          :id="'form' + index"
          :model="item.formObject"
          size="medium"
          label-position="left"
          class="form"
        >
          <FormScale
            :dataSource="item.dataSource"
            :form="item.formObject"
            :ruleNew="item.ruleNew"
            :class="item.className"
          />
        </el-form>

        <ChoseMedication
          v-if="dialogFormVisible"
          @closeDialog="closeDialog"
          @setMedication="setMedication"
        />

      </div>
    </div>
  </div>
</template>

<script>
  import { getDomain, getScaleModels, getScaleDetail, postScale, updateScalesStatus, submitScale  } from '@/utils/followup/followapis'

  // 量表 template
  import FormScale from '@/components/followup/form/index'
  import ChoseMedication from '@/views/followup/record-manage/dialog/chose-medication';
  // 量表模块数据模型

  // 高血压
  import hypeDataSourceBaseInfo from '../models/hypertension/hypeDataSourceBaseInfo'
  import hypeDataSourceSymptom from '../models/hypertension/hypeDataSourceSymptom'
  import hypeDataSourceSign from '../models/hypertension/hypeDataSourceSign'
  import hypeDataSourceLifeMode from '../models/hypertension/hypeDataSourceLifeMode'
  import hypeDataSourceHelpChecking from '../models/hypertension/hypeDataSourceHelpChecking'
  import hypeDataSourceMedicationUse from '../models/hypertension/hypeDataSourceMedicationUse'
  import hypeDataSourceReferral from '../models/hypertension/hypeDataSourceReferral'
  import hypeDataSourceNextFollowDay from '../models/hypertension/hypeDataSourceNextFollowDay'

  export default {
    data(){
      return {
        dialogFormVisible: false,//是否显示添加用药情况dialog
        domain: '',//通过接口获取白名单域名
        needRule: true, //是否动态开启验证
        showModule: true, //是否隐藏表单模块
        canRender: true,
        valid: false,
        validList: [],
        moduleList: [],//模块列表
        planPatientsTimesId: '',
        scaleNo: '',
        doctorId: '',
        planTimesId: '',
        addComponents: [],
        addComponentsSourceList: [],
        formData: {},//整个表单对象
        medication: [],// 用药情况
        type3Obj: {}
      }
    },
    components: {
      FormScale,
      ChoseMedication,
    },
    props: {
      scaleType: String,//病种类型
      checkStart: Boolean,
      saveWay: Number,
      showBtn: String,
    },
    watch: {
      checkStart(val){
        if(val){
          this.validList = [];
          for(let i=0;i<this.addComponents.length;i++){
            let formName = this.addComponents[i].formName;
            // 将每个模块的fornName对应后台的表名放到表单对象
            this.formData[formName] = this.addComponents[i].formObject;
            this.$nextTick(()=>{
              // saveWay=1是提交，进行校验，2是暂存，不需要校验，直接发送请求
              if(this.saveWay==1){
                if(this.$refs['form' + i].length > 0){
                  this.$refs['form' + i][0].validate((valid) => {
                    this.validList.push(valid);
                  });
                }
              }
            })
          }

          this.$nextTick(()=>{
            // saveWay=1是提交，进行校验，2是暂存，不需要校验，直接发送请求
            if(this.saveWay==1){
              for(let k=0;k<this.validList.length;k++){
                if(!this.validList[k]){
                  this.$emit('checkEnd',false);
                  this.valid = false;
                  this.$nextTick(() => {
                    // 如果表单未完善，跳转到该表单模块
                    document.querySelector(`#form${k}`).scrollIntoView(true);
                  })
                  return;
                }else{
                  this.valid = true;
                }
              }
              if(this.valid){
                this.dataSubmit(()=>{
                  updateScalesStatus({
                    fuPlanPatientTimesId: this.planPatientsTimesId,
                    planTimesId: this.planTimesId,
                    resourceId: this.scaleNo
                  })
                });
              }
            }else{
              this.dataSubmit();
            }

            this.$emit('checkEnd',false);

          })

        }else{
          this.$emit('checkEnd',false);
        }
      },
      showModule(val){
        this.addComponents.forEach((item,index)=>{
          if(index >= 3){
            this.addComponents[index].showModule = val;
          }
        })
      },
    },
    created(){
      this.planPatientsTimesId = this.$route.query.planPatientsTimesId
      this.scaleNo = this.$route.query.scaleNo
      this.doctorId = this.$route.query.doctorId
      this.planTimesId = this.$route.query.planTimesId;
      // 获取量表类型
      this.initScaleType();
      // 获取白名单域名
      this.getWhiteDomain();
    },
    methods: {
      // 获取量表类型
      initScaleType(){
        this.addComponentsSourceList = [
          {name: 'hypeDataSourceBaseInfo',formObject: {},showModule: true,formName: 'h_s_001',className: 'obj-form-title',dataSource: hypeDataSourceBaseInfo(this), hideTitle: true, title: '基本信息'},
          {name: 'hypeDataSourceSymptom',formObject: {},showModule: true,formName: 'hypertension_001',className: 'obj-form-title',dataSource: hypeDataSourceSymptom(this), hideTitle: false, title: '症状'},
          {name: 'hypeDataSourceSign',formObject: {bmi: 0,nextBmi: 0},showModule: true,formName: 'hypertension_002',className: 'obj-form-title',dataSource: hypeDataSourceSign(this), hideTitle: false, title: '体征'},
          {name: 'hypeDataSourceLifeMode',formObject: {},showModule: true,formName: 'hypertension_003',className: 'obj-form-title',dataSource: hypeDataSourceLifeMode(this), hideTitle: false, title: '生活方式指导'},
          {name: 'hypeDataSourceHelpChecking',formObject: {},showModule: true,formName: 'hypertension_004',className: 'obj-form-title',dataSource: hypeDataSourceHelpChecking(this), hideTitle: false, title: '辅助检查'},
          {name: 'hypeDataSourceMedicationUse',formObject: {arrList:this.medication,dosageDay:'',dosageNum:'',medicinesName:'',medicineType:''},showModule: true,formName: 'h_s_002',className: 'obj-form-title',dataSource: hypeDataSourceMedicationUse(this), hideTitle: false, title: '用药情况'},
          {name: 'hypeDataSourceReferral',formObject: {reason:'',mechanism:'',department:''},showModule: true,formName: 'h_s_003',className: 'obj-form-title',dataSource: hypeDataSourceReferral(this), hideTitle: false, title: '转诊'},
          {name: 'hypeDataSourceNextFollowDay',formObject: {nextFollowDay:''},showModule: true,formName: 'h_s_004',className: 'obj-form-title',dataSource: hypeDataSourceNextFollowDay(this), hideTitle: true, title: '下次随访日期'},
        ]
      },
      // 获取白名单域名
      getWhiteDomain(){
        getDomain().then(res=>{
          if(res.code=='000000'){
            this.domain = res.data;
//          this.setFormData()

            // 获取量表模块
            this.getFormModules();

          }else{
            this.$message({
              message: res.message,
              type: 'error'
            });
          }
        })
      },
      // 目前先默认写死
      setFormData(){
        this.addComponents = this.addComponentsSourceList
      },

      // 获取展示的模块
      getFormModules(){
        getScaleModels(this.domain,this.scaleNo).then(res=>{
          if(res.code=='000000'){
            this.moduleList = res.data;
            for(let i=0;i<this.moduleList.length;i++){
              for(let j=0;j<this.addComponentsSourceList.length;j++){
                if(this.moduleList[i]==this.addComponentsSourceList[j].formName){
                  this.addComponents.push(this.addComponentsSourceList[j])
                }
              }
            }

            if(this.showBtn!='0'){
              // 获取量表详情
              this.getFormDetail();
            }

          }else{
            this.$message({
              message: res.message,
              type: 'error'
            });
          }

        })
      },
      // 处理获取用药情况详情数据
      handleModuleMedicalUseDetai(obj){
        if(obj.medicineType=='1'){
          const { dosageDay,dosageNum,medicinesName,medicineType } = obj;
          this.medication.push({ dosageDay,dosageNum,medicinesName,medicineType });
        }else if(obj.medicineType=='3'){
          const { dosageDay,dosageNum,medicinesName,medicineType } = obj;
          this.type3Obj = { dosageDay,dosageNum,medicinesName,medicineType }
        }

      },
      // 获取量表详情
      getFormDetail(){
        getScaleDetail(this.domain,this.planPatientsTimesId,this.scaleNo).then(res=>{
          this.formData = res.data
          let keysList = Object.keys(this.formData);
          if(keysList.length > 0){
            for(let i=0;i<this.addComponents.length;i++){
              let formName = this.addComponents[i].formName;
              if(this.formData[formName] && formName=='h_s_002'){
                let h_s_002 = this.formData[formName];
                let isArr = Array.isArray(h_s_002);
                // 判断是否数组，数组是2条以上数据
                if(isArr){
                  h_s_002.forEach((item,index)=>{
                    this.handleModuleMedicalUseDetai(item);
                  })
                }else{
                  // 如果是对象，则为一条数据
                  this.handleModuleMedicalUseDetai(h_s_002);
                }
                this.addComponents[i].formObject = {
                  arrList: this.medication,
                  ...this.type3Obj
                }
//                console.log(this.addComponents[i].formObject)
              }else if(this.formData[formName] && formName=='hypertension_001'){
                this.addComponents[i].formObject = this.formData[formName];
                let symptom = this.formData[formName].symptom;
                this.addComponents[i].formObject.symptom = JSON.parse(symptom);
              }else{
                // 判断是否有数据，没有就用初始化
                if(this.formData[formName]){
                  this.addComponents[i].formObject = this.formData[formName];
                }else{
                  this.addComponents[i] = this.addComponentsSourceList[i];
                }
              }
            }
          }
        })
      },
      // 处理提交用药情况数据
      handleModuleMedicalUse(){
        let otherMed = [];
        for(let i=0;i<this.addComponents.length;i++){
          if(this.addComponents[i].name == 'hypeDataSourceMedicationUse'){
            const formObject = this.addComponents[i].formObject;
            // 有填写其他药物的情况
            if(formObject.dosageDay !=='' && formObject.dosageDay >=0 && formObject.medicinesName && formObject.dosageNum){
              otherMed.push({
                medicinesName: formObject.medicinesName,
                dosageDay: formObject.dosageDay,
                dosageNum: formObject.dosageNum,
                medicineType: '3'
              })
            }
            this.medication = [...this.medication,...otherMed];
            this.formData.h_s_002 = this.medication;
            this.valid = true;

          }
        }
        let flag = this.valid;
        this.$emit('checkEnd',false);
        return flag;
      },
      // 提交量表
      dataSubmit(callback){
        this.formData.doctorId = parseFloat(this.doctorId);
        this.formData.saveWay = parseFloat(this.saveWay);
        this.formData.planPatientsTimesId = parseFloat(this.planPatientsTimesId);
        this.formData.scaleNo = this.scaleNo;
        this.formData.isLine = 2;

        // 检测用药情况数据是否填写
        if(!this.handleModuleMedicalUse()){
          return;
        }
        this.formData.hypertension_001.symptom = JSON.stringify(this.formData.hypertension_001.symptom);
//         console.log(this.formData)
        postScale(this.domain,this.formData).then(res=>{
          if(res.code=='000000'){
            let doMsg = (this.saveWay==1) ? '提交成功' : '保存成功';
            this.$message({
              message: doMsg,
              type: 'success'
            });
            if(callback){
              callback();
            }
            setTimeout(()=>{
              this.$router.push({
                path: '/followup/record-manage/record-list'
              })
            },1000)
          }else{
            let doMsg = (this.saveWay==1) ? '提交失败' : '保存失败';
            this.$message({
              message: doMsg,
              type: 'error'
            });
          }
        });
      },
      closeDialog(val){
        this.dialogFormVisible = val;
      },
      setMedication(val){
        this.medication.push({...val,medicineType: '1'});
        console.log('medication=>',this.medication)
      }
    },
  }
</script>

<style scoped lang="scss">
  .form-wrap{
    .content-box{
      .title{
        line-height: 60px;
        height: 60px;
        font-weight: bold;
        font-size: 22px;
        border-bottom: 1px dashed #ccc;
      }
    }
  }
</style>
