<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="所在地区">
        <el-cascader
          v-model="queryArea"
          :options="areaOptions"
          :props="{ checkStrictly: true, ...areaProps }"
          placeholder="请选择地区"
          clearable
          style="width: 200px"
          @change="handleQueryAreaChange"
        />
      </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="['customer:customer:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['customer:customer:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['customer:customer:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['customer:customer:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="customerList" @selection-change="handleSelectionChange" @sort-change="handleSortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户名称" align="center" prop="name" />
      <el-table-column label="客户电话" align="center" prop="phone" sortable="custom" />
      
      <el-table-column label="所在地区" align="center" width="150" show-overflow-tooltip>
        <template #default="scope">
          {{ (scope.row.province || '') + (scope.row.city || '') + (scope.row.district || '') }}
        </template>
      </el-table-column>
      
      <el-table-column label="详细地址" align="center" prop="address" show-overflow-tooltip />
      
      <el-table-column label="创建人" align="center" prop="createBy" width="100" />
      
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['customer:customer:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['customer:customer: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"
      :page-sizes="[20, 50, 100, 200, 500, 1000, 2000]"
      @pagination="getList"
    />

    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="customerRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户名称" />
        </el-form-item>
        <el-form-item label="客户电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入客户电话" />
        </el-form-item>
        <el-form-item label="所在地区">
          <el-cascader
            v-model="selectedArea"
            :options="areaOptions"
            :props="areaProps"
            placeholder="请选择省市区"
            style="width: 100%"
            clearable
          />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </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>
import { ref, reactive, getCurrentInstance, onMounted, toRefs } from 'vue'
import { listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer } from "@/api/sale/customer/customer"
import { regionData } from 'element-china-area-data'

const { proxy } = getCurrentInstance()

const customerList = 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 areaOptions = ref(regionData)
const areaProps = {
  label: 'label',
  value: 'label',
  children: 'children'
}
// 表单用的地区绑定
const selectedArea = ref([])
// 查询用的地区绑定
const queryArea = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    name: null,
    province: null, // 新增
    city: null,     // 新增
    district: null, // 新增
    orderByColumn: null,
    isAsc: null
  },
  rules: {
    name: [{ required: true, message: "客户名称不能为空", trigger: "blur" }],
    // address 校验已移除，改为可选
  }
})

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

onMounted(() => {
  getList()
})

function getList() {
  loading.value = true
  listCustomer(queryParams.value).then(response => {
    customerList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 处理查询栏地区变化
function handleQueryAreaChange(val) {
  if (val && val.length > 0) {
    queryParams.value.province = val[0] || null
    queryParams.value.city = val[1] || null
    queryParams.value.district = val[2] || null
  } else {
    queryParams.value.province = null
    queryParams.value.city = null
    queryParams.value.district = null
  }
}

// 处理排序变化
function handleSortChange({ column, prop, order }) {
  queryParams.value.orderByColumn = prop
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc'
  getList()
}

function cancel() {
  open.value = false
  reset()
}

function reset() {
  form.value = {
    id: null,
    name: null,
    phone: null,
    province: null,
    city: null,
    district: null,
    address: null,
    remark: null
  }
  selectedArea.value = []
  proxy.resetForm("customerRef")
}

function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置地区选择
  queryArea.value = []
  queryParams.value.province = null
  queryParams.value.city = null
  queryParams.value.district = null
  
  queryParams.value.orderByColumn = null
  queryParams.value.isAsc = null
  handleQuery()
}

function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

function handleAdd() {
  reset()
  open.value = true
  title.value = "添加客户"
}

function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getCustomer(id).then(response => {
    form.value = response.data
    // 设置地区选择
    if (response.data.province || response.data.city || response.data.district) {
      selectedArea.value = [
        response.data.province,
        response.data.city,
        response.data.district
      ].filter(item => item) // 过滤空值
    }
    open.value = true
    title.value = "修改客户"
  })
}

// 处理表单提交时的地区数据
function handleAddress() {
  if (selectedArea.value && selectedArea.value.length > 0) {
    form.value.province = selectedArea.value[0] || ''
    form.value.city = selectedArea.value[1] || ''
    form.value.district = selectedArea.value[2] || ''
  } else {
    form.value.province = ''
    form.value.city = ''
    form.value.district = ''
  }
}

function submitForm() {
  handleAddress() // 处理地址数据
  
  proxy.$refs["customerRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCustomer(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addCustomer(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

function handleDelete(row) {
  const customerIds = row.id || ids.value
  proxy.$modal.confirm('是否确认删除选中的数据?').then(() => {
    return delCustomer(customerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

function handleExport() {
  proxy.download('customer/customer/export', {
    ...queryParams.value
  }, `customer_${new Date().getTime()}.xlsx`)
}
</script>