<template>
  <div class="home">
    <!-- <el-row :gutter="16" class="home__summary">
      <el-col :md="6" :sm="12" :xs="24" v-for="item in summaryCards" :key="item.label">
        <el-card shadow="hover" class="home__card">
          <div class="home__card-title">{{ item.label }}</div>
          <div class="home__card-value">{{ item.value }}</div>
          <div class="home__card-footer">
            <i :class="item.icon"></i>
            <span>{{ item.sub }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row> -->
    <el-dialog
      :visible.sync="qrDialogVisible"
      title="登记信息二维码"
      width="320px"
      center
    >
      <div style="text-align: center;">
        <canvas ref="qrCanvas"></canvas>
        <p style="margin-top: 12px; color: #909399; font-size: 12px;">扫描二维码查看登记信息</p>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="showDialog"
      title="文件列表"
      :fullscreen="isMobile"
      :width="isMobile ? '100%' : '1000px'"
      :top="isMobile ? '0' : '15vh'"
    >
      <div v-loading="pdfLoading" style="min-height: 120px;">
        <el-empty v-if="!pdfLoading && pdfFiles.length === 0" description="暂无PDF文件" />
        <div v-else>
          <div class="home__pdf-search">
            <el-input v-model="pdfSearchKeyword" size="large"  placeholder="搜索文件名" />
          </div>

          <el-empty v-if="!pdfLoading && filteredPdfFiles.length === 0" description="无匹配文件" />
          <el-table
            :height="isMobile ? null : 500"
            v-else
            :data="filteredPdfFiles"
            size="mini"
            border
            style="width: 100%;"
            @row-click="handlePdfRowClick"
          >
            <el-table-column label="选择" width="60" align="center">
              <template slot-scope="scope">
                <el-radio v-model="selectedFileName" :label="scope.row.name">&nbsp;</el-radio>
              </template>
            </el-table-column>
          <el-table-column prop="name" label="文件名" min-width="420">
            <template slot-scope="scope">
              <el-link
                :href="pdfHref(scope.row)"
                type="primary"
                @click.native.prevent="openPdf(scope.row)"
              >
                {{ scope.row.name }}
              </el-link>
            </template>
          </el-table-column>
            <!-- <el-table-column label="操作" width="120" align="center">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="openPdf(scope.row)">打开</el-button>
              </template>
            </el-table-column> -->
          </el-table>
        </div>
      </div>
      <template  #footer>
          <el-button type="primary" @click="confirmSaveData">确认登记</el-button>
      </template>
    </el-dialog>

    <el-card  class="home__card home__table-card">
      <div slot="header" class="home__card-header">
        <span class="home__card-header-title">登记列表</span>
        <div class="home__header-actions">
          <!-- <el-button size="mini" class="home__header-action home__header-action--pdf" @click="openPdfDialog">文件列表</el-button> -->
          <el-button size="small" type="primary" class="home__header-action" @click="loadData" :loading="loading">刷新</el-button>
        </div>
      </div>
      <div v-loading="loading">
        <el-table v-if="!isMobile" height="650px" border align="center" :data="tableData" stripe size="medium">
          <!-- <el-table-column prop="id" label="ID" width="80" /> -->
          <el-table-column align="center" prop="registerTime" label="登记时间" min-width="180" />

          <el-table-column align="center" prop="customerName" label="客户名称*" min-width="140">
            <template slot-scope="scope">
              <template v-if="isEditable(scope.row)">
                <el-input v-model="scope.row.customerNameDraft" size="mini" />
              </template>
              <template v-else>{{ scope.row.customerName }}</template>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="contact" label="联系方式*" min-width="140">
            <template slot-scope="scope">
              <template v-if="isEditable(scope.row)">
                <el-input v-model="scope.row.contactDraft" size="mini" />
              </template>
              <template v-else><div >{{ scope.row.contact }}</div></template>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="serviceType" label="服务类型*" min-width="120">
            <template slot-scope="scope">
              <template v-if="isEditable(scope.row)">
              <el-select
                v-model="scope.row.serviceTypeDraft"
                size="mini"
                placeholder="请选择"
                clearable
                style="width: 100%;"
              >
                  <el-option
                    v-for="opt in serviceTypeOptions"
                    :key="opt"
                    :label="opt"
                    :value="opt"
                  />
                </el-select>
              </template>
              <template v-else>{{ scope.row.serviceType }}</template>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="powerType" label="办电类型*" min-width="120">
            <template slot-scope="scope">
              <template v-if="isEditable(scope.row)">
              <el-select
                v-model="scope.row.powerTypeDraft"
                size="mini"
                placeholder="请选择"
                clearable
                style="width: 100%;"
              >
                  <el-option
                    v-for="opt in powerTypeOptions"
                    :key="opt"
                    :label="opt"
                    :value="opt"
                  />
                </el-select>
              </template>
              <template v-else>{{ scope.row.powerType }}</template>
            </template>
          </el-table-column>
          <el-table-column  align="center" prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <el-tag :type="statusType(scope.row.status)" disable-transitions>
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="note" label="备注" min-width="160">
            <template slot-scope="scope">
              <template v-if="isEditable(scope.row)">
                <el-input v-model="scope.row.noteDraft" size="mini" />
              </template>
              <template v-else>{{ scope.row.note }}</template>
            </template>
          </el-table-column>
          <!-- <el-table-column align="center" label="二维码" width="80">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="showQrCode(scope.row)">
                查看
              </el-button>
            </template>
          </el-table-column> -->
          <el-table-column align="center" label="操作" width="180">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                v-if="isEditable(scope.row)"
                :loading="isSaving(scope.row)"
                :disabled="isSaving(scope.row) || !canSave(scope.row)"
                @click="openFileDialog(scope.row)"
              >
                登记
              </el-button>
              <el-popconfirm
                title="确定要删除这条记录吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                style="flex: 1;"
                @confirm="deleteRow(scope.row)"
              >
                <el-button
                  slot="reference"
                  class="home__danger-text"
                  type="text"
                  size="mini"
                  
                  :loading="isDeleting(scope.row)"
                  :disabled="isSaving(scope.row) || isDeleting(scope.row)"
                >
                  删除
                </el-button>
              </el-popconfirm>
               <!-- <el-button
                type="text"
                size="mini"
                v-if="!isEditable(scope.row)"
                @click="sendSms(scope.row.id)"
              >
                发送文件通知
              </el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <div v-else class="home__mobile-list">
          <el-empty v-if="!loading && tableData.length === 0" description="暂无数据" />
          <el-card v-else v-for="row in tableData" :key="row.id" class="home__mobile-card">
            <div class="home__mobile-card-header">
              <div class="home__mobile-card-time">{{ row.registerTime }}</div>
              <el-tag size="mini" :type="statusType(row.status)" disable-transitions>{{ row.status }}</el-tag>
            </div>

            <div class="home__mobile-field">
              <div class="home__mobile-label">客户名称*</div>
              <div class="home__mobile-value">
                <el-input v-if="isEditable(row)" v-model="row.customerNameDraft" size="small" />
                <span v-else>{{ row.customerName }}</span>
              </div>
            </div>

            <div class="home__mobile-field">
              <div class="home__mobile-label">联系方式*</div>
              <div class="home__mobile-value">
                <el-input v-if="isEditable(row)" v-model="row.contactDraft" size="small" />
                <span v-else>{{ row.contact }}</span>
              </div>
            </div>

            <div class="home__mobile-field">
              <div class="home__mobile-label">服务类型*</div>
              <div class="home__mobile-value">
                <el-select
                  v-if="isEditable(row)"
                  v-model="row.serviceTypeDraft"
                  size="small"
                  placeholder="请选择"
                  clearable
                  style="width: 100%;"
                >
                  <el-option v-for="opt in serviceTypeOptions" :key="opt" :label="opt" :value="opt" />
                </el-select>
                <span v-else>{{ row.serviceType }}</span>
              </div>
            </div>

            <div class="home__mobile-field">
              <div class="home__mobile-label">办电类型*</div>
              <div class="home__mobile-value">
                <el-select
                  v-if="isEditable(row)"
                  v-model="row.powerTypeDraft"
                  size="small"
                  placeholder="请选择"
                  clearable
                  style="width: 100%;"
                >
                  <el-option v-for="opt in powerTypeOptions" :key="opt" :label="opt" :value="opt" />
                </el-select>
                <span v-else>{{ row.powerType }}</span>
              </div>
            </div>

            <div class="home__mobile-field">
              <div class="home__mobile-label">备注</div>
              <div class="home__mobile-value">
                <el-input v-if="isEditable(row)" v-model="row.noteDraft" size="small" />
                <span v-else>{{ row.note }}</span>
              </div>
            </div>

            <div class="home__mobile-actions">
              <el-button
                v-if="isEditable(row)"
                type="primary"
                size="medium "
                :loading="isSaving(row)"
                style="flex: 1;"
                :disabled="isSaving(row) || !canSave(row)"
                @click="openFileDialog(row)"
              >
                登记
              </el-button>
              <el-popconfirm
                title="确定要删除这条记录吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="deleteRow(row)"
              >
               
                <el-button
                  slot="reference"
                  type="danger"
                  size="medium "
                  style="flex: 1;"
                  :loading="isDeleting(row)"
                  :disabled="isSaving(row) || isDeleting(row)"
                >
                  删除
                </el-button>
              </el-popconfirm>
            </div>
            <!-- <div v-else class="home__mobile-actions">
              <el-button type="primary" size="mini" plain @click="showQrCode(row)">
                查看二维码
              </el-button>
            </div> -->
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { buildPdfUrl } from '@/api/client'
import Qrcode from'qrcode'
export default {
  name: 'Home',
  data() {
    
    return {
      showDialog:false,
      qrDialogVisible: false,
      pdfLoading: false,
      pdfFiles: [],
      pdfSearchKeyword: '',
      loading: false,
      savingId: null,
      deletingId: null,
      windowWidth: typeof window !== 'undefined' ? window.innerWidth : 1024,
      serviceTypeOptions: ['办电类','咨询类'],
      powerTypeOptions: ['高压新装、增容', '低压居民新装、增容', '低压非居民新装、增容','低压分布式电源新装、增容','个人电动汽车充电桩','新户通电','电能表校验','低压公共汽车充电桩业务','改压','小区配套新装'],
      summaryCards: [
      
      ],
      tableData: [],
      savedData:undefined,
      selectedFileName: ''
    }
  },
  computed: {
    isMobile() {
      return this.windowWidth <= 768
    },
    filteredPdfFiles() {
      const keyword = (this.pdfSearchKeyword || '').trim().toLowerCase()
      if (!keyword) return this.pdfFiles || []
      return (this.pdfFiles || []).filter(item => String(item.name || '').toLowerCase().includes(keyword))
    }
  },
  created() {
    this.loadData()
  },
  mounted() {
    this._onResize = () => {
      this.windowWidth = window.innerWidth
    }
    window.addEventListener('resize', this._onResize, { passive: true })
  },
  beforeDestroy() {
    window.removeEventListener('resize', this._onResize)
  },
  methods: {
  async confirmSaveData(){
    const data = this.savedData;
    await this.saveRow(data)
    this.showDialog = false
  },
  handlePdfRowClick(row) {
    if (!row) return
    this.selectedFileName = row.name || ''
  },
  openFileDialog(data){
    this.savedData = data;
    this.selectedFileName = '';
    this.pdfSearchKeyword = ''
    this.openPdfDialog();
  },
  async sendSms(id){
    const { sendSmsToUserPhone } = await import('@/api/registrations')
   
      this.$confirm('是否确认发送文件通知', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          customClass: this.isMobile ? 'home__message-box--mobile-center' : undefined
        }).then(async() => {
           await sendSmsToUserPhone(id)
          this.$message({
            type: 'success',
            message: '发送成功!'
          });
        }).catch(() => {
                  
        });
    
  },

    async openPdfDialog() {
      this.showDialog = true
      this.pdfSearchKeyword = ''
      await this.loadPdfFiles()
    },
    async loadPdfFiles() {
      this.pdfLoading = true
      try {
        const { fetchPdfs } = await import('@/api/pdfs')
        const list = await fetchPdfs()
        this.pdfFiles = (list || []).map(item => ({
          name: item.name,
          url: item.url
        }))
      } catch (err) {
        this.$message.error('加载PDF列表失败')
        // eslint-disable-next-line no-console
        console.error(err)
      } finally {
        this.pdfLoading = false
      }
    },
    openPdf(file) {
      const url = this.pdfHref(file)
      if (url && url !== '#') window.location.href = url
    },
    pdfHref(row) {
      return buildPdfUrl(row && row.name) || (row && row.url) || '#'
    },
    async loadData() {
      this.loading = true
      try {
        const { fetchRegistrations } = await import('@/api/registrations')
        const list = await fetchRegistrations()
        this.tableData = (list || []).map(item => ({
          id: item.id,
          customerName: item.customerName,
          customerNameDraft: item.customerName,
          contact: item.contact,
          contactDraft: item.contact,
          serviceType: item.serviceType,
          serviceTypeDraft: item.serviceType,
          powerType: item.powerType,
          powerTypeDraft: item.powerType,
          registerTime: item.registerTime,
          note: item.note,
          noteDraft: item.note,
          status: item.status
        }))
      } catch (err) {
        this.$message.error('加载登记数据失败')
        // eslint-disable-next-line no-console
        console.error(err)
      } finally {
        this.loading = false
      }
    },
    isEditable(row) {
      return row.status === '待登记'
    },
    isSaving(row) {
      return this.savingId === row.id
    },
    isDeleting(row) {
      return this.deletingId === row.id
    },
    canSave(row) {
      const customerName = (row.customerNameDraft || '').trim()
      const contact = (row.contactDraft || '').trim()
      const serviceType = (row.serviceTypeDraft || '').trim()
      const powerType = (row.powerTypeDraft || '').trim()
      return Boolean(customerName && contact && serviceType && powerType)
    },
    async deleteRow(row) {
      const id = row && row.id
      if (!id) return
      this.deletingId = id
      try {
        const { deleteRegistration } = await import('@/api/registrations')
        await deleteRegistration(id)

        this.tableData = (this.tableData || []).filter(item => item.id !== id)
        if (this.savedData && this.savedData.id === id) {
          this.showDialog = false
          this.savedData = undefined
          this.selectedFileName = ''
        }
        this.$message.success('已删除')
      } catch (err) {
        this.$message.error('删除失败')
        // eslint-disable-next-line no-console
        console.error(err)
      } finally {
        this.deletingId = null
      }
    },
    async saveRow(row) {
      const customerName = (row.customerNameDraft || '').trim()
      const contact = (row.contactDraft || '').trim()
      const serviceType = (row.serviceTypeDraft || '').trim()
      const powerType = (row.powerTypeDraft || '').trim()

      if (!customerName) {
        this.$message.warning('客户名称为必填')
        return
      }
      if (!contact) {
        this.$message.warning('联系方式为必填')
        return
      }
      if (!serviceType) {
        this.$message.warning('服务类型为必填')
        return
      }
      if (!powerType) {
        this.$message.warning('办电类型为必填')
        return
      }

      this.savingId = row.id
      try {
        const { updateRegistration } = await import('@/api/registrations')
        const payload = {
          id: row.id,
          customerName,
          contact,
          serviceType,
          powerType,
          registerTime: row.registerTime,
          note: row.noteDraft,
          status: '已登记',
          fileName: this.selectedFileName
        }
        await updateRegistration(row.id, payload)
        row.customerNameDraft = customerName
        row.contactDraft = contact
        row.serviceTypeDraft = serviceType
        row.powerTypeDraft = powerType
        row.customerName = customerName
        row.contact = contact
        row.serviceType = serviceType
        row.powerType = powerType
        row.note = row.noteDraft
        row.status = '已登记'
        this.$message.success('已登记')
      } catch (err) {
        this.$message.error('保存失败')
        // eslint-disable-next-line no-console
        console.error(err)
      } finally {
        this.savingId = null
      }
    },
    statusType(status) {
      const map = {
        待登记: 'warning',
        已登记: 'success',
        已完成: 'success',
        已关闭: 'info'
      }
      return map[status] || 'default'
    },
    async showQrCode(row) {
      this.qrDialogVisible = true
      await this.$nextTick()
      const canvas = this.$refs.qrCanvas
      if (!canvas) return
      const qrContent = [
        `客户名称: ${row.customerName || ''}`,
        `联系方式: ${row.contact || ''}`,
        `服务类型: ${row.serviceType || ''}`,
        `办电类型: ${row.powerType || ''}`,
        `登记时间: ${row.registerTime || ''}`,
        `状态: ${row.status || ''}`,
        `备注: ${row.note || ''}`
      ].join('\n')
      try {
        await Qrcode.toCanvas(canvas, qrContent, {
          width: 240,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#ffffff'
          }
        })
      } catch (err) {
        this.$message.error('生成二维码失败')
        // eslint-disable-next-line no-console
        console.error(err)
      }
    }
  }
}
</script>

