<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="sendDateRange">
          <template slot="label">{{ dhT("querySendDate") }}</template>
          <el-date-picker
            v-model="queryParams.sendDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            :range-separator="dhT('sendRangeSeparator')"
            :start-placeholder="dhT('sendRangeStartPh')"
            :end-placeholder="dhT('sendRangeEndPh')"
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item prop="receiverName">
          <template slot="label">{{ dhT("queryReceiverName") }}</template>
          <el-input
            v-model="queryParams.receiverName"
            :placeholder="dhT('queryReceiverNamePh')"
            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">{{ dhCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dhCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['dataHub:dataSendRecord:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ dhCommon("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="dhT('colSendTime')" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.sendTime ? parseTime(scope.row.sendTime) : dash }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dhT('colSendContent')" prop="sendContent" align="center" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column :label="dhT('colReceiverName')" prop="receiverName" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="dhT('colReceiverAddress')" prop="receiverAddress" align="center" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column :label="dhCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['dataHub:dataSendRecord:query']" type="text" size="mini" @click="handleView(scope.row)">{{ dhCommon("view") }}</el-button>
            <el-button v-hasPermi="['dataHub:dataSendRecord:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ dhCommon("edit") }}</el-button>
            <el-button v-hasPermi="['dataHub:dataSendRecord:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ dhCommon("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="720px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="130px">
        <el-form-item prop="sendTime" :rules="formRules.sendTime">
          <template slot="label">{{ dhT("formSendTime") }}</template>
          <el-date-picker
            v-model="form.sendTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            :placeholder="dhCommon('pleaseInput')"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item prop="sendContent" :rules="formRules.sendContent">
          <template slot="label">{{ dhT("formSendContent") }}</template>
          <el-input
            v-model="form.sendContent"
            type="textarea"
            :rows="4"
            :placeholder="dhT('phSendContent')"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>
        <el-form-item prop="receiverName" :rules="formRules.receiverName">
          <template slot="label">{{ dhT("formReceiverName") }}</template>
          <el-input v-model="form.receiverName" :placeholder="dhT('phReceiverName')" maxlength="128" show-word-limit />
        </el-form-item>
        <el-form-item prop="receiverAddress" :rules="formRules.receiverAddress">
          <template slot="label">{{ dhT("formReceiverAddress") }}</template>
          <el-input v-model="form.receiverAddress" :placeholder="dhT('phReceiverAddress')" maxlength="512" show-word-limit />
        </el-form-item>
        <el-form-item prop="remark" :rules="formRules.remark">
          <template slot="label">{{ dhT("formRemark") }}</template>
          <el-input v-model="form.remark" type="textarea" :rows="2" :placeholder="dhT('phRemark')" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ dhCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ dhCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dhCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="130px" size="small">
        <el-form-item :label="dhT('formSendTime')">
          <span>{{ viewRow.sendTime ? parseTime(viewRow.sendTime) : dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('formSendContent')">
          <span class="dsr-pre">{{ viewRow.sendContent || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('formReceiverName')">
          <span>{{ viewRow.receiverName || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('formReceiverAddress')">
          <span class="dsr-pre">{{ viewRow.receiverAddress || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('formRemark')">
          <span>{{ viewRow.remark || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('viewCreateBy')">
          <span>{{ viewRow.createBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="dhT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ dhCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dataHubLocaleMixin from "@/mixins/dataHubLocaleMixin"
import {
  listDataSendRecord,
  getDataSendRecord,
  addDataSendRecord,
  updateDataSendRecord,
  delDataSendRecord
} from "@/api/dataHub/dataSendRecord"

export default {
  name: "DataSendRecord",
  mixins: [dataHubLocaleMixin],
  data() {
    return {
      dhNs: "dataSendRecord",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sendDateRange: null,
        receiverName: undefined
      },
      form: {}
    }
  },
  computed: {
    dash() {
      return this.$t("dataHub.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.dhT("dialogEdit") : this.dhT("dialogAdd")
    },
    formRules() {
      return {
        sendTime: [{ required: true, message: this.dhT("ruleSendTimeRequired"), trigger: "change" }],
        sendContent: [
          { required: true, message: this.dhT("ruleSendContentRequired"), trigger: "blur" },
          { validator: this.validateSendContent, trigger: "blur" }
        ],
        receiverName: [
          { required: true, message: this.dhT("ruleReceiverNameRequired"), trigger: "blur" },
          { validator: this.validateReceiverName, trigger: "blur" }
        ],
        receiverAddress: [
          { required: true, message: this.dhT("ruleReceiverAddressRequired"), trigger: "blur" },
          { validator: this.validateReceiverAddress, trigger: "blur" }
        ],
        remark: [{ validator: this.validateRemark, trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetFormModel() {
      this.form = {
        id: undefined,
        sendTime: undefined,
        sendContent: undefined,
        receiverName: undefined,
        receiverAddress: undefined,
        remark: undefined
      }
    },
    defaultSendTime() {
      return this.parseTime(new Date(), "{y}-{m}-{d} {h}:{i}:{s}")
    },
    validateSendContent(rule, value, callback) {
      const text = value != null ? String(value).trim() : ""
      if (!text) {
        callback(new Error(this.dhT("ruleSendContentRequired")))
        return
      }
      if (text.length > 2000) {
        callback(new Error(this.dhT("ruleSendContentLen")))
        return
      }
      callback()
    },
    validateReceiverName(rule, value, callback) {
      const text = value != null ? String(value).trim() : ""
      if (!text) {
        callback(new Error(this.dhT("ruleReceiverNameRequired")))
        return
      }
      if (text.length > 128) {
        callback(new Error(this.dhT("ruleReceiverNameLen")))
        return
      }
      callback()
    },
    validateReceiverAddress(rule, value, callback) {
      const text = value != null ? String(value).trim() : ""
      if (!text) {
        callback(new Error(this.dhT("ruleReceiverAddressRequired")))
        return
      }
      if (text.length > 512) {
        callback(new Error(this.dhT("ruleReceiverAddressLen")))
        return
      }
      callback()
    },
    validateRemark(rule, value, callback) {
      if (value != null && String(value).length > 500) {
        callback(new Error(this.dhT("ruleRemarkLen")))
        return
      }
      callback()
    },
    buildListQuery() {
      const q = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        receiverName: this.queryParams.receiverName
      }
      const range = this.queryParams.sendDateRange
      if (range && range.length === 2) {
        if (range[0] > range[1]) {
          this.$modal.msgError(this.dhT("ruleSendDateInvalid"))
          return null
        }
        q.startDate = range[0]
        q.endDate = range[1]
      }
      return q
    },
    getList() {
      const q = this.buildListQuery()
      if (!q) {
        return
      }
      this.loading = true
      listDataSendRecord(q)
        .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.sendDateRange = null
      this.queryParams.receiverName = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.form.sendTime = this.defaultSendTime()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getDataSendRecord(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.form = {
          id: data.id,
          sendTime: data.sendTime,
          sendContent: data.sendContent,
          receiverName: data.receiverName,
          receiverAddress: data.receiverAddress,
          remark: data.remark
        }
        this.open = true
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    handleView(row) {
      getDataSendRecord(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      this.$modal
        .confirm(this.dhT("confirmDelete", { id: row.id }))
        .then(() => delDataSendRecord(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dhCommon("msgDelOk"))
          this.getList()
        })
        .catch(() => {})
    },
    buildPayload() {
      return {
        sendTime: this.form.sendTime,
        sendContent: this.form.sendContent != null ? String(this.form.sendContent).trim() : undefined,
        receiverName: this.form.receiverName != null ? String(this.form.receiverName).trim() : undefined,
        receiverAddress: this.form.receiverAddress != null ? String(this.form.receiverAddress).trim() : undefined,
        remark: this.form.remark
      }
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateDataSendRecord(payload).then(() => {
            this.$modal.msgSuccess(this.dhCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addDataSendRecord(payload).then(() => {
            this.$modal.msgSuccess(this.dhCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
.dsr-pre {
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
