<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="联系人姓名" prop="contactName">
        <el-input
            v-model="queryParams.contactName"
            placeholder="请输入联系人姓名"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人电话" prop="contactPhone">
        <el-input
            v-model="queryParams.contactPhone"
            placeholder="请输入联系人电话"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否默认" prop="defaultFlag">
        <el-select
            v-model="queryParams.defaultFlag"
            placeholder="请选择是否是默认地址"
        >
          <el-option
              v-for="dict in yes_or_no"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:book:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:book:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:book:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:book:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Download"
            @click="handleDownloadTemplate"
            v-hasPermi="['system:dept:add']">
          模板下载
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:book:add']">
          导入
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="联系人姓名" align="center" prop="contactName" width="180"/>
      <el-table-column label="联系人电话" align="center" prop="contactPhone" width="180"/>
      <el-table-column label="省/市/区(县)" align="center"  width="280">
        <template #default="scope">
          {{scope.row.provinceName}}/{{scope.row.cityName}}/{{scope.row.countyName}}
        </template>
      </el-table-column>
      <el-table-column label="详细地址" align="center" prop="detailedAddress" width="350"/>
      <el-table-column label="是否默认" align="center" prop="defaultFlag" width="180" >
        <template #default="scope">
          <dict-tag :options="yes_or_no" :value="scope.row.defaultFlag" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="180">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['system:book:edit']">修改</el-button>
          <el-button link type="primary"   @click="handleDelete(scope.row)" v-hasPermi="['system:book:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改地址簿管理对话框（增加智能识别区域） -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <!-- 智能识别区域 -->
      <div class="recognition-area">
        <div class="recognition-tip">识别后，请检查拆分地址信息是否准确，如有遗漏请及时补充</div>
        <el-input
            type="textarea"
            v-model="recognitionText"
            placeholder="请输入文本，自动识别姓名、电话和地址"
            :rows="3"
            maxlength="250"
            show-word-limit
            class="recognition-textarea"
        />
        <div class="recognition-actions">
          <el-button
              type="primary"
              @click="handleRecognition(1)"
              v-if="!recognitionText"
              class="recognition-btn"
              :loading="recognitionLoading"
          >粘贴并识别</el-button>
          <el-button
              type="primary"
              @click="handleRecognition(2)"
              v-else
              class="recognition-btn"
              :loading="recognitionLoading"
          >识别</el-button>
        </div>
      </div>

      <el-form ref="bookRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" placeholder="请输入联系人姓名" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="联系人电话" prop="contactPhone">
          <el-input v-model="form.contactPhone" placeholder="请输入联系人电话"  show-word-limit />
        </el-form-item>
        <el-form-item label="省市区" prop="region">
          <RegionCascader
              v-model="form.region"
              placeholder="请选择省市区"
              size="large"
              :clearable="true"
              @change="handleRegionChange"
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="是否默认" prop="defaultFlag">
          <el-select
              v-model="form.defaultFlag"
              placeholder="请选择是否是默认地址"
              size="large"
          >
            <el-option
                v-for="dict in yes_or_no"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 供应商导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Book">
import { listBook, getBook, delBook, addBook, updateBook, getAddressInfo } from "@/api/logistics/book"
import RegionCascader from '@/components/RegionCascader.vue'
import { getToken } from "@/utils/auth"
import { download } from '@/utils/request'
import { getCodesByNames } from '@/utils/area-data.js'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { yes_or_no } = proxy.useDict("yes_or_no")

