<template>
  <el-form ref="visitForm" v-loading="loading" :model="form" :rules="rules" label-width="150px" size="small">
    <div class="base-dialog-body">
      <!-- 中心编号 -->
<!--      <el-form-item :label="$t('trials:crcUpload:form:siteId')" prop="SiteId">-->
<!--        <el-select-->
<!--          v-if="form.Id===''"-->
<!--          v-model="form.SiteId"-->
<!--          clearable-->
<!--          filterable-->
<!--          style="width:100%"-->
<!--          @change="handleSiteChange"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="item of siteOptions"-->
<!--            :key="item.Id"-->
<!--            :label="item.TrialSiteCode"-->
<!--            :value="item.SiteId"-->
<!--          />-->
<!--        </el-select>-->
<!--        <el-input :maxLength="$inputMax" v-else v-model="form.TrialSiteCode" disabled />-->
<!--      </el-form-item>-->
      <!-- 受试者编号 -->
      <el-form-item :label="$t('trials:crcUpload:form:subjectId')" prop="SubjectId">
        <el-select
          v-if="form.Id===''"
          v-model="form.SubjectId"
          clearable
          style="width:100%"
          @change="handleSubjectChange"
        >
          <el-option
            v-for="item in subjectOptions"
            :key="item.SubjectId"
            :label="item.Code"
            :value="item.SubjectId"
            :disabled="item.Status === 3"
          />
        </el-select>
        <el-input :maxLength="$inputMax" v-else v-model="form.SubjectCode" disabled />
      </el-form-item>
      <!-- 访视名称 -->
      <el-form-item :label="$t('trials:crcUpload:form:visitName')" prop="VisitName">
        <!-- <el-input :maxLength="$inputMax" v-if="(form.IsFinalVisit && !form.InPlan) || form.InPlan" v-model="form.VisitName" style="width:100%" disabled />
        <el-input :maxLength="$inputMax" v-else v-model="form.VisitName" style="width:100%" :disabled="data.SubmitState*1 === 2" /> -->
        <el-input :maxLength="$inputMax"
          v-model="form.VisitName"
          style="width:100%"
          :disabled="data.SubmitState*1 === 2 || form.InPlan || form.IsFinalVisit"
        />
        <span v-if="!form.InPlan && form.IsFinalVisit" style="color:red">
          *{{ $t('trials:crcUpload:form:setFinalAssessment1').replaceAll('xxx', otherInfo.OutEnrollmentVisitName) }}
        </span>
      </el-form-item>
      <!-- 上一访视 -->
      <el-form-item v-if="!form.InPlan" :label="$t('trials:crcUpload:form:preVisitName')" prop="OutPlanPreviousVisitId">
        <el-select
          v-model="form.OutPlanPreviousVisitId"
          clearable
          style="width:100%"
          :disabled="data.SubmitState*1 === 2"
          @change="handleSubjectVisitChange"
        >
          <el-option
            v-for="item in subjectVisitOptions"
            :key="item.Id"
            :label="item.VisitName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 访视基准日期 -->
      <el-form-item
        v-if="form.IsBaseLine && otherInfo.IsHaveFirstGiveMedicineDate && form.Id !== ''"
        :label="$t('trials:crcUpload:form:baseDateOfVisit')"
      >
        <el-date-picker
          v-model="form.SubjectFirstGiveMedicineTime"
          type="date"
          :picker-options="pickerOption"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
        />
      </el-form-item>
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-button :disabled="btnLoading" size="small" type="primary" @click="cancel">
        {{ $t('common:button:cancel') }}
      </el-button>
      <el-button size="small" type="primary" :loading="btnLoading" :disabled="isDisabled" @click="handleSave">
        {{ $t('common:button:save') }}
      </el-button>
    </div>
  </el-form>
