<!-- 订单发货弹窗 -->
<template>
  <a-modal
    :visible="visible"
    title="订单发送货"
    width="50%"
    :confirm-loading="loading"
    @update:visible="updateVisible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <!-- 配送方式 -->
      <a-form-item label="配送方式" name="deliveryType">
        <a-radio-group v-model:value="form.deliveryType">
          <a-radio :value="0">
            <span style="color: #1890ff">快递配送</span>
          </a-radio>
          <a-radio :value="2">商家送货</a-radio>
          <a-radio :value="1">无需发货</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 发货类型 -->
      <a-form-item
        v-if="form.deliveryType === 0"
        label="发货类型"
        name="deliveryMethod"
      >
        <a-radio-group v-model:value="form.deliveryMethod">
          <a-radio value="manual">
            <span style="color: #1890ff">手动填写</span>
          </a-radio>
          <a-radio value="print">电子面单打印</a-radio>
        </a-radio-group>
      </a-form-item>

      <!-- 快递公司 -->
      <a-form-item
        label="快递公司"
        name="expressId"
        v-if="form.deliveryType === 0"
      >
        <a-row :gutter="8">
          <a-col :span="18">
            <a-select
              v-model:value="form.expressId"
              placeholder="请选择"
              show-search
              :filter-option="filterExpressOption"
              @change="onExpressChange"
            >
              <a-select-option
                v-for="express in expressList"
                :key="express.expressId"
                :value="express.expressId"
              >
                {{ express.expressName }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="openExpressModal">
              设置物流公司
            </a-button>
          </a-col>
        </a-row>
      </a-form-item>

      <!-- 物流单号 -->
      <a-form-item
        label="物流单号"
        name="expressNo"
        v-if="form.deliveryType === 0"
      >
        <a-input
          v-model:value="form.expressNo"
          placeholder="请输入物流单号"
          :maxlength="50"
        />
      </a-form-item>

      <template v-if="form.deliveryType !== 1">
        <!-- 发货门店：快递配送=发货仓库，商家送货=配送门店 -->
        <a-form-item
          :label="form.deliveryType === 0 ? '发货门店' : '配送门店'"
          name="sendStoreId"
        >
          <a-select
            v-model:value="form.sendStoreId"
            :placeholder="form.deliveryType === 0 ? '请选择发货门店' : '请选择配送门店'"
            @change="onStoreChange"
          >
            <a-select-option
              v-for="store in storeList"
              :key="store.id"
              :value="store.id"
            >
              {{ store.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 商家送货：配送店员，依赖门店二级联动 -->
        <a-form-item
          label="配送店员"
          name="deliveryUserId"
          v-if="form.deliveryType === 2"
        >
          <a-select
            v-model:value="form.deliveryUserId"
            placeholder="请先选择门店"
            :disabled="!form.sendStoreId"
            @change="onUserChange"
          >
            <a-select-option
              v-for="user in userList"
              :key="user.id"
              :value="user.id"
            >
              {{ user.name }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <div style="color: #999; font-size: 12px; margin: 4px 0 12px">
          {{
            form.deliveryType === 0
              ? '选择发货门店后，将自动回填寄件人信息（快递配送时，寄件人即为发货门店）'
              : '选择配送门店后，将自动回填配送店员信息'
          }}，可手动修改
        </div>

        <a-form-item
          :label="form.deliveryType === 0 ? '寄件人' : '发货人'"
          name="sendName"
        >
          <a-input
            v-model:value="form.sendName"
            :placeholder="form.deliveryType === 0 ? '请输入寄件人' : '请输入发货人'"
            :maxlength="50"
          />
          <div
            v-if="form.deliveryType === 0"
            style="color: #999; font-size: 12px; margin-top: 4px"
          >
            快递配送场景下，寄件人信息将同步至快递面单
          </div>
        </a-form-item>
        <a-form-item
          :label="form.deliveryType === 0 ? '寄件人联系方式' : '发货人联系方式'"
          name="sendPhone"
        >
          <a-input
            v-model:value="form.sendPhone"
            :placeholder="form.deliveryType === 0 ? '请输入寄件人联系方式' : '请输入发货人联系方式'"
            :maxlength="50"
          />
        </a-form-item>
        <a-form-item label="发货地址" name="sendAddress">
          <a-input
            v-model:value="form.sendAddress"
            placeholder="请输入发货地址"
          />
        </a-form-item>
      </template>

      <!--      &lt;!&ndash; 分单发货 &ndash;&gt;-->
      <!--      <a-form-item label="分单发货" v-if="form.deliveryType === 0">-->
      <!--        <a-switch-->
      <!--          v-model:checked="form.partialDelivery"-->
      <!--          checked-children="支持"-->
      <!--          un-checked-children="不支持"-->
      <!--        />-->
      <!--      </a-form-item>-->

      <!-- 发货备注 -->
      <a-form-item label="发货备注" name="deliveryNote">
        <a-textarea
          v-model:value="form.deliveryNote"
          placeholder="请输入发货备注（可选）"
          :rows="3"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <!-- 发货时间 -->
      <a-form-item label="发货时间" name="deliveryTime">
        <a-date-picker
          v-model:value="form.deliveryTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择发货时间"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>

    <!-- 快递公司设置弹窗 -->
    <express-setting-modal
      v-model:visible="expressModalVisible"
      @done="loadExpressList"
    />
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { ShopOrder } from '@/api/shop/shopOrder/model';
  import { updateShopOrder } from '@/api/shop/shopOrder';
  import { listShopExpress } from '@/api/shop/shopExpress';
  import { ShopExpress } from '@/api/shop/shopExpress/model';
  import { listShopStore } from '@/api/shop/shopStore';
  import { ShopStore } from '@/api/shop/shopStore/model';
  import { listShopStoreUser } from '@/api/shop/shopStoreUser';
  import { ShopStoreUser } from '@/api/shop/shopStoreUser/model';
  import { toDateString } from 'ele-admin-pro';
  import dayjs, { Dayjs } from 'dayjs';
  import ExpressSettingModal from './expressSettingModal.vue';

  const useForm = Form.useForm;

  const props = defineProps<{
    visible: boolean;
    data?: ShopOrder | null;
  }>();

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

  // 表单数据
  const form = reactive({
    deliveryType: 0, // 0快递配送 1无需发货 2商家送货
    deliveryMethod: 'manual', // manual手动填写 print电子面单打印
    expressId: undefined as number | undefined,
    expressName: '',
    expressNo: '',
    partialDelivery: false,
    deliveryNote: '',
    sendName: '',
    sendPhone: '',
    sendAddress: '',
    sendStoreId: undefined as number | undefined, // 发货门店/配送门店
    deliveryUserId: undefined as number | undefined, // 配送店员
    deliveryTime: dayjs() as Dayjs
  });

  // 表单验证规则
  const rules = {
    deliveryType: [{ required: true, message: '请选择配送方式' }],
    deliveryMethod: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType === 0 && !value) {
            return Promise.reject('请选择发货类型');
          }
          return Promise.resolve();
        }
      }
    ],
    expressId: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType === 0 && !value) {
            return Promise.reject('请选择快递公司');
          }
          return Promise.resolve();
        }
      }
    ],
    expressNo: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType === 0 && !value) {
            return Promise.reject('请输入物流单号');
          }
          return Promise.resolve();
        }
      }
    ],
    deliveryTime: [{ required: true, message: '请选择发货时间' }],
    sendName: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType !== 1 && !value) {
            return Promise.reject(
              form.deliveryType === 0 ? '请输入寄件人' : '请输入发货人'
            );
          }
          return Promise.resolve();
        }
      }
    ],
    sendPhone: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType !== 1 && !value) {
            return Promise.reject(
              form.deliveryType === 0
                ? '请输入寄件人联系方式'
                : '请输入发货人联系方式'
            );
          }
          return Promise.resolve();
        }
      }
    ],
    sendAddress: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType !== 1 && !value) {
            return Promise.reject('请输入发货地址');
          }
          return Promise.resolve();
        }
      }
    ],
    sendStoreId: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType !== 1 && !value) {
            return Promise.reject(
              form.deliveryType === 0 ? '请选择发货门店' : '请选择配送门店'
            );
          }
          return Promise.resolve();
        }
      }
    ],
    deliveryUserId: [
      {
        validator: (_: any, value: any) => {
          if (form.deliveryType === 2 && !value) {
            return Promise.reject('请选择配送店员');
          }
          return Promise.resolve();
        }
      }
    ]
  };

  const formRef = ref();
  const { resetFields, validate } = useForm(form, rules);

  // 状态
  const loading = ref(false);
  const expressList = ref<ShopExpress[]>([]);
  const storeList = ref<ShopStore[]>([]);
  const userList = ref<ShopStoreUser[]>([]);
  const expressModalVisible = ref(false);

  // 加载快递公司列表
  const loadExpressList = async () => {
    try {
      const data = await listShopExpress({});
      expressList.value = data || [];
    } catch (error) {
      console.error('加载快递公司失败:', error);
    }
  };

  // 加载门店列表
  const loadStoreList = async () => {
    try {
      const data = await listShopStore({});
      storeList.value = data || [];
    } catch (error) {
      console.error('加载门店失败:', error);
    }
  };

  // 加载指定门店下的店员
  const loadUserList = async (storeId?: number) => {
    if (!storeId) {
      userList.value = [];
      return;
    }
    try {
      const data = await listShopStoreUser({ storeId });
      userList.value = data || [];
    } catch (error) {
      console.error('加载店员失败:', error);
    }
  };

  // 门店选择变化
  const onStoreChange = (storeId: number) => {
    const store = storeList.value.find((item) => item.id === storeId);
    if (store) {
      // 发货地址统一回填写门店地址
      form.sendAddress = store.address || '';
      if (form.deliveryType === 0) {
        // 快递配送：门店作为发货方，直接回填发货人与联系方式
        form.sendName = store.name || '';
        form.sendPhone = store.phone || '';
      }
      if (form.deliveryType === 2) {
        // 商家送货：切换门店后清空已选店员并重新加载
        form.deliveryUserId = undefined;
        loadUserList(storeId);
      }
    }
  };

  // 店员选择变化
  const onUserChange = (userId: number) => {
    const user = userList.value.find((item) => item.id === userId);
    if (user) {
      form.sendName = user.name || '';
      form.sendPhone = user.phone || '';
    }
  };

  // 快递公司筛选
  const filterExpressOption = (input: string, option: any) => {
    return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  // 快递公司选择变化
  const onExpressChange = (value: number) => {
    const express = expressList.value.find((item) => item.expressId === value);
    if (express) {
      form.expressName = express.expressName || '';
    }
  };

  // 打开快递公司设置
  const openExpressModal = () => {
    expressModalVisible.value = true;
  };

  // 根据配送方式重置不需要的字段
  watch(
    () => form.deliveryType,
    (type) => {
      if (type !== 0) {
        form.expressId = undefined;
        form.expressName = '';
        form.expressNo = '';
        form.deliveryMethod = 'manual';
      }
      if (type === 1) {
        form.sendName = '';
        form.sendPhone = '';
        form.sendAddress = '';
        form.sendStoreId = undefined;
        form.deliveryUserId = undefined;
        userList.value = [];
      }
    }
  );

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

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

  // 提交发货
  const handleSubmit = async () => {
    try {
      await validate();
      loading.value = true;

      const deliveryTime = toDateString(
        form.deliveryTime.toDate(),
        'yyyy-MM-dd HH:mm:ss'
      );

      const updateData = {
        ...props.data,
        deliveryStatus: 20, // 已发货
        deliveryType: form.deliveryType,
        deliveryTime: deliveryTime,
        deliveryNote: form.deliveryNote
      };

      // 如果是快递配送，添加快递信息
      if (form.deliveryType === 0) {
        const express =
          expressList.value.find((item) => item.expressId === form.expressId) ||
          undefined;
        updateData.expressId = form.expressId;
        updateData.sendName = form.sendName;
        updateData.sendPhone = form.sendPhone;
        updateData.sendAddress = form.sendAddress;
        updateData.sendStoreId = form.sendStoreId;
        updateData.deliveryUserId = undefined;
        updateData.expressName = form.expressName || express?.expressName;
        updateData.expressNo = form.expressNo;
      } else if (form.deliveryType === 2) {
        // 商家送货需要记录发货人信息，但不需要快递公司
        updateData.sendName = form.sendName;
        updateData.sendPhone = form.sendPhone;
        updateData.sendAddress = form.sendAddress;
        updateData.sendStoreId = form.sendStoreId;
        updateData.deliveryUserId = form.deliveryUserId;
        updateData.expressId = undefined;
        updateData.expressName = undefined;
        updateData.expressNo = undefined;
      } else {
        // 无需发货，清理快递/发货信息
        updateData.expressId = undefined;
        updateData.sendName = undefined;
        updateData.sendPhone = undefined;
        updateData.sendAddress = undefined;
        updateData.expressName = undefined;
        updateData.expressNo = undefined;
      }

      // 分单发货
      if (form.partialDelivery) {
        updateData.deliveryStatus = 30;
      }

      await updateShopOrder(updateData);

      message.success('发货成功');
      emit('done');
      updateVisible(false);
    } catch (error: any) {
      console.log(error);
      message.error(error.message || '发货失败');
    } finally {
      loading.value = false;
    }
  };

  // 监听弹窗显示状态
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        // 重置表单
        form.deliveryType = 0;
        form.deliveryMethod = 'manual';
        form.expressId = undefined;
        form.expressName = '';
        form.expressNo = '';
        form.partialDelivery = false;
        form.deliveryNote = '';
        form.sendName = '';
        form.sendPhone = '';
        form.sendAddress = '';
        form.sendStoreId = undefined;
        form.deliveryUserId = undefined;
        userList.value = [];
        form.deliveryTime = dayjs();

        // 加载快递公司列表与门店列表
        loadExpressList();
        loadStoreList();
      } else {
        resetFields();
      }
    }
  );
</script>

<style scoped>
  .ant-radio-wrapper {
    margin-right: 16px;
  }
</style>
