<!-- 快递公司设置弹窗 -->
<template>
  <a-modal
    :visible="visible"
    title="设置物流公司"
    width="900px"
    :confirm-loading="loading"
    @update:visible="updateVisible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="express-setting">
      <!-- 搜索栏 -->
      <div class="search-bar" style="margin-bottom: 16px">
        <a-input-search
          v-model:value="searchKeyword"
          placeholder="搜索快递公司名称"
          style="width: 300px"
          @search="handleSearch"
        />
        <a-button type="primary" style="margin-left: 8px" @click="openAddModal">
          添加快递公司
        </a-button>
      </div>

      <!-- 快递公司列表 -->
      <a-table
        :data-source="filteredExpressList"
        :columns="columns"
        :pagination="false"
        :scroll="{ y: 400 }"
        row-key="expressId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-switch
              v-model:checked="record.enabled"
              checked-children="启用"
              un-checked-children="禁用"
              @change="handleStatusChange(record)"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="editExpress(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除此快递公司吗？"
                @confirm="deleteExpress(record)"
              >
                <a class="text-red-500">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑快递公司弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      :title="editingExpress ? '编辑快递公司' : '添加快递公司'"
      width="500px"
      :confirm-loading="addLoading"
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="快递公司名称" name="expressName">
          <a-input
            v-model:value="addForm.expressName"
            placeholder="请输入快递公司名称"
            :maxlength="50"
          />
        </a-form-item>

        <a-form-item label="微信编码" name="wxCode">
          <a-input
            v-model:value="addForm.wxCode"
            placeholder="请输入微信快递编码（可选）"
            :maxlength="20"
          />
        </a-form-item>

        <a-form-item label="快递100编码" name="kuaidi100Code">
          <a-input
            v-model:value="addForm.kuaidi100Code"
            placeholder="请输入快递100编码（可选）"
            :maxlength="20"
          />
        </a-form-item>

        <a-form-item label="快递鸟编码" name="kdniaoCode">
          <a-input
            v-model:value="addForm.kdniaoCode"
            placeholder="请输入快递鸟编码（可选）"
            :maxlength="20"
          />
        </a-form-item>

        <a-form-item label="排序号" name="sortNumber">
          <a-input-number
            v-model:value="addForm.sortNumber"
            placeholder="数字越小越靠前"
            :min="0"
            :max="9999"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { ShopExpress } from '@/api/shop/shopExpress/model';
  import {
    listShopExpress,
    addShopExpress,
    updateShopExpress,
    removeShopExpress
  } from '@/api/shop/shopExpress';

  const useForm = Form.useForm;

  const props = defineProps<{
    visible: boolean;
  }>();

  const emit = defineEmits<{
    (e: 'update:visible', visible: boolean): void;
    (e: 'done'): void;
  }>();

  // 状态
  const loading = ref(false);
  const searchKeyword = ref('');
  const expressList = ref<ShopExpress[]>([]);
  const addModalVisible = ref(false);
  const addLoading = ref(false);
  const editingExpress = ref<ShopExpress | null>(null);

  // 添加表单
  const addForm = reactive({
    expressName: '',
    wxCode: '',
    kuaidi100Code: '',
    kdniaoCode: '',
    sortNumber: 0
  });

  const addRules = {
    expressName: [
      { required: true, message: '请输入快递公司名称' },
      { min: 2, max: 50, message: '快递公司名称长度为2-50个字符' }
    ]
  };

  const addFormRef = ref();
  const { resetFields: resetAddFields, validate: validateAdd } = useForm(
    addForm,
    addRules
  );

  // 表格列定义
  const columns = [
    {
      title: '快递公司名称',
      dataIndex: 'expressName',
      key: 'expressName',
      width: 150
    },
    {
      title: '微信编码',
      dataIndex: 'wxCode',
      key: 'wxCode',
      width: 100
    },
    {
      title: '快递100编码',
      dataIndex: 'kuaidi100Code',
      key: 'kuaidi100Code',
      width: 120
    },
    {
      title: '快递鸟编码',
      dataIndex: 'kdniaoCode',
      key: 'kdniaoCode',
      width: 120
    },
    {
      title: '排序号',
      dataIndex: 'sortNumber',
      key: 'sortNumber',
      width: 80,
      align: 'center'
    },
    {
      title: '状态',
      key: 'status',
      width: 100,
      align: 'center'
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      align: 'center'
    }
  ];

  // 过滤后的快递公司列表
  const filteredExpressList = computed(() => {
    if (!searchKeyword.value) {
      return expressList.value;
    }
    return expressList.value.filter((item) =>
      item.expressName
        ?.toLowerCase()
        .includes(searchKeyword.value.toLowerCase())
    );
  });

  // 加载快递公司列表
  const loadExpressList = async () => {
    try {
      loading.value = true;
      const data = await listShopExpress({});
      expressList.value = (data || []).map((item) => ({
        ...item,
        enabled: item.deleted === 0 // 假设deleted=0表示启用
      }));
    } catch (error) {
      console.error('加载快递公司失败:', error);
      message.error('加载快递公司失败');
    } finally {
      loading.value = false;
    }
  };

  // 搜索
  const handleSearch = () => {
    // 搜索逻辑已在computed中处理
  };

  // 状态变化
  const handleStatusChange = async (
    record: ShopExpress & { enabled: boolean }
  ) => {
    try {
      await updateShopExpress({
        ...record,
        deleted: record.enabled ? 0 : 1
      });
      message.success(record.enabled ? '已启用' : '已禁用');
    } catch (error: any) {
      message.error(error.message || '操作失败');
      // 恢复状态
      record.enabled = !record.enabled;
    }
  };

  // 打开添加弹窗
  const openAddModal = () => {
    editingExpress.value = null;
    resetAddFields();
    addModalVisible.value = true;
  };

  // 编辑快递公司
  const editExpress = (record: ShopExpress) => {
    editingExpress.value = record;
    addForm.expressName = record.expressName || '';
    addForm.wxCode = record.wxCode || '';
    addForm.kuaidi100Code = record.kuaidi100Code || '';
    addForm.kdniaoCode = record.kdniaoCode || '';
    addForm.sortNumber = record.sortNumber || 0;
    addModalVisible.value = true;
  };

  // 删除快递公司
  const deleteExpress = async (record: ShopExpress) => {
    try {
      if (record.expressId) {
        await removeShopExpress(record.expressId);
        message.success('删除成功');
        loadExpressList();
      }
    } catch (error: any) {
      message.error(error.message || '删除失败');
    }
  };

  // 添加/编辑提交
  const handleAddSubmit = async () => {
    try {
      await validateAdd();
      addLoading.value = true;

      if (editingExpress.value) {
        // 编辑
        await updateShopExpress({
          ...editingExpress.value,
          ...addForm
        });
        message.success('编辑成功');
      } else {
        // 添加
        await addShopExpress(addForm);
        message.success('添加成功');
      }

      addModalVisible.value = false;
      loadExpressList();
    } catch (error: any) {
      message.error(error.message || '操作失败');
    } finally {
      addLoading.value = false;
    }
  };

  // 取消添加/编辑
  const handleAddCancel = () => {
    addModalVisible.value = false;
    resetAddFields();
  };

  // 更新弹窗显示状态
  const updateVisible = (visible: boolean) => {
    emit('update:visible', visible);
  };

  // 取消
  const handleCancel = () => {
    updateVisible(false);
  };

  // 确定
  const handleSubmit = () => {
    emit('done');
    updateVisible(false);
  };

  // 监听弹窗显示状态
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        loadExpressList();
      }
    }
  );
</script>

<style scoped>
  .express-setting {
    min-height: 400px;
  }

  .search-bar {
    display: flex;
    align-items: center;
  }
</style>
