<template>
  <div class="form-container">
    <el-card class="box-card">
      <div style="width: 80%">
        <el-form
          ref="employmentForm"
          v-loading="loading"
          :rules="employmentRules"
          :model="employmentForm"
          class="demo-ruleForm"
          label-width="150px"
        >
          <el-row>
            <el-col :span="14">
              <el-form-item
                :label="$t('system:reviewer:label:Hospital')"
                prop="HospitalName"
              >
                <el-autocomplete
                  clearable
                  class="inline-input"
                  style="width: 100%"
                  v-model="employmentForm.HospitalName"
                  :fetch-suggestions="querySearch"
                  @select="handleSelect"
                  placeholder="Please specify in English"
                  @change="handleChange"
                ></el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item prop="HospitalNameCN">
                <el-autocomplete
                  clearable
                  class="inline-input"
                  style="width: 100%"
                  v-model="employmentForm.HospitalNameCN"
                  :fetch-suggestions="querySearchCN"
                  @select="handleSelect"
                  placeholder="请用中文注明"
                  @change="handleChange"
                ></el-autocomplete>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="14">
              <el-form-item
                :label="$t('system:reviewer:label:AffiliatedUniversity')"
                prop="UniversityAffiliated"
              >
                <el-input
                  v-model="employmentForm.UniversityAffiliated"
                  type="textarea"
                  autosize
                  placeholder="Please specify in English"
                  size="small"
                  :maxlength="4000"
                />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item prop="UniversityAffiliated">
                <el-input
                  v-model="employmentForm.UniversityAffiliatedCN"
                  type="textarea"
                  autosize
                  placeholder="请用中文注明"
                  size="small"
                  :maxlength="4000"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item :label="$t('system:reviewer:label:City')">
                <el-input
                  v-model="employmentForm.City"
                  size="small"
                  placeholder="Please specify in English"
                />
              </el-form-item>
            </el-col>
            <el-col :span="14">
              <el-form-item>
                <el-input
                  v-model="employmentForm.CityCN"
                  size="small"
                  placeholder="请用中文注明"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- <el-row>
            <el-col :span="14">
              <el-form-item :label="$t('system:reviewer:label:State/Province')">
                <el-input
                  disabled
                  v-model="Province"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item :label="$t('system:reviewer:label:Country')">
                <el-input
                  disabled
                  v-model="Country"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
          </el-row> -->

          <el-row>
            <el-col :span="14">
              <el-form-item
                :label="$t('system:reviewer:label:Department')"
                prop="DepartmentId"
              >
                <el-select
                  v-model="employmentForm.DepartmentId"
                  placeholder="select"
                  :disabled="$route.query.ReviewStatus === '1'"
                  style="width: 100%"
                  size="small"
                >
                  <!-- <el-option
                    v-for="(key,value) of dictionaryList.Department"
                    :key="key"
                    :label="key"
                    :value="value"
                  /> -->
                  <el-option
                    v-for="item of dictionaryList.Department"
                    :key="item.Id"
                    :label="item.Value"
                    :value="item.Id"
                  />
                  <el-option
                    :label="$t('curriculumVitae:selectLabel:Other')"
                    :value="otherId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                v-if="employmentForm.DepartmentId === otherId"
                class="other-item"
                prop="DepartmentOther"
              >
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.DepartmentOther"
                  placeholder="Please specify (required)"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                v-if="employmentForm.DepartmentId === otherId"
                class="other-item"
                prop="DepartmentOtherCN"
              >
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.DepartmentOtherCN"
                  placeholder="请用中文注明"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="14">
              <el-form-item
                :label="$t('system:reviewer:label:Rank')"
                prop="RankId"
              >
                <el-select
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.RankId"
                  placeholder="select"
                  @change="RankChange"
                  style="width: 100%"
                  size="small"
                >
                  <!-- <el-option
                    v-for="(key,value) of dictionaryList.Rank"
                    :key="key"
                    :label="key"
                    :value="value"
                  /> -->
                  <el-option
                    v-for="item of $d.Rank"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id"
                  />
                  <!--                  <el-option label="Other" :value="otherId" />-->
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                v-if="
                  $fd('Rank', employmentForm.RankId, 'id') ===
                  $t('curriculumVitae:selectLabel:Other')
                "
                class="other-item"
                prop="RankOther"
              >
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.RankOther"
                  placeholder="Please specify"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item
                v-if="
                  $fd('Rank', employmentForm.RankId, 'id') ===
                  $t('curriculumVitae:selectLabel:Other')
                "
                class="other-item"
                prop="RankOtherCN"
              >
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.RankOtherCN"
                  placeholder="请用中文注明"
                  size="small"
                  :maxlength="400"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item
                :label="$t('system:reviewer:label:WorkPartTime')"
                prop="WorkPartTime"
              >
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.WorkPartTime"
                  type="textarea"
                  :rows="2"
                  :placeholder="
                    $t('curriculumVitae:info:form:placeholder:partTimeJob')
                  "
                  size="small"
                  :maxlength="4000"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item prop="WorkPartTimeEn">
                <el-input
                  :disabled="$route.query.ReviewStatus === '1'"
                  v-model="employmentForm.WorkPartTimeEn"
                  type="textarea"
                  :rows="2"
                  :placeholder="
                    $t('curriculumVitae:info:form:placeholder:partTimeJobEN')
                  "
                  size="small"
                  :maxlength="4000"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button
              type="primary"
              :disabled="isDisabled || $route.query.ReviewStatus === '1'"
              size="small"
              @click="handleSave"
              >{{ $t('common:button:save') }}</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>