</template>
<script>
import {
  getTrialSiteSelect,
  getSubjectListBySiteId,
  getSubjectVisitSelectOptions,
  addOrUpdateSubjectVisit
} from '@/api/trials'
export default {
  name: 'VisitForm',
  props: {
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    otherInfo: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      siteOptions: [],
      subjectOptions: [],
      subjectVisitOptions: [],
      btnLoading: false,
      form: {
        Id: '',
        SiteId: '',
        SubjectId: '',
        VisitName: '',
        VisitNum: '',
        OutPlanPreviousVisitId: null,
        LastVisit: '',
        VisitExecuted: 0,
        InPlan: false,
        SubjectFirstGiveMedicineTime: '',
        IsEnrollmentConfirm: false,
        PDState: 0,
        IsLostVisit: false,
        IsFinalVisit: false
      },
      rules: {
        SiteId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        SubjectId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        VisitName: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['blur', 'change'] }],
        LastVisit: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
        OutPlanPreviousVisitId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur'] }],
      },
      loading: false,
      isDisabled: false,
      pickerOption: {
        disabledDate: time => {
          return time.getTime() > Date.now()
        }
      },
      trialId: this.$route.query.trialId,
      showFinalVisitWarning: false
    }
  },
  computed: {
    isUploadedData() {
      const count = this.data.NoneDicomStudyCount + this.data.DicomStudyCount
      return count > 0
    }
  },
  mounted() {
    console.log(this.$d.YesOrNo)
    this.initForm()
  },
  methods: {
    // 初始化表单
    async initForm() {
      this.loading = true
      this.isDisabled = true
      const res = await getTrialSiteSelect(this.trialId)
      this.siteOptions = res.Result
      this.form.SiteId = this.siteOptions[0].SiteId
      this.handleSiteChange(this.form.SiteId)
      if (Object.keys(this.data).length && this.data.Id) {
        const { Result } = await getSubjectVisitSelectOptions(this.data.SubjectId)
        this.subjectVisitOptions = Result
        this.form = { ...this.data }
      }
      this.form.TrialId = this.trialId
      this.loading = false
      this.isDisabled = false
    },
    // 保存表单信息
    handleSave() {
      this.$refs.visitForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.form.TrialId = this.trialId
          addOrUpdateSubjectVisit(this.form).then((res) => {
            this.btnLoading = false
            this.$emit('getList')
            this.$emit('closeDialog')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          })
            .catch(() => {
              this.btnLoading = false
            })
        }
      })
    },
    // 关闭弹窗
    cancel() {
      this.$emit('closeDialog')
    },
    // 获取受试者下拉信息
    getSubjectList() {
      getSubjectListBySiteId(this.form.SiteId, this.trialId).then((res) => {
        this.subjectOptions = res.Result
      }
      )
    },
    // site change事件
    handleSiteChange(val) {
      this.form.SubjectId = ''
      this.subjectVisitOptions = []
      if (val) {
        this.getSubjectList()
      } else {
        this.subjectOptions = []
      }
    },
    // 获取受试者访视信息
    getVisitList() {
      getSubjectVisitSelectOptions(this.form.SubjectId).then((res) => {
        this.subjectVisitOptions = res.Result
      })
    },
    // subject change事件
    handleSubjectChange(val) {
      this.form.LastVisit = ''
      this.form.VisitNum = ''
      if (val) {
        this.getVisitList()
      } else {
        this.subjectVisitOptions = []
      }
    },
    // visit change事件
    handleSubjectVisitChange(val) {
      if (val) {
        const selectArr = this.subjectVisitOptions.filter(item => item.Id === val)
        this.form.VisitNum = selectArr[0].VisitNum + 0.1
      }
    },
    handleIsFinalVisitChange(val) {
      // 如果是出组以后的访视，则访视名称取项目配置中出租以后访视名称
      if (!this.form.InPlan && val) {
        this.form.VisitName = this.otherInfo.OutEnrollmentVisitName
      } else if (!this.form.InPlan) {
        this.form.VisitName = this.data.VisitName
      }
      if (val) {
        this.showFinalVisitWarning = true
        this.form.IsLostVisit = false
      } else {
        this.showFinalVisitWarning = false
      }
    },
    handlePdStateChange(val) {
      if (val) {
        this.form.IsLostVisit = false
      }
    }
  }
}
</script>
