<template>
  <el-container class="send">
    <el-main>
      <el-tabs class="sa-m-b-20" v-model="state.dispatch_type">
        <el-tab-pane v-if="state.nosendItem.length" :label="t('modules.order.expressDelivery')"
          name="express"></el-tab-pane>
        <el-tab-pane v-if="state.customItem.length" :label="t('modules.order.manualDelivery')"
          name="custom"></el-tab-pane>
      </el-tabs>
      <el-alert class="sa-alert sa-m-b-16">
        <template #title>{{ t('modules.order.deliveryTip') }}</template>
      </el-alert>
      <div v-if="state.dispatch_type == 'express'">
        <el-table ref="expressTableRef" class="sa-table" :data="state.nosendItem"
          @selection-change="handleSelectionChange">
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column type="selection" width="40" />
          <el-table-column :label="t('modules.order.productInfo')" min-width="360">
            <template #default="scope">
              <div class="sa-flex">
                <sa-image :url="scope.row.image" size="40"></sa-image>
                <div class="sa-m-l-8">{{ scope.row.productName }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.specification')" min-width="120">
            <template #default="scope">
              {{ scope.row.sku || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.quantity')" min-width="80">
            <template #default="scope">
              {{ scope.row.payNum }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.orderStatus')" min-width="140">
            <template #default="scope"> {{ t('modules.order.pendingShipment') }} </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.expressNumber')" min-width="80">
            <template #default>-</template>
          </el-table-column>
        </el-table>
        <div class="address">
          <div class="title sa-m-b-16">{{ t('modules.order.deliveryInfo') }}</div>
          <div class="sa-m-l-16" v-if="state.addressInfo">
            <div class="sa-flex sa-m-b-8">
              <div class="label">{{ t('modules.order.recipientInfo') }}：</div>
              <div class="content">
                {{ state.addressInfo?.realName }}&nbsp;
                {{ state.addressInfo?.phone || state.addressInfo?.userPhone }}
              </div>
            </div>
            <div class="sa-flex sa-col-top sa-m-b-16">
              <div class="label">{{ t('modules.order.recipientAddress') }}：</div>
              <div class="content">
                <div>
                  {{ state.addressInfo?.province }}&nbsp;
                  {{ state.addressInfo?.city }}&nbsp;
                  {{ state.addressInfo?.district }}
                </div>
                <div>{{ state.addressInfo?.detail }}</div>
                <div v-if="state.addressInfo?.postCode">
                  {{ t('modules.order.postalCode') }}：{{ state.addressInfo?.postCode }}
                </div>
              </div>
            </div>
          </div>
          <div v-if="!state.addressInfo" class="mb-20px text-14px text-red ml-20px">
            {{ t('modules.order.incompleteAddress') }}
          </div>
        </div>
        <div class="express">
          <div class="title sa-m-b-16">{{ t('modules.order.logisticsInfo') }}</div>
          <div class="sa-m-l-16">
            <el-form>
              <el-form-item :label="t('modules.order.shippingMethod')">
                <el-radio-group v-model="state.method">
                  <el-radio label="input">{{ t('modules.order.expressShipping') }}</el-radio>
                  <!-- <el-radio label="api">一键发货</el-radio> -->
                </el-radio-group>
              </el-form-item>
            </el-form>
            <el-form v-if="state.method == 'input'" ref="expressRef" :inline="true" :model="express"
              :rules="state.method == 'input' ? state.expressRules : {}">
              <el-form-item :label="t('modules.order.expressCompany')" prop="code">
                <el-select v-model="express.code" :placeholder="t('modules.order.selectExpressCompany')"
                  @change="onChangeExpressCode" filterable remote reserve-keyword :remote-method="remoteMethod"
                  :loading="deliverCompany.loading" autocomplete="none">
                  <el-option v-for="dc in deliverCompany.data" :key="dc" :label="dc.name" :value="dc.code"
                    :ref="`dc-${dc.code}`" :data-name="dc.name">{{ dc.name }}</el-option>
                  <div class="sa-p-l-15 sa-p-r-27">
                    <sa-pagination layout="total, prev, pager, next" :pageData="deliverCompany.pageData"
                      @updateFn="getDeliverCompany" />
                  </div>
                </el-select>
              </el-form-item>
              <el-form-item :label="t('modules.order.expressNumber')" prop="no">
                <el-input v-model="express.no" :placeholder="t('modules.order.enterExpressNumber')" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div v-if="state.dispatch_type == 'custom'">
        <el-table ref="customTableRef" class="sa-table" :data="state.customItem"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="48"></el-table-column>
          <el-table-column :label="t('modules.order.productInfo')" min-width="360">
            <template #default="scope">
              <div class="sa-flex">
                <sa-image :url="scope.row.goods_image" size="40"></sa-image>
                <div class="sa-m-l-8">{{ scope.row.goods_title }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="goods_num" :label="t('modules.order.quantity')" min-width="80"></el-table-column>
          <el-table-column prop="dispatch_status_text" :label="t('modules.order.orderStatus')" min-width="140">
            <template #default="scope">
              {{ scope.row.dispatch_status_text }}/{{ scope.row.aftersale_status_text }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.order.expressNumber')" min-width="80">
            <template #default>-</template>
          </el-table-column>
        </el-table>
        <el-form class="sa-m-t-20">
          <el-form-item label="发货类型：">
            <el-radio-group v-model="state.custom_type" @change="onChangeAutosendType">
              <el-radio label="text">固定内容</el-radio>
              <el-radio label="params">自定义内容</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="state.custom_type == 'text'" label="发货内容：">
            <el-input v-model="state.custom_content" placeholder="请输入自动发货内容"></el-input>
          </el-form-item>
          <el-form-item v-if="state.custom_type == 'params'" label="发货内容：">
            <div class="sa-template-wrap">
              <div class="title sa-flex">
                <div class="key">参数名称</div>
                <div class="key">内容</div>
                <div class="oper">操作</div>
              </div>
              <draggable v-model="state.custom_content" :animation="300" handle=".sortable-drag" item-key="element">
                <template #item="{ element, index }">
                  <div class="item">
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.title"> </el-input>
                    </el-form-item>
                    <el-form-item class="key">
                      <el-input placeholder="请输入" v-model="element.content"> </el-input>
                    </el-form-item>
                    <el-form-item class="oper">
                      <el-popconfirm width="fit-content" confirm-button-text="确认" cancel-button-text="取消"
                        title="确认删除这条记录?" @confirm="onDeleteContent(index)">
                        <template #reference>
                          <el-button type="danger" link @click.stop>删除 </el-button>
                        </template>
                      </el-popconfirm>
                      <i class="iconfont iconmove sortable-drag"></i>
                    </el-form-item>
                  </div>
                </template>
              </draggable>
              <el-button class="add-params" type="primary" plain icon="Plus" @click="onAddContent">添加
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button type="primary" :loading="state.sendLoading"
        :disabled="state.expressItem.length == 0 || state.sendLoading" @click="onSend">{{ t('modules.order.shipNow')
        }}</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { computed, getCurrentInstance, onMounted, reactive, ref, watch, nextTick } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElMessage } from 'element-plus';
import { api } from '../order.service';
import useExpress from '@/app/shop/admin/data/express/express.js';
import draggable from 'vuedraggable';

const { t } = useI18n();

const emit = defineEmits(['modalCallBack']);
const props = defineProps(['modal']);

const { proxy } = getCurrentInstance();

// 表格引用
const expressTableRef = ref();
const customTableRef = ref();

const state = reactive({
  nosendItem: computed(() => {
    console.log('发货弹窗接收到的数据:', props.modal);
    console.log('订单详情数据:', props.modal?.params?.data);

    if (!props.modal?.params?.data) return [];

    const data = props.modal.params.data;

    // 判断数据来源:
    // 1. 如果有 orderInfoVO 字段,说明是从详情页进入,使用 orderInfoVO
    if (data.orderInfoVO && Array.isArray(data.orderInfoVO)) {
      console.log('详情页数据结构,使用 orderInfoVO');
      return data.orderInfoVO;
    }

    // 2. 否则是从列表进入,直接使用 data 包装成数组
    console.log('列表页数据结构,使用 data');
    return [data];
  }),
  method: 'input',
  expressItem: [],
  expressRules: computed(() => ({
    code: [{ required: true, message: t('modules.order.selectExpressCompany'), trigger: 'none' }],
    no: [{ required: true, message: t('modules.order.enterExpressNumber'), trigger: 'none' }],
  })),
  sendLoading: false,

  dispatch_type: 'express',
  customItem: computed(() => {
    // 手动发货暂不支持，返回空数组
    return [];
  }),
  custom_type: 'text',
  custom_content: [],
  // 地址信息 - 需要通过订单号获取
  addressInfo: null,
});

function handleSelectionChange(val) {
  state.expressItem = val;
}

const { express, deliverCompany, getDeliverCompany, onChangeExpressCode, remoteMethod } =
  useExpress();
// TODO
async function onSend() {
  // 检查订单是否有收货地址信息
  if (!state.addressInfo || !state.addressInfo.realName || (!state.addressInfo.phone && !state.addressInfo.userPhone) || !state.addressInfo.detail) {
    ElMessage.error(t('modules.order.incompleteAddress'));
    return;
  }

  let order_item_ids = [];
  state.expressItem.forEach((item) => {
    order_item_ids.push(item.id);
  });
  if (state.dispatch_type == 'express') {
    if (state.method == 'input') {
      proxy.$refs.expressRef &&
        proxy.$refs.expressRef.validate(async (valid) => {
          if (valid) {
            const { name, no } = express;
            state.sendLoading = true;
            const { code } = await api.order.dispatch([
              {
                orderId: props.modal.params?.data?.orderId,
                deliveryName: name,
                deliveryNo: no,
              },
            ]);
            state.sendLoading = false;
            if (code == '200') {
              ElMessage.success(t('modules.order.sendSuccess'));
              emit('modalCallBack', { event: 'confirm' });
            }
          }
        });
    } else if (state.method == 'api') {
      state.sendLoading = true;
      const { code } = await api.order.dispatch({
        order_id: props.modal.data.id,
        order_item_ids,
        action: 'confirm',
        method: 'api',
      });
      state.sendLoading = false;
      if (code == '200') {
        ElMessage.success(t('modules.order.sendSuccess'));
        emit('modalCallBack', { event: 'confirm' });
      }
    }
  } else if (state.dispatch_type == 'custom') {
    const { code } = await api.order.customDispatch({
      order_id: props.modal.data.id,
      order_item_ids,
      custom_type: state.custom_type,
      custom_content: state.custom_content,
    });
    state.sendLoading = false;
    if (code == '200') {
      emit('modalCallBack', { event: 'confirm' });
    }
  }
}

function onChangeAutosendType(type) {
  state.custom_content = type == 'text' ? '' : [];
}
function onAddContent() {
  if (!state.custom_content) {
    state.custom_content = [];
  }
  state.custom_content.push({
    title: '',
    content: '',
  });
}
function onDeleteContent(index) {
  state.custom_content.splice(index, 1);
}

// 监听发货类型变化，自动选中所有商品
watch(
  () => state.dispatch_type,
  (newType) => {
    nextTick(() => {
      if (newType === 'express' && expressTableRef.value && state.nosendItem.length) {
        state.nosendItem.forEach((row) => {
          expressTableRef.value.toggleRowSelection(row, true);
        });
      } else if (newType === 'custom' && customTableRef.value && state.customItem.length) {
        state.customItem.forEach((row) => {
          customTableRef.value.toggleRowSelection(row, true);
        });
      }
    });
  },
);

// 获取订单地址信息
async function getOrderAddress() {
  const data = props.modal?.params?.data;
  if (!data) return;

  // 如果已经有 orderAddressVO (从详情页进入),直接使用
  if (data.orderAddressVO) {
    console.log('使用详情页已有的地址信息');
    state.addressInfo = data.orderAddressVO;
    return;
  }

  // 否则通过订单号请求地址信息 (从列表页进入)
  const orderId = data.orderId;
  if (!orderId) return;

  try {
    console.log('从列表页进入,请求订单地址信息');
    const { code, data: detailData } = await api.order.detail({ orderNo: orderId });
    if (code == '200' && detailData?.orderAddressVO) {
      state.addressInfo = detailData.orderAddressVO;
    }
  } catch (error) {
    console.error('获取订单地址失败:', error);
  }
}

onMounted(() => {
  // 获取订单地址信息
  getOrderAddress();

  if (state.nosendItem.length) {
    state.dispatch_type = 'express';
    // 默认选中所有快递发货商品
    nextTick(() => {
      if (expressTableRef.value) {
        state.nosendItem.forEach((row) => {
          expressTableRef.value.toggleRowSelection(row, true);
        });
      }
    });
  } else if (state.customItem.length) {
    state.dispatch_type = 'custom';
    // 默认选中所有手动发货商品
    nextTick(() => {
      if (customTableRef.value) {
        state.customItem.forEach((row) => {
          customTableRef.value.toggleRowSelection(row, true);
        });
      }
    });
  }
});
</script>
<style lang="scss" scoped>
.send {

  .address,
  .express {
    line-height: 16px;
    font-size: 12px;
    font-weight: 400;

    .title {
      height: 32px;
      line-height: 32px;
      padding: 0 16px;
      background: var(--sa-table-header-bg);
      border-radius: 4px;
      font-size: 12px;
      font-weight: 400;
      color: var(--sa-subtitle);
    }

    .label {
      color: var(--sa-subfont);
    }

    .content {
      color: var(--sa-subtitle);
    }
  }
}
</style>
