<!-- eslint-disable -->
<template>
  <el-form ref="trialForm" v-loading="loading" label-width="250px" :rules="trialFormRules"
    class="demo-ruleForm trial-Form" :model="trialForm" label-position="right" :inline="true">
    <el-row>
      <!-- 项目码 -->
      <el-form-item :label="$t('trials:trials-list:table:trialId')" prop="TrialCode" v-if="trialForm.Id !== ''">
        <el-input v-model="trialForm.TrialCode" disabled />
        <!-- <el-input v-model="trialForm.TrialCode" /> -->
      </el-form-item>
      <!-- 项目类型 -->
      <el-form-item :label="$t('trials:trials-list:form:trialType')" prop="TrialType">
        <el-radio-group v-model="trialForm.TrialType" :disabled="trialForm.Id !== ''">
          <el-radio v-for="item of $d.TrialType" :key="item.id" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 研究方案号 -->
      <el-form-item :label="$t('trials:trials-list:form:researchNumber')" prop="ResearchProgramNo">
        <el-input v-model="trialForm.ResearchProgramNo" clearable :disabled="TrialStatusStr === 'Ongoing'" />
      </el-form-item>
      <!-- 研究名称 -->
      <el-form-item :label="$t('trials:trials-list:table:researchName')" prop="ExperimentName">
        <el-input v-model="trialForm.ExperimentName" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" clearable />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 药物/器械名称 -->
      <el-form-item :label="$t('trials:trials-list:message:D/Dname')">
        <el-input v-model="trialForm.MedicineName" clearable />
      </el-form-item>
      <!-- 申办方 -->
      <el-form-item :label="$t('trials:trials-list:form:sponsor')" prop="Sponsor">
        <el-input v-model="trialForm.Sponsor" maxlength="200" clearable />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 研究者 -->
      <el-form-item :label="$t('trials:trials-list:form:investigator')" prop="HeadPI">
        <el-input v-model="trialForm.HeadPI" clearable />
      </el-form-item>
      <!-- 临床分期 -->
      <el-form-item :label="$t('trials:trials-list:form:phase')" prop="PhaseId">
        <el-select v-model="trialForm.PhaseId" @change="handlePhaseChange" clearable>
          <el-option v-for="item of $d.Trial_Phase" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 适应症 -->
      <el-form-item :label="$t('trials:trials-list:form:indication')">
        <el-input v-model="trialForm.Indication" clearable />
      </el-form-item>
      <!-- 阅片标准 -->
      <el-form-item :label="$t('trials:trials-list:form:criterion')" prop="CriterionTypeList">
        <el-select v-model="trialForm.CriterionTypeList" multiple clearable :disabled="TrialStatusStr === 'Ongoing'">
          <el-option v-for="item of CriterionTypeList" :key="item.Id" :label="item.CriterionName"
            :value="item.CriterionType" :title="item.Description" />
        </el-select>
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 课题组 -->
      <el-form-item :label="$t('trials:trials-list:form:HospitalGroupId')" prop="HospitalGroupId">
        <el-select v-model="trialForm.HospitalGroupId" clearable :disabled="TrialStatusStr === 'Ongoing'">
          <el-option v-for="item of hospitalGroupList" :key="item.Id" :label="item.Name" :value="item.Id" />
        </el-select>
      </el-form-item>
      <!-- CRO -->
      <el-form-item :label="$t('trials:trials-list:form:cro')" prop="Cro">
        <el-input v-model="trialForm.CRO" maxlength="200" clearable />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 联系人 -->
      <el-form-item :label="$t('trials:researchForm:form:contactor')">
        <el-input v-model="trialForm.ContactUser" clearable />
      </el-form-item>
      <!-- 电话 -->
      <el-form-item :label="$t('trials:trials-myinfo:form:phone')">
        <el-input v-model="trialForm.ContactPhone" type="number" clearable />
      </el-form-item>
    </el-row>
    <el-row>
      <!-- 项目周期 -->
      <el-form-item :label="$t('trials:trials-list:form:projectCycle')" prop="AuthorizationDuration">
        <div style="position: relative">
          <el-input v-model.number="trialForm.AuthorizationDuration" type="number" clearable :max="200" :min="1" />
        </div>
      </el-form-item>
      <!-- 到期日 -->
      <el-form-item :label="$t('trials:trials-list:table:dateAuthorized')" prop="visitNumberAuthorized">
        <el-date-picker v-model="trialForm.AuthorizationDate" value-format="yyyy-MM-dd" type="date" placeholder=""
          disabled>
        </el-date-picker>
      </el-form-item>
    </el-row>
    <el-row style="margin-left: 190px">
      <el-form-item label="">
        <el-button type="primary" :disabled="btnLoading" @click="handleCancel">
          {{ $t("trials:trials-list:form:cancel") }}
        </el-button>
        <el-button type="primary" :loading="btnLoading" @click="handleSave">
          {{ $t("trials:trials-list:form:save") }}
        </el-button>
      </el-form-item>
    </el-row>
  </el-form>
