<template>
  <el-drawer v-model="drawer.visible" :title="drawer.title" size="500px" direction="rtl" :before-close="handleClose">
    <div class="drawer-content">
      <el-form ref="orderAssignmentFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="订单编号" v-if="form.orderNo">
          <span class="form-value">{{ form.orderNo }}</span>
        </el-form-item>

        <el-form-item label="订单数量" v-if="orderCount > 1">
          <span class="form-value">{{ orderCount }} 个订单</span>
        </el-form-item>

        <el-divider v-if="form.platformCode" />

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

        <el-form-item label="分配后平台" prop="platformAfter">
          <el-select v-model="form.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="form.remark" type="textarea" :rows="6" placeholder="请输入分配原因（选填）" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="drawer-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

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

.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;
  font-size: 14px;
}

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

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>
<script setup name="OrderAssignmentDialog" lang="ts">
import { getOrderAssignment, addOrderAssignment, updateOrderAssignment } from '@/api/order/orderAssignmentLog';
import { 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 orderAssignmentFormRef = ref<ElFormInstance>();
const orderCount = ref(0); // 订单数量

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

const initFormData: OrderAssignmentForm = {
  id: undefined,
  orderId: undefined,
  orderIds: undefined,
  orderNo: undefined,
  platformBefore: undefined,
  platformAfter: undefined,
  assignedBy: undefined,
  assignTime: undefined,
  assignType: '0',
  status: undefined,
  remark: undefined
};

const data = reactive<PageData<OrderAssignmentForm, any>>({
  form: { ...initFormData },
  queryParams: {},
  rules: {
    platformAfter: [{ required: true, message: '分配后平台不能为空', trigger: 'blur' }]
  }
});

const { form, rules } = toRefs(data);

/** 打开对话框 */
const open = async (orderIds: Array<string | number>, orderNo?: string, platformCode?: string) => {
  reset();
  drawer.visible = true;
  drawer.title = orderIds.length > 1 ? '批量整单分配' : '整单分配';

  form.value.orderNo = orderNo;
  form.value.platformCode = platformCode;
  orderCount.value = orderIds.length;

  // 如果是单个订单，可以查询已有的分配信息
  if (orderIds.length === 1) {
    try {
      form.value.orderIds = orderIds[0] as string;
    } catch (error) {}
  } else {
    // 批量分配
    form.value.orderIds = orderIds.join(',');
  }
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  orderAssignmentFormRef.value?.resetFields();
};

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

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

/** 提交按钮 */
const submitForm = () => {
  orderAssignmentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateOrderAssignment(form.value);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addOrderAssignment(form.value);
          proxy?.$modal.msgSuccess('分配成功');
        }
        drawer.visible = false;
        emit('success');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

defineExpose({
  open
});
</script>
