<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('drugName') }}</template>
          <el-input
            v-model="queryParams.keyword"
            :placeholder="stdT('drugNamePh')"
            clearable
            style="width: 220px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="drugType">
          <template slot="label">{{ stdT('drugType') }}</template>
          <el-select v-model="queryParams.drugType" :placeholder="$t('breedingStd.common.pleaseSelect')" clearable style="width: 160px">
            <el-option
              v-for="item in drugTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </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="['withdrawalPeriod: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('colDrugName')" prop="drugName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="stdT('colDrugType')" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ drugTypeLabel(scope.row.drugType) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="stdT('colDays')" prop="withdrawalDays" align="center" width="110" />
        <el-table-column :label="stdT('colGuide')" prop="usageGuide" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="stdT('colEffect')" prop="drugEffect" align="center" min-width="140" :show-overflow-tooltip="true" />
        <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="['withdrawalPeriod:standard:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ $t('breedingStd.common.view') }}</el-button>
            <el-button
              v-hasPermi="['withdrawalPeriod: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="['withdrawalPeriod: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="['withdrawalPeriod: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="['withdrawalPeriod: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="620px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="100px">
        <el-form-item prop="drugName" :rules="formRules.drugName">
          <template slot="label">{{ stdT('formDrugName') }}</template>
          <el-input v-model="form.drugName" :placeholder="stdT('phDrugName')" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item prop="drugType" :rules="formRules.drugType">
          <template slot="label">{{ stdT('formDrugType') }}</template>
          <el-select v-model="form.drugType" :placeholder="$t('breedingStd.common.pleaseSelect')" style="width: 100%">
            <el-option
              v-for="item in drugTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="withdrawalDays" :rules="withdrawalDaysRules">
          <template slot="label">{{ stdT('formDays') }}</template>
          <el-input-number
            v-model="form.withdrawalDays"
            :min="1"
            :max="999"
            :step="1"
            :precision="0"
            controls-position="right"
            :placeholder="stdT('phDays')"
            style="width: 200px"
          />
          <span class="unit-suffix">{{ stdT('dayUnit') }}</span>
        </el-form-item>
        <el-form-item prop="usageGuide" :rules="formRules.usageGuide">
          <template slot="label">{{ stdT('formGuide') }}</template>
          <el-input
            v-model="form.usageGuide"
            type="textarea"
            :rows="4"
            :placeholder="stdT('phGuide')"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="drugEffect" :rules="formRules.drugEffect">
          <template slot="label">{{ stdT('formEffect') }}</template>
          <el-input
            v-model="form.drugEffect"
            type="textarea"
            :rows="4"
            :placeholder="stdT('phEffect')"
            maxlength="200"
            show-word-limit
          />
        </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="100px" size="small">
        <el-form-item :label="stdT('formDrugName')">
          <span>{{ viewRow.drugName }}</span>
        </el-form-item>
        <el-form-item :label="stdT('formDrugType')">
          <span>{{ drugTypeLabel(viewRow.drugType) }}</span>
        </el-form-item>
        <el-form-item :label="stdT('formDays')">
          <span>{{ viewRow.withdrawalDays != null ? viewRow.withdrawalDays + ' ' + stdT('dayUnit') : $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('formGuide')">
          <span class="pre-wrap">{{ viewRow.usageGuide || $t('breedingStd.status.dash') }}</span>
        </el-form-item>
        <el-form-item :label="stdT('formEffect')">
          <span class="pre-wrap">{{ viewRow.drugEffect || $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 {
  listWithdrawalPeriodStandard,
  getWithdrawalPeriodStandard,
  addWithdrawalPeriodStandard,
  updateWithdrawalPeriodStandard,
  delWithdrawalPeriodStandard,
  syncKbWithdrawalPeriodStandard,
  removeKbWithdrawalPeriodStandard
} from "@/api/breedingStandards/withdrawalPeriod"

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

export default {
  name: "WithdrawalPeriodStandard",
  mixins: [breedingStdLocaleMixin],
  data() {
    return {
      stdNs: "wp",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        keyword: undefined,
        drugType: undefined
      },
      form: {}
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogEdit ? this.stdT("dialogEdit") : this.stdT("dialogAdd")
    },
    drugTypeOptions() {
      return [1, 2, 3, 4].map((value) => ({ label: this.stdT("type" + value), value }))
    },
    withdrawalDaysRules() {
      return [
        {
          required: true,
          validator: (rule, value, callback) => {
            if (value === undefined || value === null || value === "") {
              callback(new Error(this.stdT("ruleDaysRequired")))
              return
            }
            const n = Number(value)
            if (!Number.isInteger(n) || n < 1 || n > 999) {
              callback(new Error(this.stdT("ruleDaysRange")))
              return
            }
            callback()
          },
          trigger: ["change", "blur"]
        }
      ]
    },
    formRules() {
      return {
        drugName: [
          { required: true, message: this.stdT("ruleDrugNameRequired"), trigger: "blur" },
          { min: 1, max: 20, message: this.stdT("ruleDrugNameLen"), trigger: "blur" }
        ],
        drugType: [{ required: true, message: this.stdT("ruleDrugTypeRequired"), trigger: "change" }],
        usageGuide: [
          { required: true, message: this.stdT("ruleGuideRequired"), trigger: "blur" },
          { min: 1, max: 200, message: this.stdT("ruleGuideLen"), trigger: "blur" }
        ],
        drugEffect: [
          { required: true, message: this.stdT("ruleEffectRequired"), trigger: "blur" },
          { min: 1, max: 200, message: this.stdT("ruleEffectLen"), trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    drugTypeLabel(val) {
      if (val == null || val === "") {
        return ""
      }
      const n = Number(val)
      const item = this.drugTypeOptions.find((o) => o.value === n)
      return item ? item.label : String(val)
    },
    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
      listWithdrawalPeriodStandard(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.queryParams.drugType = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    resetFormModel() {
      this.form = {
        id: undefined,
        drugName: undefined,
        drugType: undefined,
        withdrawalDays: undefined,
        usageGuide: undefined,
        drugEffect: undefined
      }
    },
    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
      }
      getWithdrawalPeriodStandard(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          drugName: data.drugName,
          drugType: data.drugType,
          withdrawalDays: data.withdrawalDays,
          usageGuide: data.usageGuide,
          drugEffect: data.drugEffect
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getWithdrawalPeriodStandard(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleSyncKb(row) {
      this.runSyncKbAfterConfirm(this.stdT("confirmSync"), () => syncKbWithdrawalPeriodStandard(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.stdT("msgSyncOk"))
          this.getList()
        })
        .catch(() => {})
    },
    handleRemoveKb(row) {
      this.runRemoveKbAfterConfirm(this.stdT("confirmRemoveKb"), () => removeKbWithdrawalPeriodStandard(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(() => delWithdrawalPeriodStandard(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.stdT("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const drugName = typeof this.form.drugName === "string" ? this.form.drugName.trim() : this.form.drugName
        const payload = {
          drugName,
          drugType: this.form.drugType,
          withdrawalDays: this.form.withdrawalDays,
          usageGuide: this.form.usageGuide,
          drugEffect: this.form.drugEffect
        }
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateWithdrawalPeriodStandard(payload).then(() => {
            this.$modal.msgSuccess(this.stdT("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addWithdrawalPeriodStandard(payload).then(() => {
            this.$modal.msgSuccess(this.stdT("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.unit-suffix {
  margin-left: 8px;
  color: #606266;
  font-size: 14px;
}
.pre-wrap {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