</template>
<script>
// import store from "@/store";
import { mapGetters, mapState } from "vuex";
import {
  getTrialInfoHir,
  addOrUpdateTrialHir,
  getSystemConfirmedCreiterionList,
} from "@/api/trials";
import {
  getHospitalGroupList
} from '@/api/admin.js'
import { getBasicDataSelects } from "@/api/dictionary/dictionary";
export default {
  name: "TrialForm",
  props: {
    trialId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      trialForm: {
        Id: "",
        TrialCode: "",
        TrialType: null,
        ResearchProgramNo: "",
        ExperimentName: "",
        HeadPI: "",
        CRO: "",
        Sponsor: "",
        MedicineName: "",
        PhaseId: "",
        Indication: "",
        ModalityIds: [],
        CriterionTypeList: [],
        ContactUser: "",
        ContactPhone: "",
        AuthorizationDuration: null,
        AuthorizationDate: null,
        HospitalGroupId: null
      },
      indicationGrouping: null,
      trialFormRules: {
        // 项目码
        HospitalGroupId: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
        ],
        // 项目码
        TrialCode: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
        ],
        // 授权时长
        AuthorizationDuration: [
          {
            required: true,
            message: this.$t(
              "trials:trials-list:formRule:enterDurationAuthorized"
            ),
            trigger: "blur",
          },
          {
            pattern: /^[1-9]\d*$/,
            message: this.$t(
              "trials:trials-list:formRule:notDecimalsAuthorized"
            ),
            trigger: "blur",
          },
          {
            type: "number",
            min: 1,
            max: 200,
            message: this.$t("trials:trials-list:formRule:minMaxAuthorized"),
            trigger: "blur",
          },
        ],
        // 阅片标准
        CriterionTypeList: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
        ],
        // 药物/器械名称
        MedicineName: [
          {
            max: 200,
            message: `${this.$t("common:ruleMessage:maxLength")} 200`,
            trigger: "blur",
          },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
            message: this.$t("trisals:trials-list:formRule:onlyEN"),
            trigger: "blur",
          },
        ],
        // 申办方
        Sponsor: [
          {
            max: 200,
            message: `${this.$t("common:ruleMessage:maxLength")} 200`,
            trigger: "blur",
          },
          // {
          //   pattern: /^[\u4e00-\u9fa5a-zA-Z\/\\]+$/,
          //   message: this.$t("trisals:trials-list:formRule:onlyEN"),
          //   trigger: "blur",
          // },
        ],
        TrialType: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
        ],
        ResearchProgramNo: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
          {
            max: 100,
            message: `${this.$t("common:ruleMessage:maxLength")} 100`,
          },
        ],
        ExperimentName: [
          {
            required: true,
            message: this.$t("common:ruleMessage:specify"),
            trigger: "blur",
          },
          {
            max: 500,
            message: `${this.$t("common:ruleMessage:maxLength")} 500`,
          },
        ],
        ModalityIds: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ["blur", "change"],
          },
        ],
        PhaseId: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ["blur", "change"],
          },
        ],
        Indication: [
          {
            required: true,
            message: this.$t("common:ruleMessage:select"),
            trigger: ["blur", "change"],
          },
        ],
      },
      btnLoading: false,
      loading: false,
      declarationNum: null,
      indicationNum: null,
      phaseNum: null,
      dictionaryList: {},
      CriterionTypeList: [], // 阅片标准列表
      TrialStatusStr: null, // 项目状态
      hospitalGroupList: []
    };
  },
  computed: {
    ...mapGetters(["sponsorList", "croList"]),
    ...mapState("user", ["isTestUser"]),
  },
  mounted() {
    this.initPage();
  },
  methods: {
    async getHospitalGroupList() {
      try {
        let res = await getHospitalGroupList({})
        if (res.IsSuccess) {
          this.hospitalGroupList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 获取阅片标准
    async getSystemConfirmedCreiterionList() {
      try {
        let res = await getSystemConfirmedCreiterionList();
        if (res.IsSuccess) {
          this.CriterionTypeList = res.Result;
        }
      } catch (err) {
        console.log(err);
      }
    },
    initForm() {
      this.loading = true;
      getTrialInfoHir(this.trialId)
        .then((res) => {
          this.loading = false;
          if (res.IsSuccess) {
            for (var item in this.trialForm) {
              res.Result[item] === "00000000-0000-0000-0000-000000000000"
                ? ""
                : this.$set(this.trialForm, item, res.Result[item]);
              if (item === "IndicationTypeId") {
                this.indicationGrouping = this.$d.IndicationType.filter(
                  (v) => v.id === res.Result[item]
                )[0].raw.ChildGroup;
              }
            }
            this.TrialStatusStr = res.Result.TrialStatusStr;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    handleSave() {
      this.$refs.trialForm.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          var params = JSON.parse(JSON.stringify(this.trialForm));
          addOrUpdateTrialHir(params)
            .then((res) => {
              this.btnLoading = false;
              if (!this.trialForm.Id) {
                this.trialForm.Id = res.Result;
                this.$message.success(
                  this.$t("trials:trials-list:message:addedSuccessfully")
                );
              } else {
                this.$message.success(
                  this.$t("trials:trials-list:message:updatedSuccessfully")
                );
              }

              this.$emit("getList");
              this.$emit("closeDialog");
            })
            .catch(() => {
              this.btnLoading = false;
            });
        }
      });
    },
    handleCancel() {
      this.$emit("closeDialog");
      // this.$refs['trialForm'].resetFields()
    },
    handleDeclarationTypeChange(val) {
      if (val.length === 1) {
        // this.declarationNum = this.dictionaryList.DeclarationType.filter(item => item.Idd === val)[0].ShowOrder
        this.declarationNum = this.$d.DeclarationType.filter(
          (item) => item.value === val[0]
        )[0].raw.ShowOrder;
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode];
          ids[2] = this.declarationNum;
          this.trialForm.TrialCode = ids.join("");
        }
      } else {
        this.declarationNum = "X";
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode];
          ids[2] = this.declarationNum;
          this.trialForm.TrialCode = ids.join("");
        }
      }
    },
    handleIndicationTypeChange(val) {
      this.indicationGrouping = null;
      if (val) {
        // this.indicationNum = this.dictionaryList.IndicationType.filter(item => item.Id === val)[0].ShowOrder
        this.indicationNum = this.$d.IndicationType.filter(
          (item) => item.id === val
        )[0].raw.ShowOrder;
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode];
          ids[3] = this.indicationNum;
          this.trialForm.TrialCode = ids.join("");
        }
        this.indicationGrouping = this.$d.IndicationType.filter(
          (item) => item.id === val
        )[0].raw.ChildGroup;
      }
      this.trialForm.Indication = null;
    },
    handlePhaseChange(val) {
      if (val) {
        // const phase = this.dictionaryList['Trial_Phase']
        // this.phaseNum = phase.filter(item => item.Id === val)[0].ShowOrder
        this.phaseNum = this.$d.Trial_Phase.filter(
          (item) => item.id === val
        )[0].raw.ShowOrder;
        if (this.trialForm.Id) {
          const ids = [...this.trialForm.TrialCode];
          ids[4] = this.phaseNum;
          this.trialForm.TrialCode = ids.join("");
        }
      }
    },
    handleExpectedPatientsChange(val) {
      this.trialForm.PlanVisitCount = val * this.trialForm.TimePointsPerPatient;
    },
    handleTpPerPatientChange(val) {
      this.trialForm.PlanVisitCount = val * this.trialForm.ExpectedPatients;
    },
    async initPage() {
      this.loading = true;
      // await this.getDicData();
      // await store.dispatch("global/getSponsorList");
      // await store.dispatch("global/getCROList");
      if (this.trialId) {
        this.trialForm.Id = this.trialId;
        this.initForm();
      }
      this.getSystemConfirmedCreiterionList();
      this.getHospitalGroupList()
      this.loading = false;
    },
    getDicData() {
      getBasicDataSelects([
        "DeclarationType",
        "IndicationType",
        "Modality",
        "ReviewMode",
        "ReviewType",
        "Trial_Phase",
      ]).then((res) => {
        this.dictionaryList = { ...res.Result };
      });
    },
  },
};
</script>
<style>
.trial-Form .el-input,
.trial-Form .el-select,
.trial-Form .el-radio-group,
.trial-Form .el-input-number,
.trial-Form .el-textarea {
  width: 340px;
}

.trial-Form .el-col .el-input {
  width: 165px;
  margin-right: 10px;
}
</style>
