<template>
  <div v-loading="loading" class="add_reading-period-wrapper" style="display:flex;width: 100%;height: 100%;">
    <div
      class="reading-period-form"
      style="width:400px;height:100%;margin-right: 10px;"
    >
      <el-card shadow="never" style="height:571px;">
        <el-form
          ref="addOrUpdatePR"
          :model="form"
          size="small"
          :rules="rules"
          label-width="100px"
        >
          <!-- 阅片期类型 -->
          <el-form-item :label="$t('trials:rpManage:table:readingType')">
            <el-input :maxLength="$inputMax" v-model="form.ReadingSetTypeName" disabled style="width:100%;" />
          </el-form-item>
          <!-- 阅片期名称 -->
          <el-form-item :label="$t('trials:rpManage:table:readingName')" prop="ReadingPeriodName">
            <el-input :maxLength="$inputMax" v-model="form.ReadingPeriodName" style="width:100%;" />
          </el-form-item>
          <!-- 受试者范围 -->
          <el-form-item :label="$t('trials:rpManage:table:subjectRange')" prop="ReadingScope">
            <el-select v-model="form.ReadingScope" style="width:100%;">
              <el-option
                v-for="(item,index) of $d.ReadingScopeEnum"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 中心 -->
          <el-form-item v-if="form.ReadingScope === 1" :label="$t('trials:addRP:form:sites')" prop="SiteIds">
            <el-select v-model="form.SiteIds" filterable style="width:100%;" multiple>
              <el-option
                v-for="(item,index) of siteOptions"
                :key="index"
                :label="item.TrialSiteCode"
                :value="item.SiteId"
              />
            </el-select>
          </el-form-item>
          <!-- 条件 -->
          <el-form-item :label="$t('trials:addRP:form:condition')" prop="DeadlineCondition">
            <el-radio-group v-model="form.DeadlineCondition" style="width:100%;" @change="handleDeadlineCondition">
              <!-- 截止日期 -->
              <el-radio :label="0">{{ $t('trials:rpManage:table:expirationDate') }}</el-radio>
              <!-- 截止访视 -->
              <el-radio :label="1">{{ $t('trials:rpManage:table:expirationVisit') }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 截止日期 -->
          <el-form-item v-if="form.DeadlineCondition === 0" :label="$t('trials:rpManage:table:expirationDate')" prop="ExpirationDate">
            <el-date-picker
              v-model="form.ExpirationDate"
              type="date"
              value-format="yyyy-MM-dd"
              format="yyyy-MM-dd"

              style="width:100%;"
            />
          </el-form-item>
          <!-- 截止访视 -->
          <el-form-item v-if="form.DeadlineCondition === 1" :label="$t('trials:rpManage:table:expirationVisit')" prop="VisitStageId">
            <el-select
              v-model="form.VisitStageId"
              clearable
              style="width:100%;"
              @change="handleVisitChange"
            >
              <el-option
                v-for="item of visitPlanOptions"
                :key="item.VisitStageId"
                :label="item.VisitName"
                :value="item.VisitStageId"
              >
                <span style="float: left">{{ item.VisitName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <div style="text-align:right;margin-top:10px;">
            <el-form-item>
              <!-- 生成阅片期 -->
              <el-button size="small" type="primary" :loading="btnLoading" @click="getRPList">
                {{ $t('trials:addRP:button:createPR') }}
              </el-button>
            </el-form-item>
          </div>

        </el-form>
      </el-card>

    </div>
    <div class="result-table" style="flex:1;">
      <el-card shadow="never">

        <el-table
          ref="prList"
          v-loading="listLoading"
          :data="list"
          stripe
          height="455"
          @selection-change="handleSelectChange"
        >
          <el-table-column type="selection" align="left" width="45" />
          <el-table-column type="index" width="40" />
          <!-- 中心 -->
          <el-table-column
            prop="TrialSiteCode"
            :label="$t('trials:linkedRP:table:siteCode')"
          />
          <!-- 受试者 -->
          <el-table-column
            prop="SubjectCode"
            :label="$t('trials:linkedRP:table:subjectCode')"
          />
          <!-- 截止访视 -->
          <el-table-column
            prop="SubjectVisitName"
            :label="$t('trials:linkedRP:table:expirationVisit')"
          />
          <!-- 最晚拍片日期 -->
          <el-table-column
            prop="LatestScanDate"
            :label="$t('trials:linkedRP:table:latestScanDate')"
          >
            <template slot-scope="scope">
              {{ scope.row.LatestScanDate?moment(scope.row.LatestScanDate).format('YYYY-MM-DD'):'' }}
            </template>
          </el-table-column>
          <!-- 截止日期 -->
          <el-table-column
            prop="ExpirationDate"
            :label="$t('trials:linkedRP:table:expirationDate')"
          >
            <template slot-scope="scope">
              {{ scope.row.ExpirationDate?moment(scope.row.ExpirationDate).format('YYYY-MM-DD'):'' }}
            </template>
          </el-table-column>
          <!-- 阅片期名称 -->
          <el-table-column
            prop="ReadingPeriodName"
            :label="$t('trials:linkedRP:table:readingName')"
          />
          <!-- 生效时间 -->
          <el-table-column
            prop="EffectOfTime"
            :label="$t('trials:linkedRP:table:effectiveTime')"
          />
        </el-table>
        <!-- 分页组件 -->
        <div style="text-align:right">
          <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" :disabled="list.length === 0" @pagination="getReadingReriodList" />
        </div>

        <div style="text-align:right;padding-top: 10px;">
          <!-- 确认添加 -->
          <el-button size="small" type="primary" :disabled="selectArr.length === 0" @click="handleConfirm">
            {{ $t('trials:addRP:button:confirmAddPR') }}
          </el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getTrialSiteSelect, addOrUpdateReadingPeriodSet, getReadingVisitList, getPreviewTheReadingList, getPreviewTheReadingPlanList } from '@/api/trials'
import Pagination from '@/components/Pagination'
import moment from 'moment'
const searchDataDefault = () => {
  return {
    PageIndex: 1,
    PageSize: 20
  }
}
export default {
  name: 'AddOrEditRP',
  components: { Pagination },
  props: {
    trialReadingCriterionId: {
      type: String,
      default: ''
    },
    data: {
      type: Object,
      default() { return {} }
    }
  },
  data() {
    return {
      loading: false,
      btnLoading: false,
      visitPlanOptions: [],
      form: {
        Id: '',
        TrialId: '',
        ReadingSetType: null,
        ReadingSetTypeName: '',
        DeadlineCondition: 0,
        ReadingPeriodName: '',
        ReadingScope: null,
        SiteIds: [],
        VisitStageId: '',
        ExpirationDate: '',
        ExpirationVisitNum: null,
        PlanCount: 0
        // Remark: ''
      },
      rules: {
        ReadingPeriodName: [
          { required: true, message: this.$t('common:ruleMessage:specify'), trigger: 'blur' },
          { max: 50, message: `${this.$t('common:ruleMessage:maxLength')} 50` }
        ],
        ReadingScope: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        SiteIds: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        DeadlineCondition: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        ExpirationDate: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        VisitStageId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }]
        // Remark: [{ max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500` }]
      },
      siteOptions: [],
      trialId: '',
      listLoading: false,
      list: [],
      selectArr: [],
      searchData: searchDataDefault(),
      total: 0,
      moment
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.initForm()
  },
  methods: {
    async initForm() {
      this.loading = true
      await this.getSite()
      var param = {
        trialId: this.trialId,
        readingPeriodSetId: Object.keys(this.data).length > 0 ? this.data.Id : '',
        readingSetType: this.data.ReadingSetType,
        TrialReadingCriterionId: this.trialReadingCriterionId
      }
      const { Result } = await getReadingVisitList(param)
      this.visitPlanOptions = Result
      if (Object.keys(this.data).length > 0) {
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            this.form[k] = this.data[k]
          }
        }
        this.form.ReadingSetTypeName = this.$fd('ReadingSetType', this.data.ReadingSetType)

        this.form.DeadlineCondition = this.data.SubjectVisitName ? 1 : 0
        if (this.form.Id) {
          this.getReadingPeriodCheckedResult()
        }
      }
      this.form.TrialId = this.trialId
      this.loading = false
    },
    getRPList() {
      this.$refs.addOrUpdatePR.validate(valid => {
        if (!valid) return
        this.btnLoading = true
        this.getReadingPeriodResult()
      })
    },
    getReadingReriodList() {
      console.log(this.form)
      if (this.form.Id === '') {
        this.getReadingPeriodResult()
      } else {
        this.getReadingPeriodCheckedResult()
      }
    },
    getReadingPeriodResult() {
      this.listLoading = true
      var param = {
        SiteIds: this.form.ReadingScope === 1 ? this.form.SiteIds : [],
        TrialId: this.form.TrialId,
        ExpirationDate: this.form.ExpirationDate,
        ExpirationVisitNum: this.form.ExpirationVisitNum,
        VisitStageId: this.form.VisitStageId,
        ReadingPeriodName: this.form.ReadingPeriodName,
        ReadingSetType: this.form.ReadingSetType,
        ReadingScope: this.form.ReadingScope,
        TrialReadingCriterionId: this.trialReadingCriterionId
      }
      Object.assign(this.searchData, param)
      getPreviewTheReadingList(this.searchData).then(res => {
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.listLoading = false
        this.btnLoading = false
      })
        .catch(() => {
          this.listLoading = false
          this.btnLoading = false
        })
    },
    getReadingPeriodCheckedResult() {
      this.listLoading = true
      this.searchData.ReadingPeriodSetId = this.form.Id
      this.searchData.TrialReadingCriterionId = this.trialReadingCriterionId
      getPreviewTheReadingPlanList(this.searchData).then(res => {
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        this.listLoading = false
        this.$nextTick(() => {
          for (let i = 0; i < this.list.length; i++) {
            this.$refs['prList'].toggleRowSelection(this.list[i], true)
          }
        })
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 获取勾选行数据
    handleSelectChange(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].SubjectVisitId)
      }
      this.selectArr = arr
    },
    handleConfirm() {
      this.loading = true
      var params = Object.assign({}, this.form)
      params.subjectVisitIds = this.selectArr
      params.TrialReadingCriterionId = this.trialReadingCriterionId
      addOrUpdateReadingPeriodSet(params).then(res => {
        this.loading = false
        this.$emit('close')
        this.$emit('getList')
        this.$message.success(this.$t('common:message:savedSuccessfully'))
      }).catch(() => { this.loading = false })
    },
    handleVisitChange(val) {
      const selectArr = this.visitPlanOptions.filter(item => item.VisitStageId === val)
      if (selectArr.length > 0) {
        this.form.ExpirationVisitNum = selectArr[0].VisitNum
      } else {
        this.form.ExpirationVisitNum = null
      }
    },
    handleDeadlineCondition(val) {
      // 0：截止日期  1：截止访视
      if (val) {
        this.form.ExpirationDate = ''
      } else {
        this.form.VisitStageId = ''
        this.form.ExpirationVisitNum = null
      }
    },
    // 获取site下拉框数据
    getSite() {
      return new Promise((resolve, reject) => {
        getTrialSiteSelect(this.trialId).then(res => {
          this.siteOptions = res.Result
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    close() {
      this.$emit('close')
    }
  }
}
</script>
