<template>
  <div class="user-page flex-column card h-100 overflow-hidden">
    <div class="header-filter-form">
      <el-button type="success" @click="addDialog">
        {{ '新增' }}
      </el-button>
      <el-button
        :disabled="(tableData as ShippingAddressObj[]).filter((el) => el.checked).length === 0"
        type="danger"
        @click="
          deleteSection(
            (tableData as ShippingAddressObj[])
              .filter((el) => el.checked)
              .map((el) => el.id as number)
          )
        "
      >
        {{ '删除' }}
      </el-button>
    </div>
    <div class="user-content flex-1 flex-column overflow-hidden">
      <div class="user-list flex-1 overflow-hidden" v-loading="loading">
        <el-row :gutter="20">
          <el-col
            v-for="(item, index) in tableData as ShippingAddressObj[]"
            :key="index"
            :span="12"
          >
            <div class="address-item">
              <div class="check">
                <el-checkbox v-model="item.checked"></el-checkbox>
              </div>
              <div class="left">
                <div class="name">
                  <b>{{ item.shipperName }}</b>

                  <p :title="[item.phoneNumber, item.postalCode].join(' ')">
                    {{ [item.phoneNumber, item.postalCode].join(' ') }}
                  </p>

                  <el-tag type="success" v-if="item.swDefault">
                    {{ '默认' }}
                  </el-tag>
                </div>
                <p
                  style="white-space: pre"
                  :title="getJosn(item)"
                  class="address"
                >
                  {{ getJosn(item) }}
                </p>
                <p
                  :title="
                    [item.addressLine1, item.addressLine2, item.addressLine3]
                      .filter((el) => el != null && el !== '')
                      .join(' ')
                  "
                  class="address address-en"
                >
                  {{
                    [item.addressLine1, item.addressLine2, item.addressLine3]
                      .filter((el) => el != null && el !== '')
                      .join(' ')
                  }}
                </p>
              </div>

              <div class="action">
                <el-icon
                  size="24"
                  title="编辑"
                  color="#EF6C00"
                  style="cursor: pointer; vertical-align: middle"
                  @click="editAddress(item)"
                >
                  <Edit />
                </el-icon>
                <el-icon
                  size="24"
                  title="删除"
                  color="#f56c6c"
                  style="cursor: pointer; vertical-align: middle"
                  @click="deleteAddress(item)"
                >
                  <Delete />
                </el-icon>
                <el-icon
                  size="24"
                  title="日志"
                  color="#008aff"
                  style="cursor: pointer; vertical-align: middle"
                  @click="showLog(item)"
                >
                  <List />
                </el-icon>
              </div>
            </div>
          </el-col>
          <el-col :span="24" v-if="tableData.length === 0">
            <div class="empty-box">
              <el-empty description="暂无发货地址" />
            </div>
          </el-col>
        </el-row>
      </div>
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[100, 200, 300, 400, 500]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 10px auto 0; text-align: right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></ElPagination>
    </div>
  </div>

  <LogDialog
    :title="editForm.id ? '编辑发货地址' : '新增发货地址'"
    v-model="dialogVisible"
    dialogWidth="1000px"
    @close="cancelFn"
  >
    <CustomizeForm
      ref="editFormRef"
      v-model="editForm"
      :config="formConfig"
      formItemWidth="50%"
    >
    </CustomizeForm>

    <template #footer>
      <div style="text-align: center">
        <ElButton @click="cancelFn">取消</ElButton>

        <ElButton type="primary" @click="save">保存</ElButton>
      </div>
    </template>
  </LogDialog>

  <LogDialog
    title="日志"
    v-model="logDialogVisible"
    @close="logDialogVisible = false"
  >
    <div v-for="item in logList" :key="item.id" style="margin-bottom: 8px">
      <span style="margin-right: 10px">{{ item.createTime }}</span>
      <span>{{ item.description }}</span>
    </div>
  </LogDialog>
</template>

<script setup lang="tsx">
defineOptions({
  name: 'ShippingAddress',
})
import {
  getAddressByIdList,
  addAddress,
  updateAddress,
  getLogisticsLog,
  deleteAddressByIds,
  getAllCountryApi,
} from '@/api/logistics'

import { IFormConfig } from '@/components/CustomizeForm.tsx'

import LogDialog from './components/LogDialog.tsx'
import CustomizeForm from '@/components/CustomizeForm.tsx'
import { Edit, Delete, List } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'

