<template>
  <div class="workload">
    <el-form
      ref="workloadForm"
      size="small"
      :model="workloadForm"
      :rules="workloadRules"
      class="demo-ruleForm"
      label-width="180px"
    >
      <!-- Expedited -->
      <el-form-item :label="$t('trials:stats:form:expedited')">
        <el-select v-model="trialExpeditedState" disabled>
          <el-option v-for="item of $d.TrialExpeditedState" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- 展示所有 -->
      <el-form-item :label="$t('trials:stats:form:dispalyAll')">
        <el-switch v-model="trialExpeditedDisplayAll" />
      </el-form-item>
      <!-- Work Month -->
      <el-form-item v-if="workloadForm.DataFrom!=0" :label="$t('trials:stats:form:workmonth')" prop="WorkTime">
        <el-date-picker
          v-model="workloadForm.WorkTime"
          type="month"
          value-format="yyyy-MM"
          :picker-options="pickerOption"
          disabled
        />
      </el-form-item>
      <!-- Work Date -->
      <el-form-item v-if="workloadForm.DataFrom==0" :label="$t('trials:stats:form:workdate')" prop="WorkTime">
        <el-date-picker
          v-model="workloadForm.WorkTime"
          type="date"
          :default-value="defaultDate"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOption"
          @change="datePickerChange"
        />
      </el-form-item>
      <!-- Source -->
      <el-form-item :label="$t('trials:stats:form:source')" prop="DataFrom">
        <el-select v-model="workloadForm.DataFrom" style="width:100%;" value-key="value" disabled>
          <el-option
            v-for="item in statusOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- Training -->
      <el-form-item :label="$t('trials:enrolledReviews:table:training')">
        <el-input-number v-model="workloadForm.Training" :min="0" style="width:100%" />
        <span
          v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Training') !== -1"
          style="color:#428bca;font-size:13px;"
        >
          <!-- Training from client is {{ info.clientData.Training }}. -->
          {{ `${$t('trials:stats:message:training')} ${info.clientData.Training}` }}
        </span>
      </el-form-item>
      <!-- Refresher Training -->
      <el-form-item :label="$t('trials:enrolledReviews:table:refresherTraining')">
        <el-input-number v-model="workloadForm.RefresherTraining" :min="0" style="width:100%" />
        <span
          v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Refresher Training') !== -1"
          style="color:#428bca;font-size:13px;"
        >
          <!-- Refresher Training from client is {{ info.clientData.RefresherTraining }}. -->
          {{ `${$t('trials:stats:message:refresherTraining')} ${info.clientData.RefresherTraining}` }}
        </span>
      </el-form-item>
      <div v-show="trialExpeditedState==0||trialExpeditedDisplayAll">
        <!-- Timepoint -->
        <el-form-item :label="$t('trials:enrolledReviews:table:tpRegular')">
          <el-input-number v-model="workloadForm.Timepoint" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Timepoint') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Timepoint from client is {{ info.clientData.Timepoint }}. -->
            {{ `${$t('trials:stats:message:tp')} ${info.clientData.Timepoint}` }}
          </span>
        </el-form-item>
        <!-- Adjudication -->
        <el-form-item label="Adjudication：">
          <el-input-number v-model="workloadForm.Adjudication" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Adjudication') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Adjudication from client is {{ info.clientData.Adjudication }}. -->
            {{ `${$t('trials:stats:message:ad')} ${info.clientData.Adjudication}` }}
          </span>
        </el-form-item>
      </div>
      <div v-show="trialExpeditedState==1||trialExpeditedDisplayAll">
        <!-- Timepoint 24H -->
        <el-form-item label="Timepoint 24H：">
          <el-input-number v-model="workloadForm.TimepointIn24H" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Timepoint 24H') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Timepoint 24H from client is {{ info.clientData.TimepointIn24H }}. -->
            {{ `${$t('trials:stats:message:tp24H')} ${info.clientData.TimepointIn24H}` }}
          </span>
        </el-form-item>
        <!-- Adjudication 24H -->
        <el-form-item label="Adjudication 24H：">
          <el-input-number v-model="workloadForm.AdjudicationIn24H" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Adjudication 24H') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Adjudication 24H from client is {{ info.clientData.AdjudicationIn24H }}. -->
            {{ `${$t('trials:stats:message:ad24H')} ${info.clientData.AdjudicationIn24H}` }}
          </span>
        </el-form-item>
      </div>
      <div v-show="trialExpeditedState==2||trialExpeditedDisplayAll">
        <!-- Timepoint 48H -->
        <el-form-item label="Timepoint 48H：">
          <el-input-number v-model="workloadForm.TimepointIn48H" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Timepoint 48H') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Timepoint 48H from client is {{ info.clientData.TimepointIn48H }}. -->
            {{ `${$t('trials:stats:message:tp48H')} ${info.clientData.TimepointIn48H}` }}
          </span>
        </el-form-item>
        <!-- Adjudication 48H -->
        <el-form-item label="Adjudication 48H：">
          <el-input-number v-model="workloadForm.AdjudicationIn48H" :min="0" style="width:100%" />
          <span
            v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Adjudication 48H') !== -1"
            style="color:#428bca;font-size:13px;"
          >
            <!-- Adjudication 48H from client is {{ info.clientData.AdjudicationIn48H }}. -->
            {{ `${$t('trials:stats:message:ad48H')} ${info.clientData.AdjudicationIn48H}` }}
          </span>
        </el-form-item>
      </div>
      <!-- Global -->
      <el-form-item label="Global：">
        <el-input-number v-model="workloadForm.Global" :min="0" style="width:100%" />
        <span
          v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Global') !== -1"
          style="color:#428bca;font-size:13px;"
        >
          <!-- Global from client is {{ info.clientData.Global }}. -->
          {{ `${$t('trials:stats:message:global')} ${info.clientData.Global}` }}
        </span>
      </el-form-item>
      <!-- Downtime -->
      <el-form-item label="Downtime：">
        <el-input-number v-model="workloadForm.Downtime" :min="0" style="width:100%" />
        <span
          v-if="workloadForm.DataFrom == 2 && info.clientData && incorrectItem.indexOf('Downtime') !== -1"
          style="color:#428bca;font-size:13px;"
        >
          <!-- Downtime from client is {{ info.clientData.Downtime }}. -->
          {{ `${$t('trials:stats:message:downtime')} ${info.clientData.Downtime}` }}
        </span>
      </el-form-item>

      <el-row>
        <el-form-item>
          <!-- Save -->
          <el-button
            size="small"
            type="primary"
            style="float:right;"
            :disabled="btnDisabled"
            @click="saveWorkload"
          >
            {{ $t('common:button:save') }}
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { existWorkLoad, workLoadAddOrUpdate } from '@/api/trials'
import { parseISOLocal } from '@/utils/formatter'
export default {
  props: {
    trialId: {
      type: String,
      default: ''
    },
    doctorId: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    info: {
      type: Object,
      default: () => {}
    },
    yearMonth: {
      type: String,
      default: ''
    },
    trialExpeditedState: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      trialExpeditedDisplayAll: false,
      defaultDate: '',
      YearMonthStr: '',
      isExist: false,
      existObj: '',
      workloadForm: {
        Id: '',
        DoctorId: '',
        TrialId: '',
        Training: 0,
        Timepoint: '',
        TimepointIn24H: 0,
        TimepointIn48H: 0,
        Adjudication: 0,
        AdjudicationIn24H: 0,
        AdjudicationIn48H: 0,
        Global: 0,
        Downtime: 0,
        RefresherTraining: 0,
        WorkTime: '',
        DataFrom: 0
      },
      statusOption: [
        { label: 'Data from Reviewer', value: 0 },
        { label: 'Data from Client', value: 1 },
        { label: 'Reconciled Data', value: 2 }
      ],
      workloadRules: {
        WorkTime: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: 'blur' }
        ],
        DataFrom: [
          { required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }
        ]
      },
      pickerOption: {
        disabledDate: (time) => {
          var minDate = parseISOLocal(this.yearMonth + '-01')
          var maxDate = parseISOLocal(this.yearMonth + '-01')
          maxDate.setMonth(maxDate.getMonth() + 1)
          maxDate.setDate(maxDate.getDate() - 1)
          return (
            time.getTime() < minDate.getTime() ||
            time.getTime() > maxDate.getTime() ||
            time.getTime() > Date.now()
          )
        }
      },
      btnDisabled: false,
      incorrectItem: []
    }
  },
  mounted() {
    if (this.id) {
      this.workloadForm = {
        Training: this.info.Training,
        Timepoint: this.info.Timepoint,
        TimepointIn24H: this.info.TimepointIn24H,
        TimepointIn48H: this.info.TimepointIn48H,
        Adjudication: this.info.Adjudication,
        AdjudicationIn24H: this.info.AdjudicationIn24H,
        AdjudicationIn48H: this.info.AdjudicationIn48H,
        Global: this.info.Global,
        RefresherTraining: this.info.RefresherTraining,
        Downtime: this.info.Downtime,
        WorkTime: this.info.WorkTimeStr,
        DataFrom: this.info.DataFrom
      }
      if (this.info.Id) {
        this.workloadForm.Id = this.info.Id
      }
      this.YearMonthStr = this.info.YearMonthStr
    } else {
      this.defaultDate = parseISOLocal(this.yearMonth + '-01')
      this.workloadForm.DataFrom = 0
    }
  },
  methods: {
    datePickerChange() {
      this.existworkLoad()
    },

    existworkLoad() {
      const param = {
        TrialId: this.trialId,
        DoctorId: this.doctorId,
        WorkDate: this.workloadForm.WorkTime,
        DataFrom: 0
      }

      var that = this
      existWorkLoad(param).then((res) => {
        if (res.IsSuccess) {
          that.isExist = res.Result.IsExist
          that.existObj = res.Result.WorkLoad

          if (that.isExist && that.id) {
            that
              .$confirm(this.$t('trials:stats:message:editWorkload'), {
                type: 'warning'
              })
              .then(() => {
                that.$emit('setTitle', this.$t('trials:stats:dialogTitle:edit'))
                that.workloadForm.Id = that.existObj.Id
                that.workloadForm.DoctorId = that.existObj.DoctorId
                that.workloadForm.TrialId = that.existObj.TrialId
                that.workloadForm.Training = that.existObj.Training
                that.workloadForm.Timepoint = that.existObj.Timepoint
                that.workloadForm.TimepointIn24H = that.existObj.TimepointIn24H
                that.workloadForm.TimepointIn48H = that.existObj.TimepointIn48H
                that.workloadForm.Adjudication = that.existObj.Adjudication
                that.workloadForm.AdjudicationIn24H =
                  that.existObj.AdjudicationIn24H
                that.workloadForm.AdjudicationIn48H =
                  that.existObj.AdjudicationIn48H
                that.workloadForm.Global = that.existObj.Global
                that.workloadForm.RefresherTraining = that.existObj.RefresherTraining
                that.workloadForm.Downtime = that.existObj.Downtime
                that.workloadForm.WorkTime === that.existObj.WorkTime
              })
              .catch(() => {
                //
                that.workloadForm.WorkTime = ''
              })
          }
        } else {
          this.$alert(res.ErrorMessage)
        }
      })
    },
    saveWorkload() {
      this.$refs.workloadForm.validate((valid) => {
        if (valid) {
          this.workloadForm.DoctorId = this.doctorId
          this.workloadForm.TrialId = this.trialId
          this.addWorkload()
        }
      })
    },

    addWorkload() {
      this.incorrectItem = []
      if (
        this.workloadForm.Timepoint +
          this.workloadForm.TimepointIn24H +
          this.workloadForm.TimepointIn48H +
          this.workloadForm.Global +
          this.workloadForm.Training +
          this.workloadForm.Downtime +
          this.workloadForm.Adjudication +
          this.workloadForm.AdjudicationIn24H +
          this.workloadForm.AdjudicationIn48H + this.workloadForm.RefresherTraining ===
        0
      ) {
        this.$message({
          showClose: true,
          message: this.$t('trials:stats:message:editWorkloadWarning1'),
          type: 'error'
        })

        return
      }
      if (this.info.DataFrom === 2) {
        const items = []
        if (this.workloadForm.Training !== this.info.clientData.Training) items.push('Training')
        if (this.workloadForm.Timepoint !== this.info.clientData.Timepoint) items.push('Timepoint')
        if (this.workloadForm.TimepointIn24H !== this.info.clientData.TimepointIn24H) items.push('Timepoint 24H')
        if (this.workloadForm.TimepointIn48H !== this.info.clientData.TimepointIn48H) items.push('Timepoint 48H')

        if (this.workloadForm.Adjudication !== this.info.clientData.Adjudication) items.push('Adjudication')
        if (this.workloadForm.AdjudicationIn24H !== this.info.clientData.AdjudicationIn24H) items.push('Adjudication 24H')
        if (this.workloadForm.AdjudicationIn48H !== this.info.clientData.AdjudicationIn48H) items.push('Adjudication 48H')
        if (this.workloadForm.Global !== this.info.clientData.Global) items.push('Global')
        if (this.workloadForm.RefresherTraining !== this.info.clientData.RefresherTraining) items.push('Refresher Training')
        if (this.workloadForm.Downtime !== this.info.clientData.Downtime) items.push('Downtime')
        if (items.length === 0) {
          this.workLoadAddOrUpdate()
        } else {
          const confirmMsg = this.$t('trials:stats:message:editWorkloadWarning2')

          this.$confirm(confirmMsg, {
            type: 'warning'
          })
            .then(() => {
              this.workLoadAddOrUpdate()
            })
            .catch(() => {
              this.incorrectItem = items
            })
        }
      } else {
        this.workLoadAddOrUpdate()
      }
    },
    workLoadAddOrUpdate() {
      this.btnDisabled = true
      workLoadAddOrUpdate(this.workloadForm)
        .then((res) => {
          this.btnDisabled = false
          if (res.IsSuccess) {
            if (!this.workloadForm.Id) {
              this.workloadForm.Id = res.Result
            }
            // this.$message.success('Saved  successfully')
            this.$message.success(this.$t('common:message:savedSuccessfully'))
            this.$emit('handleClose')
          }
        })
        .catch(() => {
          this.btnDisabled = false
        })
    }
  }
}
</script>
<style scoped>
.workload .el-date-editor.el-input,
.workload .el-input-number--small,
.workload .el-date-editor.el-input__inner {
  width: 100%;
}

</style>
