<template>
  <div class="app-container">
    <el-card shadow="never">
      <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
        <el-form-item prop="appointeeName">
          <template slot="label">{{ dtT("queryAppointeeName") }}</template>
          <el-input
            v-model="queryParams.appointeeName"
            :placeholder="dtT('queryAppointeeNamePh')"
            clearable
            style="width: 160px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <template slot="label">{{ dtT("queryAppointDate") }}</template>
          <el-date-picker
            v-model="queryDateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="-"
            :start-placeholder="dtT('queryDateRangePh')"
            :end-placeholder="dtT('queryDateRangeEndPh')"
            clearable
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item prop="status">
          <template slot="label">{{ dtT("queryStatus") }}</template>
          <el-select v-model="queryParams.status" :placeholder="dtCommon('pleaseSelect')" clearable style="width: 140px">
            <el-option
              v-for="item in statusOptions"
              :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">{{ dtCommon("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ dtCommon("reset") }}</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="dtT('colAppointeeName')" prop="appointeeName" align="center" min-width="100" :show-overflow-tooltip="true" />
        <el-table-column :label="dtT('colAppointDate')" prop="appointDate" align="center" width="120" />
        <el-table-column :label="dtT('colTimeSlot')" align="center" width="130">
          <template slot-scope="scope">
            <span>{{ formatTimeSlot(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dtT('colContactPhone')" prop="contactPhone" align="center" width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="dtT('colServiceAddress')" prop="serviceAddress" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="dtT('colServiceRequirement')" prop="serviceRequirement" align="center" min-width="140" :show-overflow-tooltip="true" />
        <el-table-column :label="dtT('colStatus')" align="center" width="100">
          <template slot-scope="scope">
            <el-tag v-if="vetAppointmentStatusTagType(scope.row.status)" :type="vetAppointmentStatusTagType(scope.row.status)" size="mini">
              {{ displayStatus(scope.row) }}
            </el-tag>
            <span v-else>{{ displayStatus(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="dtT('colRejectReason')" prop="rejectReason" align="center" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column :label="dtCommon('colOp')" align="center" class-name="small-padding fixed-width" width="280" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['diseaseTreatment:vetMyAppointment:query']"
              type="text"
              size="mini"
              @click="handleView(scope.row)"
            >{{ dtCommon("view") }}</el-button>
            <el-button
              v-if="canConfirmOrReject(scope.row)"
              v-hasPermi="['diseaseTreatment:vetMyAppointment:confirm']"
              type="text"
              size="mini"
              @click="handleConfirm(scope.row)"
            >{{ dtT("actionConfirm") }}</el-button>
            <el-button
              v-if="canConfirmOrReject(scope.row)"
              v-hasPermi="['diseaseTreatment:vetMyAppointment:reject']"
              type="text"
              size="mini"
              @click="openReject(scope.row)"
            >{{ dtT("actionReject") }}</el-button>
            <el-button
              v-if="canComplete(scope.row)"
              v-hasPermi="['diseaseTreatment:vetMyAppointment:complete']"
              type="text"
              size="mini"
              @click="handleComplete(scope.row)"
            >{{ dtT("actionComplete") }}</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="dtT('viewTitle')" :visible.sync="viewOpen" width="640px" append-to-body>
      <el-descriptions v-if="viewRow.id" :column="1" border size="small">
        <el-descriptions-item :label="dtT('viewAppointeeName')">{{ viewRow.appointeeName || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewAppointDate')">{{ viewRow.appointDate || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewTimeSlot')">{{ formatTimeSlot(viewRow) || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewContactPhone')">{{ viewRow.contactPhone || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewServiceAddress')">{{ viewRow.serviceAddress || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewServiceRequirement')">{{ viewRow.serviceRequirement || dash }}</el-descriptions-item>
        <el-descriptions-item :label="dtT('viewStatus')">{{ displayStatus(viewRow) }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.status === STATUS_REJECTED" :label="dtT('viewRejectReason')">
          {{ viewRow.rejectReason || dash }}
        </el-descriptions-item>
        <el-descriptions-item v-if="viewRow.confirmTime" :label="dtT('viewConfirmTime')">{{ viewRow.confirmTime }}</el-descriptions-item>
        <el-descriptions-item v-if="viewRow.rejectTime" :label="dtT('viewRejectTime')">{{ viewRow.rejectTime }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">{{ dtCommon("close") }}</el-button>
        <el-button
          v-if="canConfirmOrReject(viewRow)"
          v-hasPermi="['diseaseTreatment:vetMyAppointment:confirm']"
          type="primary"
          @click="handleConfirm(viewRow)"
        >{{ dtT("actionConfirm") }}</el-button>
        <el-button
          v-if="canConfirmOrReject(viewRow)"
          v-hasPermi="['diseaseTreatment:vetMyAppointment:reject']"
          type="danger"
          plain
          @click="openReject(viewRow)"
        >{{ dtT("actionReject") }}</el-button>
        <el-button
          v-if="canComplete(viewRow)"
          v-hasPermi="['diseaseTreatment:vetMyAppointment:complete']"
          type="primary"
          plain
          @click="handleComplete(viewRow)"
        >{{ dtT("actionComplete") }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="dtT('rejectTitle')" :visible.sync="rejectOpen" width="480px" append-to-body @close="cancelReject">
      <el-form ref="rejectForm" :model="rejectForm" label-width="100px">
        <el-form-item prop="rejectReason" :rules="rejectRules">
          <template slot="label">{{ dtT("rejectReason") }}</template>
          <el-input
            v-model="rejectForm.rejectReason"
            type="textarea"
            :rows="4"
            maxlength="100"
            show-word-limit
            :placeholder="dtT('rejectReasonPh')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelReject">{{ dtCommon("cancel") }}</el-button>
        <el-button type="primary" :loading="rejectSubmitting" @click="submitReject">{{ dtCommon("ok") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import diseaseTreatmentLocaleMixin from "@/mixins/diseaseTreatmentLocaleMixin"
import {
  listVetMyAppointment,
  getVetMyAppointment,
  confirmVetMyAppointment,
  rejectVetMyAppointment,
  completeVetMyAppointment
} from "@/api/diseaseTreatment/vetMyAppointment"

const STATUS_PENDING = 0
const STATUS_CONFIRMED = 1
const STATUS_REJECTED = 2

export default {
  name: "DiseaseTreatmentVetMyAppointment",
  mixins: [diseaseTreatmentLocaleMixin],
  data() {
    return {
      dtNs: "vetMyAppointment",
      STATUS_PENDING,
      STATUS_CONFIRMED,
      STATUS_REJECTED,
      loading: false,
      tableList: [],
      total: 0,
      queryDateRange: null,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        appointeeName: undefined,
        startDate: undefined,
        endDate: undefined,
        status: undefined
      },
      viewOpen: false,
      viewRow: {},
      rejectOpen: false,
      rejectSubmitting: false,
      rejectTargetId: null,
      rejectForm: {
        rejectReason: ""
      }
    }
  },
  computed: {
    dash() {
      return this.$t("diseaseTreatment.status.dash")
    },
    statusOptions() {
      return [0, 1, 2, 3, 4].map((value) => ({
        value,
        label: this.vetAppointmentStatusText(value)
      }))
    },
    rejectRules() {
      return [
        { required: true, message: this.dtT("rejectReasonRequired"), trigger: "blur" },
        { min: 1, max: 100, message: this.dtT("rejectReasonLen"), trigger: "blur" }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.syncDateRangeToQuery()
      this.loading = true
      listVetMyAppointment(this.queryParams)
        .then((res) => {
          this.tableList = res.rows || []
          this.total = res.total || 0
        })
        .finally(() => {
          this.loading = false
        })
    },
    syncDateRangeToQuery() {
      if (this.queryDateRange && this.queryDateRange.length === 2) {
        this.queryParams.startDate = this.queryDateRange[0]
        this.queryParams.endDate = this.queryDateRange[1]
      } else {
        this.queryParams.startDate = undefined
        this.queryParams.endDate = undefined
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryDateRange = null
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        appointeeName: undefined,
        startDate: undefined,
        endDate: undefined,
        status: undefined
      }
      this.$nextTick(() => {
        if (this.$refs.queryForm) {
          this.$refs.queryForm.resetFields()
        }
      })
      this.getList()
    },
    formatTimeSlot(row) {
      if (!row) {
        return ""
      }
      const start = row.timeStart
      const end = row.timeEnd
      if (start && end) {
        return `${start}~${end}`
      }
      return start || end || ""
    },
    displayStatus(row) {
      if (!row || row.status == null) {
        return this.dash
      }
      if (row.statusLabel) {
        return row.statusLabel
      }
      return this.vetAppointmentStatusText(row.status)
    },
    canConfirmOrReject(row) {
      return row && row.status === STATUS_PENDING
    },
    canComplete(row) {
      if (!row) {
        return false
      }
      if (row.canComplete != null) {
        return !!row.canComplete
      }
      return row.status === STATUS_CONFIRMED
    },
    handleView(row) {
      getVetMyAppointment(row.id).then((res) => {
        this.viewRow = res.data || {}
        this.viewOpen = true
      })
    },
    handleConfirm(row) {
      if (!row || !row.id) {
        return
      }
      this.$modal
        .confirm(this.dtT("confirmAcceptMsg"))
        .then(() => confirmVetMyAppointment(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtT("msgConfirmOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    handleComplete(row) {
      if (!row || !row.id) {
        return
      }
      this.$modal
        .confirm(this.dtT("confirmCompleteMsg"))
        .then(() => completeVetMyAppointment(row.id))
        .then(() => {
          this.$modal.msgSuccess(this.dtT("msgCompleteOk"))
          this.viewOpen = false
          this.getList()
        })
        .catch(() => {})
    },
    openReject(row) {
      if (!row || !row.id) {
        return
      }
      this.rejectTargetId = row.id
      this.rejectForm.rejectReason = ""
      this.rejectOpen = true
      this.$nextTick(() => {
        if (this.$refs.rejectForm) {
          this.$refs.rejectForm.clearValidate()
        }
      })
    },
    cancelReject() {
      this.rejectOpen = false
      this.rejectTargetId = null
      this.rejectForm.rejectReason = ""
    },
    submitReject() {
      this.$refs.rejectForm.validate((valid) => {
        if (!valid || !this.rejectTargetId) {
          return
        }
        const reason = (this.rejectForm.rejectReason || "").trim()
        if (!reason) {
          this.$modal.msgWarning(this.dtT("rejectReasonRequired"))
          return
        }
        this.rejectSubmitting = true
        rejectVetMyAppointment(this.rejectTargetId, { rejectReason: reason })
          .then(() => {
            this.$modal.msgSuccess(this.dtT("msgRejectOk"))
            this.rejectOpen = false
            this.viewOpen = false
            this.getList()
          })
          .finally(() => {
            this.rejectSubmitting = false
          })
      })
    }
  }
}
</script>