import { ShippingAddressObj, ICountryObj } from './types/shippingAddress.ts'
import usePageList from '@/utils/hooks/usePageList'
import { useValue } from './hooks/useValue'
import { showConfirm } from '@/utils/ui'

const [editForm, resetEditForm] = useValue<ShippingAddressObj>({
  swDefault: false,
})
const {
  loading,
  currentPage,
  pageSize,
  total,
  data: tableData,
  refresh: search,
  onCurrentPageChange: handleCurrentChange,
  onPageSizeChange: handleSizeChange,
} = usePageList({
  query: (page, pageSize) =>
    getAddressByIdList({
      pageSize: pageSize,
      currentPage: page,
    }).then(({ data }) => {
      console.log(130, data)
      return data
    }),
})
const dialogVisible = ref(false)
const logDialogVisible = ref(false)
const editFormRef = ref<InstanceType<typeof CustomizeForm> | null>(null)
const countryList = ref([])

const formConfig = computed<IFormConfig[]>(() => [
  {
    prop: 'shipperName',
    type: 'input',
    label: '发货人姓名',
    attrs: {
      placeholder: '请输入发货人姓名',
    },
    rules: [{ required: true, message: '请输入发货人姓名' }],
  },
  {
    prop: 'addressLine1',
    type: 'input',
    label: '地址 1',
    attrs: {
      width: '100%',
      placeholder: '请输入地址 1',
    },
    rules: [{ required: true, message: '请输入地址1' }],
  },
  {
    prop: 'addressLine2',
    type: 'input',
    label: '地址 2',
    attrs: {
      width: '100%',
      placeholder: '请输入地址 2',
    },
  },
  {
    prop: 'addressLine3',
    type: 'input',
    label: '地址 3',
    attrs: {
      width: '100%',
      placeholder: '请输入地址 3',
    },
  },
  {
    prop: 'countryCode',
    type: 'select',
    label: '国家代码',
    attrs: {
      options: countryList.value,
      label: 'countryCode',
      value: 'countryCode',
      filterable: true,
      placeholder: '请选择国家代码',
      onChange: (val: ICountryObj) => {
        editForm.value.countryName = val.nameCn
      },
    },
    rules: [{ required: true, message: '请选择国家代码' }],
  },
  {
    prop: 'countryName',
    type: 'select',
    label: '国家名称',
    attrs: {
      options: countryList.value,
      label: 'nameCn',
      value: 'nameCn',
      filterable: true,
      placeholder: '请选择国家名称',
      onChange: (val: ICountryObj) => {
        editForm.value.countryCode = val.countryCode
      },
    },
    rules: [{ required: true, message: '请选择国家名称' }],
  },

  {
    prop: 'stateProvince',
    type: 'input',
    label: '州/省',
    attrs: {
      // options: [],
      placeholder: '请输入州/省',
    },
  },
  {
    prop: 'stateProvinceAbbr',
    type: 'input',
    label: '州/省简称',
    attrs: {
      // options: [],
      placeholder: '请输入州/省简称',
    },
  },
  {
    prop: 'cityCode',
    type: 'input',
    label: '城市编码',
    attrs: {
      // options: [],
      placeholder: '请输入城市编码',
    },
  },
  {
    prop: 'city',
    type: 'input',
    label: '城市',
    attrs: {
      // options: [],
      placeholder: '请输入城市',
    },
    rules: [{ required: true, message: '请输入城市' }],
  },

  {
    prop: 'districtCode',
    type: 'input',
    label: '区编码',
    attrs: {
      // options: [],
      placeholder: '请选择区',
    },
  },
  {
    prop: 'district',
    type: 'input',
    label: '区',
    attrs: {
      // options: [],
      placeholder: '请选择区',
    },
  },

  {
    prop: 'postalCode',
    type: 'input',
    label: '邮编',
    attrs: {
      placeholder: '请输入邮编',
    },
    rules: [{ required: true, message: '请输入邮编' }],
  },
  {
    prop: 'phoneNumber',
    type: 'input',
    label: '电话',
    attrs: {
      placeholder: '请输入电话',
    },
  },

  {
    prop: 'swDefault',
    type: 'switch',
    label: '是否默认',
  },
])

async function getCountryList() {
  try {
    const { data } = await getAllCountryApi()
    countryList.value = data
    console.log(372, countryList.value)
  } catch (error) {
    console.log(error)
  }
}

