<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="公司名称" prop="companyName">
        <el-input
            v-model="queryParams.companyName"
            placeholder="请输入公司名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <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>
      <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="120"/>
      <el-table-column label="联系人电话" align="center" prop="contactPhone" width="120"/>
      <el-table-column label="公司名称" align="center" prop="companyName" width="180"/>
      <el-table-column label="省/市/区(县)" align="center"  width="200">
        <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="250"/>
      <el-table-column label="是否默认" align="center" prop="defaultFlag" width="80" >
        <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" prop="updateTime" width="180"/>
      <el-table-column label="备注" align="center" prop="remark" 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" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:book:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @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>
      <el-form ref="bookRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" maxlength="20" show-word-limit />
        </el-form-item>
        <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-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" maxlength="500" show-word-limit type="textarea" :rows="3" />
        </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>
  </div>
</template>

<script setup name="Book">
import { listBook, getBook, delBook, addBook, updateBook } from "@/api/logistics/book"
import RegionCascader from '@/components/RegionCascader.vue'
// 导入本地 JSON 数据
import { getCodesByNames  } from '@/utils/area-data.js'

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 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: {
    companyName: [
      { required: true, message: '公司名称不能为空', trigger: 'blur' },
      { min: 1, max: 100, message: '公司名称长度在 1 到 100 个字符', trigger: 'blur' }
    ],
    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' }
    ],
    remark: [
      { max: 500, message: '备注长度不能超过 500 个字符', trigger: 'blur' }
    ]
  }
})

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

/** 查询地址簿管理列表 */
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
  }
  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.region && form.value.region.length === 3) {
        // 这里确保省市区名称已通过handleRegionChange设置
        if (!form.value.provinceName || !form.value.cityName || !form.value.countyName) {
          proxy.$modal.msgError("请选择完整的省市区信息")
          return
        }
      }

      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`)
}

getList()
</script>