<script>
import { getEmploymentInfo, updateEmploymentInfo } from '@/api/reviewers'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
import store from '@/store'
import { mapGetters } from 'vuex'
export default {
  name: 'Employment',
  props: {
    reviewerId: {
      type: String,
    },
  },
  data() {
    const RankIndication = (rule, value, callback) => {
      if (value === this.$t('curriculumVitae:selectLabel:Other')) {
        if (!this.trialForm.IndicationOther) {
          return callback(new Error('请输入适应症'))
        }
      }
      callback()
    }
    const PhysicianIndication = (rule, value, callback) => {
      if (value === this.$t('curriculumVitae:selectLabel:Other')) {
        if (!this.trialForm.IndicationOther) {
          return callback(new Error('请输入适应症'))
        }
      }
      callback()
    }
    return {
      employmentForm: {
        Id: this.$route.query.Id || this.reviewerId,
        DepartmentId: '',
        DepartmentOther: '',
        DepartmentOtherCN: '',
        RankId: '',
        RankOther: '',
        RankOtherCN: '',
        PositionId: '',
        PositionOther: '',
        PositionOtherCN: '',
        HospitalId: '',
        PhysicianId: '',
        Physician: '',
        PhysicianCN: '',
        PhysicianOriginal: null,
        HospitalName: '',
        HospitalNameCN: '',
        WorkPartTime: null,
        WorkPartTimeEn: null,
        UniversityAffiliated: null,
        UniversityAffiliatedCN: null,
        City: null,
        CityCN: null,
      },
      UniversityAffiliated: '',
      City: '',
      Province: '',
      Country: '',
      employmentRules: {
        HospitalName: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        HospitalNameCN: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur', 'change'],
          },
        ],
        DepartmentId: [
          {
            required: true,
            message: 'Please select department',
            trigger: 'blur',
          },
        ],
        DepartmentOther: [
          { required: true, message: 'Please specify', trigger: 'blur' },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        DepartmentOtherCN: [
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        RankId: [
          { required: true, message: 'Please select rank', trigger: 'blur' },
        ],
        RankOther: [
          { required: true, message: 'Please select rank', trigger: 'blur' },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        RankOtherCN: [
          { required: true, message: 'Please select rank', trigger: 'blur' },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        PhysicianId: [
          {
            required: true,
            message: 'Please select Physician',
            trigger: 'blur',
          },
        ],
        Physician: [
          {
            required: true,
            message: 'Please select Physician',
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        PhysicianCN: [
          {
            required: true,
            message: 'Please select Physician',
            trigger: 'blur',
          },
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        PositionId: [
          {
            required: true,
            message: 'Please select position',
            trigger: 'blur',
          },
        ],
        PositionOther: [
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        PositionOtherCN: [
          {
            max: 400,
            message: this.$t('form:rules:maxLength:400'),
            trigger: 'blur',
          },
        ],
        HospitalId: [
          {
            required: true,
            message: 'Please select hospital',
            trigger: 'blur',
          },
        ],
      },
      isDisabled: false,
      selectId: '00000000-0000-0000-0000-000000000000',
      otherId: 'ef84e9cb-f1a6-49d7-b6da-34be2c12abd5',
      loading: false,
      dictionaryList: {},
      hospitalSelectList: [],
      hospitalSelectListCN: [],
    }
  },
  computed: {
    ...mapGetters(['hospitalList']),
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
  },
  mounted() {
    this.initEmployment()
  },
  watch: {
    hospitalList: {
      handler() {
        if (!Array.isArray(this.hospitalList) || this.hospitalList.length <= 0)
          return false
        this.hospitalSelectList = []
        this.hospitalList.forEach((item) => {
          this.hospitalSelectList.push({
            value: item.HospitalName,
            ...item,
          })
          this.hospitalSelectListCN.push({
            value: item.HospitalNameCN,
            ...item,
          })
        })
      },
      deep: true,
    },
  },
  methods: {
    handleSelect(value) {
      const item = value
      if (item) {
        this.employmentForm.HospitalName = item.HospitalName
        this.employmentForm.HospitalNameCN = item.HospitalNameCN
        this.employmentForm.UniversityAffiliated = item.UniversityAffiliated
        this.employmentForm.City = item.City
        this.employmentForm.UniversityAffiliatedCN = item.UniversityAffiliatedCN
        this.employmentForm.CityCN = item.CityCN
      } else {
        this.employmentForm.UniversityAffiliated = null
        this.employmentForm.City = null
        this.employmentForm.UniversityAffiliatedCN = null
        this.employmentForm.CityCN = null
      }
    },
    handleChange(v) {
      if (v) return
      this.employmentForm.UniversityAffiliated = null
      this.employmentForm.City = null
      this.employmentForm.UniversityAffiliatedCN = null
      this.employmentForm.CityCN = null
    },
    querySearch(queryString, cb) {
      var hospitalList = this.hospitalSelectList
      var results = queryString
        ? hospitalList.filter(this.createFilter(queryString))
        : hospitalList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    querySearchCN(queryString, cb) {
      var hospitalList = this.hospitalSelectListCN
      var results = queryString
        ? hospitalList.filter(this.createFilter(queryString, false))
        : hospitalList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString, isEN = true) {
      return (hospitalList) => {
        if (isEN) {
          return (
            hospitalList.HospitalName.toLowerCase().indexOf(
              queryString.toLowerCase()
            ) >= 0
          )
        } else {
          return (
            hospitalList.HospitalNameCN.toLowerCase().indexOf(
              queryString.toLowerCase()
            ) >= 0
          )
        }
      }
    },
    RankChange(val) {
      var o = this.$d.Rank.find((v) => {
        return v.id === val
      })
      if (o.label === this.$t('curriculumVitae:selectLabel:Other')) {
        this.employmentForm.RankOther = ''
        this.employmentForm.RankOtherCN = ''
      } else {
        this.employmentForm.RankOther = o.raw.Value
        this.employmentForm.RankOtherCN = o.raw.ValueCN
      }
    },
    PhysicianChange(val) {
      var o = this.$d.PhysicianOriginal.find((v) => {
        return v.id === val
      })
      if (o.label === this.$t('curriculumVitae:selectLabel:Other')) {
        this.employmentForm.Physician = ''
        this.employmentForm.PhysicianCN = ''
      } else {
        this.employmentForm.Physician = o.raw.Value
        this.employmentForm.PhysicianCN = o.raw.ValueCN
      }
    },
    handleSave() {
      this.$refs.employmentForm.validate((valid) => {
        if (valid) {
          this.loading = true
          this.isDisabled = true
          const param = {}
          // var o = this.$d.PhysicianOriginal.find(v => {
          //   return v.id === this.employmentForm.PhysicianId
          // })
          param.Id = this.$route.query.Id || this.reviewerId
          param.DepartmentId = this.employmentForm.DepartmentId
          param.WorkPartTime = this.employmentForm.WorkPartTime
          param.WorkPartTimeEn = this.employmentForm.WorkPartTimeEn
          param.DepartmentOther =
            this.employmentForm.DepartmentId === this.otherId
              ? this.employmentForm.DepartmentOther
              : ''
          param.DepartmentOtherCN =
            this.employmentForm.DepartmentId === this.otherId
              ? this.employmentForm.DepartmentOtherCN
              : ''
          param.RankId = this.employmentForm.RankId
          param.RankOther =
            this.employmentForm.RankId === this.otherId
              ? this.employmentForm.RankOther
              : ''
          param.RankOtherCN =
            this.employmentForm.RankId === this.otherId
              ? this.employmentForm.RankOtherCN
              : ''
          // param.PhysicianId = this.employmentForm.PhysicianId
          // param.Physician = o.label !== '其它' && o.label !== 'Other' ? o.raw.Value : this.employmentForm.Physician
          // param.PhysicianCN = o.label !== '其它' && o.label !== 'Other' ? o.raw.ValueCN : this.employmentForm.PhysicianCN
          param.PositionId = this.employmentForm.PositionId
          param.PositionOther =
            this.employmentForm.PositionId === this.otherId
              ? this.employmentForm.PositionOther
              : ''
          param.PositionOtherCN =
            this.employmentForm.PositionId === this.otherId
              ? this.employmentForm.PositionOtherCN
              : ''
          param.HospitalId = this.employmentForm.HospitalId

          param.HospitalName = this.employmentForm.HospitalName
          param.HospitalNameCN = this.employmentForm.HospitalNameCN
          param.UniversityAffiliated = this.employmentForm.UniversityAffiliated
          param.UniversityAffiliatedCN =
            this.employmentForm.UniversityAffiliatedCN
          param.City = this.employmentForm.City
          param.CityCN = this.employmentForm.CityCN

          updateEmploymentInfo(param)
            .then((res) => {
              this.isDisabled = false
              this.loading = false
              this.$message.success('Saved successfully')
              if (!this.id) {
                this.employmentForm.Id = res.Result
              }
            })
            .catch(() => {
              this.isDisabled = false
              this.loading = false
            })
        }
      })
    },
    initForm() {
      const id = this.$route.query.Id || this.reviewerId
      if (id) {
        this.loading = true
        getEmploymentInfo(id)
          .then((res) => {
            const {
              PhysicianId,
              Physician,
              PhysicianCN,
              DepartmentId,
              DepartmentOther,
              DepartmentOtherCN,
              RankId,
              RankOther,
              RankOtherCN,
              PositionId,
              PositionOther,
              PositionOtherCN,
              HospitalId,
              HospitalName,
              HospitalNameCN,
              WorkPartTime,
              WorkPartTimeEn,
              UniversityAffiliated,
              UniversityAffiliatedCN,
              City,
              CityCN,
            } = res.Result
            this.employmentForm.HospitalName = HospitalName
            this.employmentForm.HospitalNameCN = HospitalNameCN
            this.employmentForm.UniversityAffiliated = UniversityAffiliated
            this.employmentForm.UniversityAffiliatedCN = UniversityAffiliatedCN
            this.employmentForm.City = City
            this.employmentForm.CityCN = CityCN

            this.employmentForm.WorkPartTime = WorkPartTime
            this.employmentForm.WorkPartTimeEn = WorkPartTimeEn
            this.employmentForm.Id = id
            this.employmentForm.DepartmentId =
              DepartmentId === this.selectId ? '' : DepartmentId
            this.employmentForm.DepartmentOther = DepartmentOther
            this.employmentForm.DepartmentOtherCN = DepartmentOtherCN
            this.employmentForm.RankId = RankId === this.selectId ? '' : RankId
            this.employmentForm.RankOther = RankOther
            this.employmentForm.RankOtherCN = RankOtherCN
            this.employmentForm.PositionId =
              PositionId === this.selectId ? '' : PositionId
            this.employmentForm.PositionOther = PositionOther
            this.employmentForm.PhysicianId = PhysicianId
            this.employmentForm.Physician = Physician
            this.employmentForm.PhysicianCN = PhysicianCN
            this.employmentForm.PositionOtherCN = PositionOtherCN
            this.employmentForm.HospitalId =
              HospitalId === this.selectId ? '' : HospitalId
            this.handleHospitalChange(this.employmentForm.HospitalId)
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      }
    },
    handleHospitalChange(value) {
      const item = this.hospitalList.filter((item) => item.Id === value)
      if (item.length) {
        this.UniversityAffiliated = this.isEN
          ? item[0].UniversityAffiliated
          : item[0].UniversityAffiliatedCN
        this.City = this.isEN ? item[0].City : item[0].CityCN
        this.Province = this.isEN ? item[0].Province : item[0].ProvinceCN
        this.Country = this.isEN ? item[0].Country : item[0].CountryCN
      }
    },
    async initEmployment() {
      await this.getDicData()
      await store.dispatch('global/getHospital')
      this.initForm()
    },
    getDicData() {
      getBasicDataSelects(['Department', 'Rank', 'Position']).then((res) => {
        this.dictionaryList = { ...res.Result }
      })
    },
  },
}
</script>
<style lang="scss">
.other-item .el-form-item__content {
  margin-left: 80px !important;
}
</style>