function getJosn(item: ShippingAddressObj) {
  return [
    [item.countryName, item.countryCode],
    [item.stateProvince, item.stateProvinceAbbr],
    [item.district, item.districtCode],
    [item.city, item.cityCode],
  ]
    .map(([value, code]) => {
      if (value && code) return `${value} (${code})`
      if (value) return value
      if (code) return code // 当 value 不存在但 code 存在时，不使用括号
      return null
    })
    .filter(Boolean)
    .join(`   `) // 使用三个空格作为分隔符增大间距
}

onMounted(() => {
  getCountryList()
})

/**
 * @description: 取消按钮
 */
function cancelFn() {
  dialogVisible.value = false
  editFormRef.value?.resetFields()
  resetEditForm()
}

/**
 * @description: 删除按钮
 */
async function deleteAddress(item: ShippingAddressObj) {
  try {
    await showConfirm('是否删除发货地址', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = { ids: [item.id].join(',') }
    console.log(381, ids)
    await deleteAddressByIds(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}

/**
 * @description: 编辑按钮
 */
async function editAddress(item: ShippingAddressObj) {
  try {
    editForm.value = { ...item }
    console.log(395, editForm.value)
    dialogVisible.value = true
  } catch (e) {
    console.log(e)
  }
}

/**
 * @description: 检查数据
 */
async function checkData() {
  const [isValid, postData] = await Promise.all([
    new Promise<boolean>((resolve) => {
      editFormRef.value
        ?.validate()
        .then(() => resolve(true))
        .catch((err) => {
          resolve(false)
          console.log(err)
        })
    }),
    new Promise<ShippingAddressObj>((resolve) => {
      const params = { ...editForm.value }
      resolve(params)
    }),
  ])
  console.log(isValid, postData)

  return { isValid, postData }
}

/**
 * @description: 保存按钮
 */
const save = debounce(async () => {
  const { isValid, postData } = await checkData()
  if (isValid) {
    try {
      if (!postData.id) {
        await addAddress({
          ...postData,
        })
      } else {
        await updateAddress({
          ...postData,
        })
      }
      ElMessage({
        message: postData.id ? '更新成功' : '新增成功',
        type: 'success',
        offset: window.innerHeight / 2,
      })

      cancelFn()
      search()
    } catch (e) {
      return
    }
  }
}, 400)

/**
 * @description: 新增按钮打开弹窗
 */
function addDialog() {
  dialogVisible.value = true
}

/**
 * @description: 多选删除按钮
 */
async function deleteSection(arr: number[]) {
  try {
    await showConfirm('是否删除发货地址', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
  } catch {
    return
  }
  try {
    const ids = { ids: arr.join(',') }
    await deleteAddressByIds(ids)
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    search()
  } catch (e) {
    search()
    // showError(e)
  }
}

/**
 * @description: 日志弹窗
 */
interface LogList {
  id?: number
  createTime?: string
  description?: string
}
const logList = ref<LogList[]>([])

async function showLog(row: ShippingAddressObj) {
  logDialogVisible.value = true
  try {
    const { data } = await getLogisticsLog({
      logType: 'logistics_address',
      relaId: row.id as number,
    })
    logList.value = data
  } catch (error) {
    console.log(error)
  }
}
</script>

<style lang="scss" scoped>
.header-filter-form {
  margin-bottom: 20px;

  :deep(.el-form-item) {
    margin-right: 14px;
    margin-bottom: 10px;
  }
}

.user-operate-btn {
  margin-bottom: 10px;
}

.dialog-footer {
  text-align: center;
}

:deep() {
  .rowClass {
    background-color: red;
  }
}

.address-item {
  box-sizing: border-box;
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ececec;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .check {
    margin-right: 10px;
  }

  .left {
    flex: 1;
    flex-shrink: 0;
    overflow: hidden;
    margin-right: 10px;
  }

  .address {
    margin-bottom: 10px;
    font-size: 14px;
    overflow: hidden;
    /* 确保超出的文本被裁剪 */
    white-space: nowrap;
    /* 确保文本在一行内显示 */
    text-overflow: ellipsis;
    /* 超出的文本显示为省略号 */
    width: 100%;
  }

  .action {
    .iconView {
    }
  }

  .name {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;

    p {
      flex: 1;
      flex-shrink: 0;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin: 0 10px;
      font-size: 14px;
    }

    b {
      font-size: 17px;
    }

    span {
      margin: 0 10px;
      font-size: 14px;
    }
  }
}
</style>
