<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="keyword">
          <template slot="label">{{ stdT('queryKeyword') }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="stdT('queryKeywordPh')"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('breedingStd.common.search') }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('breedingStd.common.reset') }}</el-button>
          <el-button
            v-hasPermi="['drugIncompatibility:standard:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ $t('breedingStd.common.add') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br />

    <el-card shadow="never">
      <el-table v-loading="loading" :data="tableList" border>
        <el-table-column :label="stdT('colMainDrug')" prop="mainDrugName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="stdT('colCompatResult')" prop="compatResult" align="center" min-width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.compatResult || $t('breedingStd.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="stdT('colCompanionCount')" prop="companionCount" align="center" width="110" />
        <el-table-column :label="stdT('colKb')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ kbSyncStatusText(scope.row.kbSyncStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="stdT('colCreate')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime ? parseTime(scope.row.createTime) : $t('breedingStd.status.dash') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="stdT('colOp')" align="center" class-name="small-padding fixed-width" width="280">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['drugIncompatibility:standard:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ $t('breedingStd.common.view') }}</el-button>
            <el-button
              v-hasPermi="['drugIncompatibility:standard:syncKb']"
              v-if="canSyncKb(scope.row)"
              type="text"
              size="mini"
              @click="handleSyncKb(scope.row)"
            >{{ $t('breedingStd.common.syncKb') }}</el-button>
            <el-button
              v-hasPermi="['drugIncompatibility:standard:removeKb']"
              v-if="canRemoveKb(scope.row)"
              type="text"
              size="mini"
              @click="handleRemoveKb(scope.row)"
            >{{ $t('breedingStd.common.removeKb') }}</el-button>
            <el-button
              v-hasPermi="['drugIncompatibility:standard:edit']"
              v-if="canEdit(scope.row)"
              type="text"
              size="mini"
              @click="handleEdit(scope.row)"
            >{{ $t('breedingStd.common.edit') }}</el-button>
            <el-button
              v-hasPermi="['drugIncompatibility:standard:remove']"
              v-if="canDelete(scope.row)"
              type="text"
              size="mini"
              @click="handleDelete(scope.row)"
            >{{ $t('breedingStd.common.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <el-dialog :title="dialogTitle" :visible.sync="open" width="640px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="108px">
        <el-form-item prop="mainDrugName" :rules="formRules.mainDrugName">
          <template slot="label">{{ stdT('formMainDrug') }}</template>
          <el-input
            v-model="form.mainDrugName"
            :placeholder="stdT('phMainDrug')"
            show-word-limit
            maxlength="20"
            @blur="touchCompanionsValidate"
          />
        </el-form-item>
        <el-form-item prop="compatResult" :rules="formRules.compatResult">
          <template slot="label">{{ stdT('formCompatResult') }}</template>
          <el-input
            v-model="form.compatResult"
            :placeholder="stdT('phCompatResult')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="companions" :rules="formRules.companions">
          <template slot="label">{{ stdT('formCompanions') }}</template>
          <div class="companion-block">
            <div v-for="(row, idx) in form.companions" :key="idx" class="companion-row">
              <el-input
                v-model="row.companionDrugName"
                :placeholder="stdT('phCompanion')"
                maxlength="20"
                show-word-limit
                class="companion-input"
                @input="touchCompanionsValidate"
              />
              <el-button
                type="text"
                icon="el-icon-delete"
                :disabled="form.companions.length <= 1"
                @click="removeCompanion(idx)"
              />
            </div>
            <el-button type="text" icon="el-icon-plus" @click="addCompanion">{{ stdT('addCompanionRow') }}</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ $t('breedingStd.common.ok') }}</el-button>
        <el-button @click="cancel">{{ $t('breedingStd.common.cancel') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="stdT('viewTitle')" :visible.sync="viewOpen" width="560px" append-to-body>
      <el-form label-width="108px" size="small">
        <el-form-item :label="stdT('formMainDrug')">
          <span>{{ viewRow.mainDrugName }}</span>
        </el-form-item>
        <el-form-item :label="stdT('formCompatResult')">
          <span>{{ viewRow.compatResult || $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('viewCompanions')">
          <ol v-if="viewCompanions.length" class="companion-view-list">
            <li v-for="(c, i) in viewCompanions" :key="i">{{ c.companionDrugName }}</li>
          </ol>
          <span v-else>{{ $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('colKb')">
          <span>{{ kbSyncStatusText(viewRow.kbSyncStatus) }}</span>
        </el-form-item>
        <el-form-item :label="stdT('viewKbDoc')">
          <span>{{ viewRow.kbDocId || $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('viewCreate')">
          <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('viewUpdate')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : $t('breedingStd.status.dash') }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ $t('breedingStd.common.close') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import breedingStdLocaleMixin from "@/mixins/breedingStdLocaleMixin"
import {
  listDrugIncompatibilityStandard,
  getDrugIncompatibilityStandard,
  addDrugIncompatibilityStandard,
  updateDrugIncompatibilityStandard,
  delDrugIncompatibilityStandard,
  syncKbDrugIncompatibilityStandard,
  removeKbDrugIncompatibilityStandard
} from "@/api/breedingStandards/drugIncompatibility"

const KB_SYNC_STATUS = { UNSYNCED: 0, SYNCED: 1 }

export default {
  name: "DrugIncompatibilityStandard",
  mixins: [breedingStdLocaleMixin],
  data() {
    return {
      stdNs: "dic",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.stdT("dialogEdit") : this.stdT("dialogAdd")
    },
    viewCompanions() {
      const list = this.viewRow.companions
      return Array.isArray(list) ? list : []
    },
    formRules() {
      return {
        mainDrugName: [
          { required: true, message: this.stdT("ruleMainRequired"), trigger: "blur" },
        ],
        compatResult: [{ max: 50, message: this.stdT("ruleCompatLen"), trigger: "blur" }],
        companions: [{ validator: this.validateCompanionsField, trigger: ["change", "blur"] }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    validateCompanionsField(rule, value, callback) {
      const list = this.form.companions || []
      const main = (this.form.mainDrugName || "").trim()
      const names = []
      for (let i = 0; i < list.length; i++) {
        const n = (list[i].companionDrugName || "").trim()
        if (!n) {
          callback(new Error(this.stdT("ruleCompanionEmpty")))
          return
        }
        if (n.length < 1 || n.length > 20) {
          callback(new Error(this.stdT("ruleCompanionLen")))
          return
        }
        if (n === main) {
          callback(new Error(this.stdT("ruleCompanionEqMain")))
          return
        }
        if (names.indexOf(n) !== -1) {
          callback(new Error(this.stdT("ruleCompanionDup")))
          return
        }
        names.push(n)
      }
      if (names.length < 1) {
        callback(new Error(this.stdT("ruleCompanionsRequired")))
        return
      }
      callback()
    },
    touchCompanionsValidate() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField("companions")
        }
      })
    },
    canEdit(row) {
      return Number(row.kbSyncStatus) === KB_SYNC_STATUS.UNSYNCED
    },
    canDelete(row) {
      return Number(row.kbSyncStatus) === KB_SYNC_STATUS.UNSYNCED
    },
    canSyncKb(row) {
      return Number(row.kbSyncStatus) === KB_SYNC_STATUS.UNSYNCED
    },
    canRemoveKb(row) {
      return Number(row.kbSyncStatus) === KB_SYNC_STATUS.SYNCED
    },
    getList() {
      this.loading = true
      listDrugIncompatibilityStandard(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total != null ? res.total : 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.keyword = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        mainDrugName: undefined,
        compatResult: undefined,
        companions: [{ companionDrugName: "" }]
      }
    },
    addCompanion() {
      this.form.companions.push({ companionDrugName: "" })
      this.touchCompanionsValidate()
    },
    removeCompanion(index) {
      if (this.form.companions.length <= 1) {
        return
      }
      this.form.companions.splice(index, 1)
      this.touchCompanionsValidate()
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => this.resetForm("form"))
    },
    handleEdit(row) {
      if (Number(row.kbSyncStatus) === KB_SYNC_STATUS.SYNCED) {
        this.$modal.msgWarning(this.stdT("ruleSyncedNoEdit"))
        return
      }
      if (!this.canEdit(row)) {
        return
      }
      getDrugIncompatibilityStandard(row.id).then((res) => {
        const data = res.data || {}
        const comps = Array.isArray(data.companions) && data.companions.length
          ? data.companions.map((c) => ({ companionDrugName: c.companionDrugName || "" }))
          : [{ companionDrugName: "" }]
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          mainDrugName: data.mainDrugName,
          compatResult: data.compatResult,
          companions: comps
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getDrugIncompatibilityStandard(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleSyncKb(row) {
      this.runSyncKbAfterConfirm(this.stdT("confirmSync"), () => syncKbDrugIncompatibilityStandard(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.stdT("msgSyncOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleRemoveKb(row) {
      this.runRemoveKbAfterConfirm(this.stdT("confirmRemoveKb"), () => removeKbDrugIncompatibilityStandard(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.stdT("msgOpOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleDelete(row) {
      if (!this.canDelete(row)) {
        this.$modal.msgWarning(this.stdT("ruleDeleteNeedRemoveKb"))
        return
      }
      this.$modal
        .confirm(this.stdT("confirmDelete", { id: row.id }))
        .then(() => delDrugIncompatibilityStandard(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.stdT("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildPayload() {
      const cr = (this.form.compatResult || "").trim()
      return {
        mainDrugName: (this.form.mainDrugName || "").trim(),
        compatResult: cr || undefined,
        companions: (this.form.companions || []).map((c) => ({
          companionDrugName: (c.companionDrugName || "").trim()
        }))
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateDrugIncompatibilityStandard(payload).then(() => {
            this.$modal.msgSuccess(this.stdT("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addDrugIncompatibilityStandard(payload).then(() => {
            this.$modal.msgSuccess(this.stdT("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.companion-block {
  width: 100%;
}
.companion-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}
.companion-input {
  flex: 1;
  margin-right: 4px;
}
.companion-view-list {
  margin: 0;
  padding-left: 20px;
}
</style>