const bookList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 手机号校验规则
const validatePhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('联系人电话不能为空'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

// 省市区校验规则
const validateRegion = (rule, value, callback) => {
  if (!value || value.length !== 3) {
    callback(new Error('请选择完整的省市区'))
  } else {
    callback()
  }
}

/*** 地址簿导入参数 */
const upload = reactive({
  open: false,
  title: "",
  isUploading: false,
  headers: { Authorization: "Bearer " + getToken() },
  url: import.meta.env.VITE_APP_BASE_API + "/system/book/importData",
  selectedFile: null
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    companyName: null,
    contactName: null,
    contactPhone: null,
    provinceName: null,
    cityName: null,
    countyName: null,
    detailedAddress: null,
    defaultFlag: null,
    deptId: null,
    userId: null,
  },
  rules: {
    contactName: [
      { required: true, message: '联系人姓名不能为空', trigger: 'blur' },
      { min: 1, max: 50, message: '联系人姓名长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    contactPhone: [
      { required: true, validator: validatePhone, trigger: 'blur' }
    ],
    region: [
      { required: true, validator: validateRegion, trigger: 'change' }
    ],
    detailedAddress: [
      { required: true, message: '详细地址不能为空', trigger: 'blur' },
      { min: 1, max: 200, message: '详细地址长度在 1 到 200 个字符', trigger: 'blur' }
    ],
    defaultFlag: [
      { required: true, message: '是否默认不能为空', trigger: 'change' }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 智能识别相关
const recognitionText = ref('')
const recognitionLoading = ref(false)

// 处理识别
const handleRecognition = async (actionType) => {
  let text = ''
  if (actionType === 1) {
    // 粘贴并识别：读取剪贴板
    try {
      const clipboardText = await navigator.clipboard.readText()
      if (!clipboardText) {
        ElMessage.warning('剪贴板内容为空')
        return
      }
      recognitionText.value = clipboardText
      text = clipboardText
    } catch (err) {
      ElMessage.error('读取剪贴板失败，请手动粘贴')
      return
    }
  } else {
    // 直接识别：使用当前文本域内容
    text = recognitionText.value
  }

  if (!text.trim()) {
    ElMessage.warning('请输入要识别的文本')
    return
  }

  recognitionLoading.value = true
  try {
    const params = { param: text }
    const res = await getAddressInfo(params)
    if (res.code === 200 && res.data?.result?.length > 0) {
      const result = res.data.result[0]

      // 填充表单
      form.value.contactName = result.name || ''
      if (result.mobile && result.mobile.length > 0) {
        form.value.contactPhone = result.mobile[0]
      }

      // 省市区
      if (result.xzq) {
        let province = '', city = '', district = ''
        if (result.xzq.fullName) {
          const parts = result.xzq.fullName.split(',').map(s => s.trim())
          province = parts[0] || ''
          city = parts[1] || ''
          district = parts[2] || ''
        } else {
          province = result.xzq.province || ''
          city = result.xzq.city || ''
          district = result.xzq.district || ''
        }
        form.value.provinceName = province
        form.value.cityName = city
        form.value.countyName = district

        // 获取省市区代码并设置 region
        const codes = getCodesByNames(province, city, district)
        form.value.region = codes

        // 详细地址
        if (result.xzq.subArea) {
          form.value.detailedAddress = result.xzq.subArea
        } else if (result.address) {
          const fullAddr = result.address
          const prefix = province + city + district
          form.value.detailedAddress = fullAddr.startsWith(prefix) ? fullAddr.substring(prefix.length) : fullAddr
        }
      }

      // 清空识别文本域
      recognitionText.value = ''

      ElMessage.success('识别成功，请核对信息')
    } else {
      ElMessage.error(res.message || '识别失败')
    }
  } catch (error) {
    console.error('识别错误', error)
    ElMessage.error('识别失败，请重试')
  } finally {
    recognitionLoading.value = false
  }
}

/** 查询地址簿管理列表 */
function getList() {
  loading.value = true
  listBook(queryParams.value).then(response => {
    bookList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    addressId: null,
    companyName: null,
    contactName: null,
    contactPhone: null,
    provinceName: null,
    cityName: null,
    countyName: null,
    region:[],
    detailedAddress: null,
    defaultFlag: null,
    deptId: null,
    userId: null,
    remark: null,
    delFlag: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null
  }
  recognitionText.value = '' // 重置识别文本域
  proxy.resetForm("bookRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.addressId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

const handleRegionChange = (regionInfo) => {
  console.log('地区信息:', regionInfo)
  form.value.provinceName = regionInfo.provinceName || ''
  form.value.cityName = regionInfo.cityName || ''
  form.value.countyName = regionInfo.districtName || ''
  form.value.region = [regionInfo.provinceCode, regionInfo.cityCode, regionInfo.districtCode]
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加地址簿管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _addressId = row.addressId || ids.value
  getBook(_addressId).then(response => {
    form.value = response.data
    form.value.region = getCodesByNames(response.data.provinceName, response.data.cityName, response.data.countyName)
    form.value.defaultFlag = form.value.defaultFlag + ''
    open.value = true
    title.value = "修改地址簿管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bookRef"].validate(valid => {
    if (valid) {
      if (form.value.addressId != null) {
        updateBook(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        }).catch(() => {})
      } else {
        addBook(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        }).catch(() => {})
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _addressIds = row.addressId || ids.value
  proxy.$modal.confirm('是否确认删除地址').then(function() {
    return delBook(_addressIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/book/export', {
    ...queryParams.value
  }, `book_${new Date().getTime()}.xlsx`)
}

/** 下载模板 */
const handleDownloadTemplate = () => {
  download('/system/book/importTemplate', {}, '地址簿模板.xlsx')
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "地址簿导入"
  upload.open = true
  upload.selectedFile = null
}

/** 文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件选择处理 */
const handleFileChange = (file, fileList) => {
  upload.selectedFile = file
}

/** 文件删除处理 */
const handleFileRemove = (file, fileList) => {
  upload.selectedFile = null
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
  getList()
}

/** 提交上传文件 */
function submitFileForm() {
  const file = upload.selectedFile
  if (!file || file.length === 0 || !file.name.toLowerCase().endsWith('.xls') && !file.name.toLowerCase().endsWith('.xlsx')) {
    proxy.$modal.msgError("请选择后缀为 “xls”或“xlsx”的文件。")
    return
  }
  proxy.$refs["uploadRef"].submit()
}

getList()
</script>

<style scoped>
/* 识别区域样式（与 createOrder 一致） */
.recognition-area {
  background-color: #fff;
  //border-radius: 8px;
  //padding: 16px;
  margin-bottom: 20px;
  //border: 1px solid #e4e7ed;
}

.recognition-textarea :deep(.el-textarea__inner) {
  background-color: #F5F7FA;
  border: none;
  border-radius: 4px;
  font-size: 14px;
}

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

.recognition-btn {
  width: 120px;
  height: 36px;
  background: #1B64F0;
  border-radius: 18px;
  font-size: 14px;
}

.recognition-tip {
  font-size: 12px;
  color: #999;
  margin-bottom: 8px;
  line-height: 1.5;
}
</style>