<template>
  <div class="continuingTraining">
    <div class="title">
      <span>{{ $t('curriculumVitae:continuingTraining:title') }}</span>
      <el-button
        type="text"
        class="editBtn"
        @click.stop="openEdit"
        :disabled="!reviewerId"
      >
        {{ $t('common:button:add') }}
      </el-button>
    </div>
    <el-table
      :data="DATA"
      v-loading="loading"
      style="width: 100%"
      :header-cell-style="{ background: '#eee', color: '#606266' }"
    >
      <el-table-column
        prop="date"
        :label="$t('curriculumVitae:continuingTraining:table:time')"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.BeginDateStr }} ~ {{ scope.row.EndDateStr }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="Training"
        :label="$t('curriculumVitae:continuingTraining:table:type')"
      >
        <template slot-scope="scope">
          <span>{{ $fd('Training', Number(scope.row.Training)) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="Major"
        :label="$t('curriculumVitae:continuingTraining:table:direction')"
      >
        <template slot-scope="scope">
          <span>{{ isEN ? scope.row.Major : scope.row.MajorCN }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="school"
        :label="$t('curriculumVitae:continuingTraining:table:school')"
      >
        <template slot-scope="scope">
          <span>{{ isEN ? scope.row.School : scope.row.SchoolCN }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="City"
        :label="$t('curriculumVitae:continuingTraining:table:city')"
      >
        <template slot-scope="scope">
          <span>{{ isEN ? scope.row.City : scope.row.CityCN }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common:action:action')">
        <template slot-scope="scope">
          <el-button
            type="text"
            class="editBtn"
            @click.stop="openEdit(scope.row)"
          >
            {{ $t('common:button:edit') }}
          </el-button>
          <el-button
            type="text"
            class="editBtn"
            @click.stop="handleDel(scope.row)"
          >
            {{ $t('common:button:delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <base-model :config="model_cfg">
      <template slot="dialog-body">
        <el-form
          ref="continuingTrainingFrom"
          v-loading="loading"
          :model="form"
          :rules="rules"
          label-width="80px"
          size="small"
        >
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:time')"
            prop="BeginDate"
          >
            <el-date-picker
              clearable
              v-model="daterange"
              type="monthrange"
              value-format="yyyy-MM-dd"
              format="yyyy-MM"
              :range-separator="$t('curriculumVitae:daterange:rangeSeparator')"
              :start-placeholder="$t('curriculumVitae:daterange:startTime')"
              :end-placeholder="$t('curriculumVitae:daterange:endTime')"
              @change="changeTimeList"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:type')"
            prop="Training"
          >
            <el-select v-model="form.Training" clearable placeholder="">
              <el-option
                v-for="item in $d.Training"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:direction')"
            prop="Major"
            v-if="isEN"
          >
            <el-input
              v-model="form.Major"
              type="textarea"
              :rows="2"
              :maxlength="4000"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:directionEN')
              "
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="MajorCN"
            :label="$t('curriculumVitae:continuingTraining:form:direction')"
            v-else
          >
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.MajorCN"
              :maxlength="4000"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:direction')
              "
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:hospital')"
            prop="Hospital"
            v-if="isEN"
          >
            <el-autocomplete
              clearable
              class="inline-input"
              style="width: 100%"
              v-model="form.Hospital"
              :fetch-suggestions="querySearch"
              placeholder=""
            ></el-autocomplete>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:hospital')"
            prop="Hospital"
            v-else
          >
            <el-autocomplete
              clearable
              class="inline-input"
              style="width: 100%"
              v-model="form.HospitalCN"
              :fetch-suggestions="querySearch"
              placeholder=""
            ></el-autocomplete>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:school')"
            prop="School"
            v-if="isEN"
          >
            <el-input
              v-model="form.School"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:schoolEN')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="SchoolCN"
            :label="$t('curriculumVitae:continuingTraining:form:school')"
            v-else
          >
            <el-input
              v-model="form.SchoolCN"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:school')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:city')"
            prop="City"
            v-if="isEN"
          >
            <el-input
              v-model="form.City"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:City')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="CityCN"
            :label="$t('curriculumVitae:continuingTraining:form:city')"
            v-else
          >
            <el-input
              v-model="form.CityCN"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:CityCN')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
          <el-form-item
            :label="$t('curriculumVitae:continuingTraining:form:Country')"
            prop="Country"
            v-if="isEN"
          >
            <el-input
              v-model="form.Country"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:Country')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
          <el-form-item
            prop="CountryCN"
            :label="$t('curriculumVitae:continuingTraining:form:Country')"
            v-else
          >
            <el-input
              v-model="form.CountryCN"
              clearable
              :placeholder="
                $t('curriculumVitae:continuingTraining:placeholder:CountryCN')
              "
              :maxlength="400"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <el-button size="small" type="primary" @click="handleCancle">
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </template>
    </base-model>
  </div>
</template>
<script>
import BaseModel from '@/components/BaseModel'
import {
  addOrUpdatePostgraduateInfo,
  deletePostgraduateInfo,
} from '@/api/reviewers'
import store from '@/store'
import { mapGetters } from 'vuex'
const defaultForm = () => {
  return {
    BeginDate: '',
    EndDate: '',
    Training: '',
    Major: '',
    MajorCN: '',
    HospitalId: null,
    HospitalCN: null,
    Hospital: null,
    School: '',
    SchoolCN: '',
    City: '',
    CityCN: '',
    Country: '',
    CountryCN: '',
  }
}
export default {
  name: 'continuingTraining',
  components: { BaseModel },
  props: {
    DATA: {
      type: Array,
      required: true,
      default: () => {
        return []
      },
    },
    reviewerId: {
      type: String,
      default: '',
    },
    isEN: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      model_cfg: {
        visible: false,
        showClose: true,
        width: '600px',
        title: this.$t('curriculumVitae:continuingTraining:form:title'),
        appendToBody: true,
      },
      form: defaultForm(),
      rules: {
        BeginDate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        EndDate: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        Training: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: 'blur',
          },
        ],
        Major: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 4000,
            message: this.$t('form:rules:maxLength:4000'),
            trigger: 'blur',
          },
        ],
        MajorCN: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 4000,
            message: this.$t('form:rules:maxLength:4000'),
            trigger: 'blur',
          },
        ],
        City: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        CityCN: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        Country: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        CountryCN: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
      },
      loading: false,
      daterange: [],
      hospitalSelectList: [],
    }
  },
  computed: {
    ...mapGetters(['hospitalList']),
  },
  mounted() {
    store.dispatch('global/getHospital')
  },
  watch: {
    hospitalList: {
      handler() {
        if (!Array.isArray(this.hospitalList) || this.hospitalList.length <= 0)
          return false
        this.hospitalSelectList = []
        this.hospitalList.forEach((item) => {
          if (this.isEN) {
            this.hospitalSelectList.push({
              value: item.HospitalName,
              ...item,
            })
          } else {
            this.hospitalSelectList.push({
              value: item.HospitalNameCN,
              ...item,
            })
          }
        })
      },
      deep: true,
    },
  },
  methods: {
    querySearch(queryString, cb) {
      var hospitalList = this.hospitalSelectList
      var results = queryString
        ? hospitalList.filter(this.createFilter(queryString))
        : hospitalList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (hospitalList) => {
        if (this.isEN) {
          return (
            hospitalList.HospitalName.toLowerCase().indexOf(
              queryString.toLowerCase()
            ) >= 0
          )
        } else {
          return (
            hospitalList.HospitalNameCN.toLowerCase().indexOf(
              queryString.toLowerCase()
            ) >= 0
          )
        }
      }
    },
    openEdit(row) {
      this.form = defaultForm()
      this.daterange = []
      if (row) {
        Object.keys(this.form).forEach((key) => {
          if (row[key]) {
            this.form[key] = row[key]
          }
        })
        if (this.form.BeginDate && this.form.EndDate) {
          this.daterange = [this.form.BeginDate, this.form.EndDate]
        }
        if (this.form.Degree) {
          this.form.Degree = Number(this.form.Degree)
        }
        this.form.Id = row.Id
      }
      this.model_cfg.visible = true
    },
    handleCancle() {
      this.form = defaultForm()
      this.daterange = []
      this.model_cfg.visible = false
    },
    async handleSave() {
      try {
        let validate = await this.$refs.continuingTrainingFrom.validate()
        if (!validate) return false
        if (this.reviewerId) {
          this.form.DoctorId = this.reviewerId
        }
        let data = Object.assign({}, this.form)
        if (!this.hospitalList.find((item) => item.Id === data.HospitalId)) {
          data.Hospital = data.HospitalId
          data.HospitalId = null
        }
        this.loading = true
        let res = await addOrUpdatePostgraduateInfo(this.form)
        this.loading = false
        if (res.IsSuccess) {
          this.$emit('getInfo')
          this.model_cfg.visible = false
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    async handleDel(row) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:trials-list:table:isDeleted')
        )
        if (!confirm) return false
        this.loading = true
        let res = await deletePostgraduateInfo(row.Id)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
          this.$emit('getInfo')
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    changeTimeList() {
      if (this.daterange && this.daterange.length === 2) {
        this.form.BeginDate = this.daterange[0]
        this.form.EndDate = this.daterange[1]
      } else {
        this.form.BeginDate = null
        this.form.EndDate = null
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.continuingTraining {
  min-height: 100px;
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    font-weight: bold;
  }
}
.el-select,
.el-date-editor {
  width: 100%;
}
</style>