<style scoped>
.home {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
}

.home__danger-text {
  color: #f56c6c;
  margin-left: 10px;
}

:global(.home__message-box--mobile-center) {
  margin-top: 0 !important;
  width: calc(100% - 32px);
  max-width: 420px;
}

.home__pdf-search {
  margin-bottom: 10px;
}

.home__card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  flex-wrap: wrap;
}

.home__card-header-title {
  line-height: 1.2;
}

.home__header-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.home__summary {
  margin: 0;
}

.home__card {
  min-height: 200px;
}

.home__card-title {
  color: #909399;
  font-size: 13px;
}

.home__card-value {
  margin-top: 12px;
  font-size: 28px;
  font-weight: 600;
  color: #303133;
}

.home__card-footer {
  margin-top: 8px;
  color: #67c23a;
  display: flex;
  align-items: center;
  gap: 6px;
}

.home__table-card {
  margin-top: 8px;
}

.home__header-action {
  margin-left: 0;
}

.home__header-action--pdf {
  background: #fff;
}

.home__mobile-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.home__mobile-card {
  border-radius: 8px;
}

.home__mobile-card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
}

.home__mobile-card-time {
  color: #909399;
  font-size: 12px;
  line-height: 1.2;
}

.home__mobile-field {
  display: grid;
  grid-template-columns: 86px 1fr;
  gap: 10px;
  padding: 6px 0;
}

.home__mobile-label {
  color: black;
  font-size: 14px;
  line-height: 28px;
}

.home__mobile-value {
  min-width: 0;
  font-size: 14px;
  color: #303133;
  line-height: 28px;
  word-break: break-word;
}

.home__mobile-link {
  color: #409eff;
}

.home__mobile-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
  gap: 8px;
}

@media (max-width: 768px) {
  .home {
    gap: 12px;
  }

  .home__card {
    min-height: auto;
  }

  .home__header-actions {
    width: 100%;
  }

  .home__header-actions ::v-deep .el-button {
    flex: 1;
  }

  .home__table-card {
    margin-top: 0;
  }
}
</style>
