<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="stationName">
          <template slot="label">{{ lsT("queryStationName") }}</template>
          <el-input
            v-model="queryParams.stationName"
            :placeholder="lsT('queryStationNamePh')"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="operateStatus">
          <template slot="label">{{ lsT("queryOperateStatus") }}</template>
          <el-select v-model="queryParams.operateStatus" :placeholder="lsCommon('pleaseSelect')" clearable style="width: 120px">
            <el-option v-for="item in operateStatusOptions" :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">{{ lsCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ lsCommon("reset") }}</el-button>
          <el-button
            v-hasPermi="['livestock:quarantineStation:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >{{ lsCommon("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="lsT('colStationName')" prop="stationName" align="center" min-width="120" fixed="left" :show-overflow-tooltip="true" />
        <el-table-column :label="lsT('colDetailAddress')" prop="detailAddress" align="center" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column :label="lsT('colPersonInCharge')" prop="personInCharge" align="center" width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="lsT('colContactPhone')" align="center" width="120">
          <template slot-scope="scope">
            <span>{{ maskPhone(scope.row.contactPhone) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="lsT('colOperateStatus')" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ operateStatusLabel(scope.row.operateStatus) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="lsCommon('colOp')" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button v-hasPermi="['livestock:quarantineStation:query']" type="text" size="mini" @click="handleView(scope.row)">{{ lsCommon("view") }}</el-button>
            <el-button v-hasPermi="['livestock:quarantineStation:edit']" type="text" size="mini" @click="handleEdit(scope.row)">{{ lsCommon("edit") }}</el-button>
            <el-button v-hasPermi="['livestock:quarantineStation:remove']" type="text" size="mini" @click="handleDelete(scope.row)">{{ lsCommon("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="550px" append-to-body @close="cancel">
      <el-form :key="formKey" ref="form" :model="form" label-width="120px">
        <el-form-item prop="stationName" :rules="formRules.stationName">
          <template slot="label">{{ lsT("formStationName") }}</template>
          <el-input v-model="form.stationName" :placeholder="lsT('phStationName')" maxlength="10" show-word-limit />
        </el-form-item>
        <el-form-item prop="detailAddress" :rules="formRules.detailAddress">
          <template slot="label">{{ lsT("formDetailAddress") }}</template>
          <el-input v-model="form.detailAddress" type="textarea" :rows="3" :placeholder="lsT('phDetailAddress')" maxlength="200" show-word-limit />
        </el-form-item>
         <el-form-item prop="personInCharge" :rules="formRules.personInCharge">
              <template slot="label">{{ lsT("formPersonInCharge") }}</template>
              <el-input v-model="form.personInCharge" :placeholder="lsT('phPersonInCharge')" maxlength="10" show-word-limit />
            </el-form-item>
             <el-form-item prop="contactPhone" :rules="formRules.contactPhone">
              <template slot="label">{{ lsT("formContactPhone") }}</template>
              <el-input v-model="form.contactPhone" :placeholder="lsT('phContactPhone')" maxlength="11" />
            </el-form-item>
        
        <el-form-item prop="operateStatus" :rules="formRules.operateStatus">
          <template slot="label">{{ lsT("formOperateStatus") }}</template>
          <el-select v-model="form.operateStatus" :placeholder="lsCommon('pleaseSelect')" style="width: 100%">
            <el-option v-for="item in operateStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="photoFilePath">
          <template slot="label">{{ lsT("formPhoto") }}</template>
          <el-upload
            list-type="picture-card"
            :class="{ hide: hidePhotoUpload }"
            :action="uploadAction"
            :headers="uploadHeaders"
            :before-upload="beforePhotoUpload"
            :on-success="handlePhotoUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handlePhotoRemove"
            :limit="1"
            :file-list="photoFileList"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <div class="el-upload__tip">{{ lsT("tipPhoto") }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ lsCommon("ok") }}</el-button>
        <el-button @click="cancel">{{ lsCommon("cancel") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="lsCommon('viewTitle')" :visible.sync="viewOpen" width="720px" append-to-body>
      <el-form label-width="120px" size="small">
        <el-form-item :label="lsT('formStationName')">
          <span>{{ viewRow.stationName || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('formDetailAddress')">
          <span class="pre-wrap">{{ viewRow.detailAddress || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('formPersonInCharge')">
          <span>{{ viewRow.personInCharge || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('formContactPhone')">
          <span>{{ viewRow.contactPhone || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('formOperateStatus')">
          <span>{{ operateStatusLabel(viewRow.operateStatus) }}</span>
        </el-form-item>
        <el-form-item :label="lsT('formPhoto')">
          <el-image
            v-if="viewPhotoUrl"
            :src="viewPhotoUrl"
            :preview-src-list="[viewPhotoUrl]"
            fit="contain"
            style="width: 120px; height: 120px"
          />
          <span v-else>{{ dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('viewCreateBy')">
          <span>{{ viewRow.createBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('viewCreateTime')">
          <span>{{ viewRow.createTime ? parseTime(viewRow.createTime) : dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('viewUpdateBy')">
          <span>{{ viewRow.updateBy || dash }}</span>
        </el-form-item>
        <el-form-item :label="lsT('viewUpdateTime')">
          <span>{{ viewRow.updateTime ? parseTime(viewRow.updateTime) : dash }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-hasPermi="['livestock:quarantineStation:edit']" type="primary" plain @click="openEditFromView">{{ lsCommon("edit") }}</el-button>
        <el-button v-hasPermi="['livestock:quarantineStation:remove']" type="danger" plain @click="handleDelete(viewRow)">{{ lsCommon("delete") }}</el-button>
        <el-button @click="viewOpen = false">{{ lsCommon("close") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import livestockLocaleMixin from "@/mixins/livestockLocaleMixin"
import {
  listQuarantineStation,
  getQuarantineStation,
  addQuarantineStation,
  updateQuarantineStation,
  delQuarantineStation
} from "@/api/livestock/quarantineStation"

const PHONE_REG = /^1[3-9]\d{9}$/

function createEmptyForm() {
  return {
    id: undefined,
    stationName: undefined,
    detailAddress: undefined,
    personInCharge: undefined,
    contactPhone: undefined,
    operateStatus: 1,
    photoFileUrl: undefined,
    photoFilePath: undefined
  }
}

export default {
  name: "LivestockQuarantineStation",
  mixins: [livestockLocaleMixin],
  data() {
    return {
      lsNs: "quarantineStation",
      loading: false,
      open: false,
      viewOpen: false,
      viewRow: {},
      dialogEdit: false,
      formKey: 0,
      total: 0,
      tableList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        stationName: undefined,
        operateStatus: undefined
      },
      form: createEmptyForm()
    }
  },
  computed: {
    dash() {
      return this.$t("livestock.status.dash")
    },
    dialogTitle() {
      return this.dialogEdit ? this.lsT("dialogEdit") : this.lsT("dialogAdd")
    },
    operateStatusOptions() {
      return [1, 2, 3].map((v) => ({ value: v, label: this.lsT("operateStatus" + v) }))
    },
    uploadAction() {
      return process.env.VUE_APP_BASE_API + "/common/upload"
    },
    uploadHeaders() {
      return { Authorization: "Bearer " + getToken() }
    },
    photoFileList() {
      if (!this.form.photoFileUrl && !this.form.photoFilePath) {
        return []
      }
      const url = this.resolvePhotoUrl(this.form.photoFileUrl, this.form.photoFilePath)
      return [{ name: this.form.photoFilePath || "photo", url: url }]
    },
    hidePhotoUpload() {
      return !!(this.form.photoFilePath || this.form.photoFileUrl)
    },
    viewPhotoUrl() {
      return this.resolvePhotoUrl(this.viewRow.photoFileUrl, this.viewRow.photoFilePath)
    },
    formRules() {
      return {
        stationName: [
          { required: true, message: this.lsT("ruleNameRequired"), trigger: "blur" },
          { validator: this.validateStationName, trigger: "blur" }
        ],
        detailAddress: [
          { required: true, message: this.lsT("ruleAddressRequired"), trigger: "blur" },
          { validator: this.validateDetailAddress, trigger: "blur" }
        ],
        personInCharge: [
          { required: true, message: this.lsT("rulePersonRequired"), trigger: "blur" },
          { validator: this.validatePersonInCharge, trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: this.lsT("rulePhoneRequired"), trigger: "blur" },
          { validator: this.validatePhone, trigger: "blur" }
        ],
        operateStatus: [{ required: true, message: this.lsT("ruleOperateStatusRequired"), trigger: "change" }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    operateStatusLabel(v) {
      if (v == null || v === "") {
        return this.dash
      }
      return this.lsT("operateStatus" + v) || v
    },
    maskPhone(val) {
      if (!val || val.length < 7) {
        return val || this.dash
      }
      return val.slice(0, 3) + "****" + val.slice(-4)
    },
    resolvePhotoUrl(url, path) {
      if (url) {
        if (url.indexOf("http") === 0) {
          return url
        }
        return process.env.VUE_APP_BASE_API + url
      }
      if (path) {
        return process.env.VUE_APP_BASE_API + path
      }
      return ""
    },
    validateStationName(rule, value, callback) {
      const v = value != null ? String(value).trim() : ""
      if (!v) {
        callback(new Error(this.lsT("ruleNameRequired")))
        return
      }
      if (v.length < 1 || v.length > 10) {
        callback(new Error(this.lsT("ruleNameLen")))
        return
      }
      callback()
    },
    validateDetailAddress(rule, value, callback) {
      const v = value != null ? String(value).trim() : ""
      if (!v) {
        callback(new Error(this.lsT("ruleAddressRequired")))
        return
      }
      if (v.length < 1 || v.length > 200) {
        callback(new Error(this.lsT("ruleAddressLen")))
        return
      }
      callback()
    },
    validatePersonInCharge(rule, value, callback) {
      const v = value != null ? String(value).trim() : ""
      if (!v) {
        callback(new Error(this.lsT("rulePersonRequired")))
        return
      }
      if (v.length < 1 || v.length > 10) {
        callback(new Error(this.lsT("rulePersonLen")))
        return
      }
      callback()
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      if (!PHONE_REG.test(String(value).trim())) {
        callback(new Error(this.lsT("rulePhoneInvalid")))
        return
      }
      callback()
    },
    extOf(fileName) {
      if (!fileName || fileName.lastIndexOf(".") < 0) {
        return ""
      }
      return fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase()
    },
    beforePhotoUpload(file) {
      const ext = this.extOf(file.name)
      if (!["jpg", "jpeg", "png"].includes(ext)) {
        this.$modal.msgError(this.lsT("tipPhoto"))
        return false
      }
      if (file.name.includes(",")) {
        this.$modal.msgError("文件名不能包含英文逗号")
        return false
      }
      if (file.size / 1024 / 1024 >= 10) {
        this.$modal.msgError(this.lsT("tipPhoto"))
        return false
      }
      this.$modal.loading("正在上传图片，请稍候...")
      return true
    },
    handlePhotoUploadSuccess(res) {
      this.$modal.closeLoading()
      if (res.code === 200) {
        this.form.photoFileUrl = res.url
        this.form.photoFilePath = res.fileName
      } else {
        this.$modal.msgError(res.msg || "上传失败")
      }
    },
    handleUploadError() {
      this.$modal.closeLoading()
      this.$modal.msgError("上传失败，请重试")
    },
    handlePhotoRemove() {
      this.form.photoFileUrl = undefined
      this.form.photoFilePath = undefined
    },
    resetFormModel() {
      this.form = createEmptyForm()
    },
    fillFormFromData(data) {
      this.form = Object.assign(createEmptyForm(), {
        id: data.id,
        stationName: data.stationName,
        detailAddress: data.detailAddress,
        personInCharge: data.personInCharge,
        contactPhone: data.contactPhone,
        operateStatus: data.operateStatus != null ? data.operateStatus : 1,
        photoFileUrl: data.photoFileUrl,
        photoFilePath: data.photoFilePath
      })
    },
    buildPayload() {
      return {
        stationName: String(this.form.stationName).trim(),
        detailAddress: String(this.form.detailAddress).trim(),
        personInCharge: String(this.form.personInCharge).trim(),
        contactPhone: String(this.form.contactPhone).trim(),
        operateStatus: this.form.operateStatus,
        photoFileUrl: this.form.photoFileUrl || undefined,
        photoFilePath: this.form.photoFilePath || undefined
      }
    },
    getList() {
      this.loading = true
      listQuarantineStation(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.stationName = undefined
      this.queryParams.operateStatus = undefined
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleAdd() {
      this.formKey += 1
      this.resetFormModel()
      this.dialogEdit = false
      this.open = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      getQuarantineStation(row.id).then((res) => {
        const data = res.data || {}
        this.formKey += 1
        this.dialogEdit = true
        this.fillFormFromData(data)
        this.open = true
        this.viewOpen = false
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate()
          }
        })
      })
    },
    openEditFromView() {
      this.handleEdit(this.viewRow)
    },
    handleView(row) {
      getQuarantineStation(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleDelete(row) {
      const name = row.stationName || row.id
      this.$modal
        .confirm(this.lsT("confirmDelete", { name: name }))
        .then(() => delQuarantineStation(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.lsCommon("msgDelOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) {
          return
        }
        const payload = this.buildPayload()
        if (this.dialogEdit) {
          payload.id = this.form.id
          updateQuarantineStation(payload).then(() => {
            this.$modal.msgSuccess(this.lsCommon("msgModOk"))
            this.open = false
            this.getList()
          })
        } else {
          addQuarantineStation(payload).then(() => {
            this.$modal.msgSuccess(this.lsCommon("msgAddOk"))
            this.open = false
            this.getList()
          })
        }
      })
    },
    cancel() {
      this.open = false
      this.resetFormModel()
    }
  }
}
</script>

<style scoped>
::v-deep.hide .el-upload--picture-card {
  display: none;
}
.pre-wrap {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
