<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="penCode">
          <template slot="label">{{ tmT("queryPenCode") }}</template>
          <el-input
            v-model="queryParams.penCode"
            :placeholder="tmT('queryPenCodePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ tmCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ tmCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['tradeMarket:isolationPen:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ tmCommon("add") }}</el-button>
          <el-button
            v-hasPermi="['tradeMarket:isolationPen:config']"
            type="warning"
            plain
            icon="el-icon-setting"
            size="mini"
            @click="handleOpenSetting"
          >{{ tmT("btnSetting") }}</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="tmT('colPenCode')" prop="penCode" align="center" width="120" />
        <el-table-column :label="tmT('colRemark')" prop="remark" align="center" min-width="200" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.remark || dash }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="tmCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['tradeMarket:isolationPen:query']" type="text" size="mini" @click="handleView(scope.row)">{{ tmCommon("view") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:isolationPen:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ tmCommon("edit") }}</el-button>
            <el-button v-hasPermi="['tradeMarket:isolationPen:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ tmCommon("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="560px" append-to-body @close="cancelPen">
      <el-form :key="formKey" ref="form" :model="form" label-width="120px">
        <el-form-item prop="penCode">
          <template slot="label">{{ tmT("formPenCode") }}</template>
          <el-input v-model="form.penCode" :placeholder="tmT('phPenCodeAuto')" :disabled="true" />
        </el-form-item>
        <el-form-item prop="remark" :rules="penFormRules.remark">
          <template slot="label">{{ tmT("formRemark") }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="3" :placeholder="tmT('phRemark')" maxlength="50" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPenForm">{{ tmCommon("ok") }}</el-button>
        <el-button @click="cancelPen">{{ tmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="tmCommon('viewTitle')" :visible.sync="viewOpen" width="560px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="tmT('formPenCode')">
          <span>{{ viewRow.penCode || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('formRemark')">
          <span>{{ viewRow.remark || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewCreateBy')">
          <span>{{ viewRow.createBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="tmT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['tradeMarket:isolationPen:edit']" type="primary" plain @click="openEditFromView">{{ tmCommon("edit") }}</el-button>
        <el-button v-hasPermi="['tradeMarket:isolationPen:remove']" type="danger" plain @click="handleDelete(viewRow)">{{ tmCommon("delete") }}</el-button>
        <el-button @click="viewOpen = false">{{ tmCommon("close") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="tmT('dialogSetting')" :visible.sync="settingOpen" width="560px" append-to-body @close="cancelSetting">
      <el-form ref="settingForm" :model="settingForm" label-width="140px">
        <el-form-item prop="defaultDays" :rules="settingFormRules.defaultDays">
          <template slot="label">{{ tmT("formDefaultDays") }}</template>
          <el-input-number
            v-model="settingForm.defaultDays"
            :min="minDefaultDays"
            :max="maxDefaultDays"
            :precision="0"
            :step="1"
            controls-position="right"
            style="width: 200px"
          />
          <span class="isolation-pen-unit">{{ tmT("unitDay") }}</span>
        </el-form-item>
        <el-form-item prop="remark" :rules="settingFormRules.remark">
          <template slot="label">{{ tmT("formSettingRemark") }}</template>
          <el-input
            v-model="settingForm.remark"
            type="textarea"
            :rows="3"
            :placeholder="tmT('phSettingRemark')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSettingForm">{{ tmCommon("ok") }}</el-button>
        <el-button @click="cancelSetting">{{ tmCommon("cancel") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tradeMarketLocaleMixin from "@/mixins/tradeMarketLocaleMixin"
import {
  listIsolationPen,
  getIsolationPen,
  addIsolationPen,
  updateIsolationPen,
  delIsolationPen,
  getIsolationSetting,
  updateIsolationSetting
} from "@/api/tradeMarket/isolationPen"

const MIN_DEFAULT_DAYS = 1
const MAX_DEFAULT_DAYS = 3650
const REMARK_MAX_LEN = 50

function createEmptyPenForm() {
  return {
    id: undefined,
    penCode: undefined,
    remark: undefined
  }
}

function createEmptySettingForm() {
  return {
    defaultDays: undefined,
    remark: undefined
  }
}

export default {
  name: "TradeMarketIsolationPen",
  mixins: [tradeMarketLocaleMixin],
  data() {
    return {
      tmNs: "isolationPen",
      loading: false,
      open: false,
      viewOpen: false,
      settingOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      minDefaultDays: MIN_DEFAULT_DAYS,
      maxDefaultDays: MAX_DEFAULT_DAYS,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        penCode: undefined
      },
      form: createEmptyPenForm(),
      settingForm: createEmptySettingForm()
    }
  },
  computed: {
    dash() {
      return this.$t("tradeMarket.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.tmT("dialogEdit") : this.tmT("dialogAdd")
    },
    penFormRules() {
      return {
        remark: [{ validator: this.validatePenRemark, trigger: "blur" }]
      }
    },
    settingFormRules() {
      return {
        defaultDays: [
          { required: true, message: this.tmT("ruleDefaultDaysRequired"), trigger: "blur" },
          { validator: this.validateDefaultDays, trigger: "blur" }
        ],
        remark: [{ validator: this.validateSettingRemark, trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    validatePenRemark(rule, value, callback) {
      if (value != null && String(value).trim().length > REMARK_MAX_LEN) {
        callback(new Error(this.tmT("ruleRemarkLen")))
        return
      }
      callback()
    },
    validateSettingRemark(rule, value, callback) {
      if (value != null && String(value).length > REMARK_MAX_LEN) {
        callback(new Error(this.tmT("ruleSettingRemarkLen")))
        return
      }
      callback()
    },
    validateDefaultDays(rule, value, callback) {
      if (value == null || value === "") {
        callback(new Error(this.tmT("ruleDefaultDaysRequired")))
        return
      }
      const n = Number(value)
      if (!Number.isInteger(n) || n < MIN_DEFAULT_DAYS || n > MAX_DEFAULT_DAYS) {
        callback(new Error(this.tmT("ruleDefaultDaysRange")))
        return
      }
      callback()
    },
    resetPenFormModel() {
      this.form = createEmptyPenForm()
    },
    resetSettingFormModel() {
      this.settingForm = createEmptySettingForm()
    },
    fillPenFormFromData(data) {
      this.form = Object.assign(createEmptyPenForm(), {
        id: data.id,
        penCode: data.penCode,
        remark: data.remark
      })
    },
    buildPenPayload() {
      const remark = this.form.remark
      return {
        remark: remark != null && String(remark).trim() ? String(remark).trim() : null
      }
    },
    getList() {
      this.loading = true
      listIsolationPen(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.penCode = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.formKey += 1
      this.resetPenFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getIsolationPen(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.fillPenFormFromData(data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    openEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getIsolationPen(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.tmT("confirmDelete", { code: row.penCode || row.id }))
        .then(() => delIsolationPen(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.tmCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    submitPenForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPenPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateIsolationPen(payload).then(() => {
            this.$modal.msgSuccess(this.tmCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addIsolationPen(payload).then(() => {
            this.$modal.msgSuccess(this.tmCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancelPen() {
      this.open = false
      this.resetPenFormModel()
    },
    handleOpenSetting() {
      this.resetSettingFormModel()
      getIsolationSetting()
        .then((res) => {
          const data = res.data
          if (data && (data.defaultDays != null || data.remark)) {
            this.settingForm = {
              defaultDays: data.defaultDays,
              remark: data.remark
            }
          }
          this.settingOpen = true
          this.$nextTick(() => {
            if (this.$refs.settingForm) {
              this.$refs.settingForm.clearValidate()
            }
          })
        })
        .catch(() => {
          this.settingOpen = true
        })
    },
    submitSettingForm() {
      this.$refs.settingForm.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = {
          defaultDays: this.settingForm.defaultDays,
          remark:
            this.settingForm.remark != null && String(this.settingForm.remark).trim()
              ? String(this.settingForm.remark).trim()
              : null
        }
        updateIsolationSetting(payload).then(() => {
          this.$modal.msgSuccess(this.tmT("msgSettingOk"))
          this.settingOpen = false
        })
      })
    },
    cancelSetting() {
      this.settingOpen = false
      this.resetSettingFormModel()
    }
  }
}
</script>

<style scoped>
.isolation-pen-unit {
  margin-left: 8px;
  color: #606266;
}
</style>
