<template>
  <el-dialog title="转桌" width="700px" v-model="show" @close="reset">
    <el-form :rules="rules" ref="refForm" :model="form">
      <el-form-item label="转桌到" prop="targetTableCode">
        <el-select v-model="form.targetTableCode" placeholder="请选择转桌到" style="width: 200px">
          <el-option v-for="item in tableList" :key="item.id" :label="item.name" :value="item.tableCode"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="转入类型">
        <el-radio-group v-model="rottableType">
          <el-radio value="0" border>转桌(可将部分商品转入)</el-radio>
          <el-radio value="1" border>并桌(并台会将全部购物车商品转入)</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="购物车商品" v-if="rottableType == 0" label-position="top">
        <el-table border :data="nowCartGoods" ref="refTable">
          <el-table-column type="selection" width="55" />
          <el-table-column label="商品" prop="name"></el-table-column>
          <el-table-column label="数量" prop="number"></el-table-column>
          <el-table-column label="商品" prop="name"></el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label="历史订单商品" v-if="rottableType == 0" label-position="top">
        <div v-for="(oldGoods, index) in oldCartGoods" :key="index" style="width: 100%">
          <h4>第{{ index }} 次下单</h4>
          <el-table border :data="oldGoods" ref="oldTableRef">
            <el-table-column type="selection" width="55" />
            <el-table-column label="商品" prop="name"></el-table-column>
            <el-table-column label="数量" prop="number"></el-table-column>
            <el-table-column label="商品" prop="name"></el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import tableApi from "@/api/account/table";
import orderApi from "@/api/order/order";

const refForm = ref();
// 历史订单table
const oldTableRef = ref([]);

let rottableType = ref("0");

const basicForm = {
  sourceOrderId: "",
  targetOrderId: "",
  targetTableCode: "",
  detailIds: [],
  allMerge: 0 // 是否全部转台
};
const form = reactive({
  ...basicForm,
});
const rules = {
  targetTableCode: [{ required: true, message: "请选择目标桌码", trigger: "blur" }],
};
function reset() {
  Object.assign(form, basicForm);
  nowCartGoods.value = [];
  oldCartGoods.value = {};
}

const show = ref(false);
const nowCartGoods = ref([]);
const oldCartGoods = ref({});
function open(obj, nowCart, oldCart) {
  Object.assign(form, obj);
  show.value = true;
  nowCartGoods.value = nowCart;
  oldCartGoods.value = oldCart;
}
function close() {
  show.value = false;
}
const refTable = ref();
const tableList = ref([]);
function getTableList() {
  tableApi.getList({ page: 1, size: 999 }).then((res) => {
    tableList.value = res.records.filter((v) => v.tableCode);
  });
}
const emits = defineEmits(["success", "confirm"]);
function confirm() {
  refForm.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      let detailIds = [];
      let cart_id = [];
      cart_id =
        rottableType.value == 0
          ? refTable.value.getSelectionRows().map((v) => v.id)
          : nowCartGoods.value.map((v) => v.id);
      if (rottableType.value == 0) {
        for (let i = 0; i < oldTableRef.value.length; i++) {
          const table = oldTableRef.value[i];
          const detailId = table.getSelectionRows().map((v) => v.id);
          detailIds.push(...detailId);
        }
      } else {
        for (let i in oldCartGoods.value) {
          detailIds.push(...oldCartGoods.value[i].map((v) => v.id));
        }
      }
      if (detailIds.length == 0 && cart_id.length == 0) {
        return ElNotification({
          title: "失败",
          message: "请选择商品",
          type: "error",
        });
      }

      if (rottableType.value == 1) {
        form.allMerge = 1;
      } else {
        console.log('oldCartGoods.value===', oldCartGoods.value);
        const orderCount = Object.values(oldCartGoods.value).reduce((sum, arr) => {
          return sum + arr.length
        }, 0)
        form.allMerge = orderCount == detailIds.length ? 1 : 0
      }

      emits(
        "confirm",
        {
          ...form,
          detailIds,
        },
        cart_id
      );
      return;
      orderApi
        .mergeOrder({
          ...form,
          detailIds,
        })
        .then((res) => {
          emits("success", form.targetTableCode);
          close();
          ElNotification({
            title: "成功",
            message: "合并成功",
            type: "success",
          });
        });
    } else {
      console.log("error submit!", fields);
    }
  });
}

onMounted(() => {
  getTableList();
});
defineExpose({
  open,
  close,
});
</script>