<template>
  <el-drawer v-model="drawer.visible" :title="drawer.title" size="70%" direction="rtl" :before-close="handleClose">
    <div class="drawer-content">
      <!-- 分配方式选择 -->
      <div class="assign-type-selector">
        <el-radio-group v-model="assignType" @change="handleAssignTypeChange">
          <el-radio-button value="whole">整单分配</el-radio-button>
          <el-radio-button value="split">拆单分配</el-radio-button>
        </el-radio-group>
      </div>

      <el-divider />

      <!-- 整单分配表单 -->
      <div v-show="assignType === 'whole'" class="whole-assign-form">
        <el-form ref="wholeAssignFormRef" :model="wholeForm" :rules="wholeRules" label-width="120px">
          <el-form-item label="订单编号" v-if="orderInfo.orderNo">
            <span class="form-value">{{ orderInfo.orderNo }}</span>
          </el-form-item>

          <el-form-item label="当前平台" v-if="orderInfo.platformCode">
            <dict-tag :options="sys_platform_code" :value="orderInfo.platformCode" />
          </el-form-item>

          <el-form-item label="分配后平台" prop="platformAfter">
            <el-select v-model="wholeForm.platformAfter" placeholder="请选择平台" style="width: 100%" filterable clearable>
              <el-option v-for="dict in sys_platform_code" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-divider content-position="left">分配原因</el-divider>

          <el-form-item label-width="0" prop="remark">
            <el-input v-model="wholeForm.remark" type="textarea" :rows="6" placeholder="请输入分配原因（选填）" maxlength="500" show-word-limit />
          </el-form-item>
        </el-form>
      </div>

      <!-- 拆单分配表单 -->
      <div v-show="assignType === 'split'" class="split-assign-form">
        <el-form ref="splitAssignFormRef" :model="form" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="订单编号">
                <span class="form-value">{{ orderInfo.orderNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="当前平台">
                <dict-tag :options="sys_platform_code" :value="orderInfo.platformCode" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">商品列表</el-divider>

          <el-form-item label-width="0">
            <el-table :data="form.productList" border style="width: 100%" max-height="500">
              <el-table-column type="index" label="序号" width="60" align="center" />
              <el-table-column label="商品图片" width="100" align="center">
                <template #default="scope">
                  <el-image
                    v-if="scope.row.productImage"
                    :src="scope.row.productImage"
                    style="width: 60px; height: 60px"
                    fit="cover"
                    :preview-src-list="[scope.row.productImage]"
                  />
                  <span v-else style="color: #999">暂无图片</span>
                </template>
              </el-table-column>
              <el-table-column label="商品编号" prop="productNo" width="140" align="center" />
              <el-table-column label="商品名称" prop="productName" show-overflow-tooltip />
              <el-table-column label="数量" prop="orderQuantity" width="100" align="center" />
              <el-table-column label="单价" prop="orderPrice" width="120" align="center">
                <template #default="scope">
                  <span>¥{{ scope.row.orderPrice }}</span>
                </template>
              </el-table-column>
              <el-table-column label="小计" width="120" align="center">
                <template #default="scope">
                  <span>¥{{ (scope.row.orderPrice * scope.row.orderQuantity).toFixed(2) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="分配平台" align="center" fixed="right">
                <template #default="scope">
                  <el-select v-model="scope.row.targetPlatform" placeholder="请选择平台" style="width: 100%">
                    <el-option v-for="dict in sys_platform_code" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-divider content-position="left">分配原因</el-divider>

          <el-form-item label-width="0" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入分配原因（选填）" maxlength="500" show-word-limit />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button v-if="assignType === 'whole'" :loading="buttonLoading" type="primary" @click="submitWholeForm">确 定</el-button>
        <el-button v-else :loading="buttonLoading" type="primary" @click="submitSplitForm">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
.drawer-content {
  padding: 0 20px 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.assign-type-selector {
  display: flex;
  justify-content: center;
  padding: 10px 0;

  :deep(.el-radio-button__inner) {
    padding: 12px 30px;
    font-size: 14px;
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 10px 20px;
  border-top: 1px solid #e4e7ed;
}

.form-value {
  font-weight: 500;
  color: #303133;
}

:deep(.el-divider__text) {
  font-weight: 600;
  font-size: 14px;
}
</style>

<script setup name="SplitAssignDialog" lang="ts">
import { getOrderMain } from '@/api/order/orderMain';
import { addOrderSplitAssign, addOrderAssignment } from '@/api/order/orderAssignmentLog';
import { OrderSplitAssignForm, OrderProductAssignRule, OrderAssignmentForm } from '@/api/order/orderAssignmentLog/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_platform_code } = toRefs<any>(proxy?.useDict('sys_platform_code'));

const emit = defineEmits(['success']);

const buttonLoading = ref(false);
const splitAssignFormRef = ref<ElFormInstance>();
const wholeAssignFormRef = ref<ElFormInstance>();

// 分配类型：whole-整单分配，split-拆单分配
const assignType = ref<'whole' | 'split'>('whole');

const drawer = reactive<DialogOption>({
  visible: false,
  title: '订单分配'
});

const orderInfo = ref<any>({
  orderNo: '',
  id: undefined,
  platformCode: ''
});

// 拆单分配表单
const form = reactive({
  productList: [] as any[],
  remark: ''
});

// 整单分配表单
const wholeForm = reactive({
  platformAfter: '',
  remark: ''
});

const wholeRules = {
  platformAfter: [{ required: true, message: '分配后平台不能为空', trigger: 'blur' }]
};

/** 打开对话框 */
const open = async (orderId: string | number) => {
  reset();
  drawer.visible = true;
  assignType.value = 'whole'; // 默认显示整单分配

  try {
    // 获取订单详情
    const res = await getOrderMain(orderId);
    orderInfo.value = {
      orderNo: res.data.orderNo,
      id: res.data.id,
      platformCode: res.data.platformCode
    };

    // 加载订单商品列表（用于拆单分配）
    if (res.data.orderProductList && res.data.orderProductList.length > 0) {
      form.productList = res.data.orderProductList.map((item: any) => ({
        ...item,
        itemId: item.id, // 商品行ID
        targetPlatform: '' // 初始化分配平台为空
      }));
    }
  } catch (error) {
    proxy?.$modal.msgError('获取订单信息失败');
    drawer.visible = false;
  }
};

/** 分配类型切换 */
const handleAssignTypeChange = (value: 'whole' | 'split') => {
  // 切换时可以做一些清理工作
  if (value === 'split' && form.productList.length === 0) {
    proxy?.$modal.msgWarning('该订单没有商品信息，无法进行拆单分配');
    assignType.value = 'whole';
  }
};

/** 表单重置 */
const reset = () => {
  form.productList = [];
  form.remark = '';
  wholeForm.platformAfter = '';
  wholeForm.remark = '';
  assignType.value = 'whole';
  orderInfo.value = {
    orderNo: '',
    id: undefined,
    platformCode: ''
  };
  splitAssignFormRef.value?.resetFields();
  wholeAssignFormRef.value?.resetFields();
};

/** 取消按钮 */
const cancel = () => {
  drawer.visible = false;
  reset();
};

/** 关闭前的回调 */
const handleClose = (done: () => void) => {
  if (buttonLoading.value) {
    return;
  }
  done();
  reset();
};

/** 提交整单分配 */
const submitWholeForm = async () => {
  wholeAssignFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const submitData: OrderAssignmentForm = {
          orderIds: orderInfo.value.id,
          platformAfter: wholeForm.platformAfter,
          assignType: '0', // 整单分配
          remark: wholeForm.remark
        };

        await addOrderAssignment(submitData);
        proxy?.$modal.msgSuccess('整单分配成功');
        drawer.visible = false;
        emit('success');
      } catch (error) {
        proxy?.$modal.msgError('整单分配失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 提交拆单分配 */
const submitSplitForm = async () => {
  // 验证每个商品都选择了平台
  const unassignedProducts = form.productList.filter((item) => !item.targetPlatform);
  if (unassignedProducts.length > 0) {
    proxy?.$modal.msgWarning('请为所有商品选择分配平台');
    return;
  }

  buttonLoading.value = true;
  try {
    // 组装数据结构
    const submitData: OrderSplitAssignForm = {
      orderId: orderInfo.value.id,
      itemRules: form.productList.map(
        (product): OrderProductAssignRule => ({
          itemId: product.itemId,
          targetPlatform: product.targetPlatform
        })
      ),
      remark: form.remark
    };

    // 调用拆单分配接口
    await addOrderSplitAssign(submitData);
    proxy?.$modal.msgSuccess('拆单分配成功');
    drawer.visible = false;
    emit('success');
  } catch (error) {
    proxy?.$modal.msgError('拆单分配失败');
  } finally {
    buttonLoading.value = false;
  }
};

defineExpose({
  open
});
</script>
