<template>
  <el-container class="is-vertical batchtable">
    <el-header class="sa-header">
      <el-tabs class="sa-tabs" v-model="state.status">
        <el-tab-pane
          v-for="(sl, key) in state.statusList"
          :key="sl"
          :label="`${sl.label}${
            state[key] && state[key].length > 0 ? '(' + state[key].length + ')' : ''
          }`"
          :name="key"
        ></el-tab-pane>
      </el-tabs>
      <template
        v-if="
          (state.status == 'all' || state.status == 'nosend') &&
          loop.index < state[state.status].length
        "
      >
        <div class="sa-flex sa-row-center sa-m-t-16">
          已完成：{{ (loop.index / state[state.status].length) * 100 }}%
        </div>
        <el-progress
          class="sa-m-t-8"
          :percentage="`${(loop.index / state[state.status].length) * 100}`"
        />
        <div class="sa-m-t-16">
          当前发货：{{ loop.item.province_name }}{{ loop.item.city_name }}{{ loop.item.area_name
          }}{{ loop.item.address }}
        </div>
      </template>
    </el-header>
    <el-main>
      <el-table height="100%" class="sa-table" :data="state[state.status]" stripe>
        <template #empty>
          <sa-empty />
        </template>
        <el-table-column prop="order_id" label="ID" min-width="80"></el-table-column>
        <el-table-column label="订单号" width="260">
          <template #default="scope">
            <div>
              {{ scope.row.order_sn }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="子订单" width="100">
          <template #default="scope">
            <div>共{{ scope.row.order_item_ids?.length }}单</div>
          </template>
        </el-table-column>
        <el-table-column label="发货状态" min-width="200">
          <template #default="scope">
            <div
              v-if="scope.row.dispatch_status || scope.row.dispatch_status == 0"
              :class="['sa-flex', `code-${scope.row.dispatch_status}`]"
            >
              <el-icon
                v-if="scope.row.dispatch_status != 0"
                class="sa-m-r-8"
                @click="onAloneDispatch(scope.$index)"
                ><Refresh
              /></el-icon>
              {{ scope.row.dispatch_status_text }}
            </div>
            <div v-else class="code-nosend">待发货</div>
          </template>
        </el-table-column>
        <el-table-column label="快递单号" min-width="260">
          <template #default="scope">
            <div>
              {{ scope.row.express ? scope.row.express.no : '-' }}
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer class="sa-footer--submit">
      <template v-if="state.status == 'all' && loop.index < state.all.length">
        <el-button @click="onStartDispatch">
          <sa-svg
            class="sa-m-r-4"
            :name="`sa-shop-order-${loop.index == 0 ? 'start' : 'continue'}`"
          ></sa-svg>
          {{ loop.index == 0 ? '开始' : '继续' }}
        </el-button>
        <el-button v-if="loop.index != 0" @click="onSuspendDispatch">
          <sa-svg class="sa-m-r-4" name="sa-shop-order-pause"></sa-svg>
          暂停</el-button
        >
      </template>
      <el-button
        v-if="state.status == 'error'"
        type="primary"
        icon="Refresh"
        @click="onAgainDispatch"
        >重新发货</el-button
      >
    </el-footer>
  </el-container>
</template>
<script setup>
  import { cloneDeep } from 'lodash';
  import { reactive } from 'vue';
  import { api } from '../order.service';

  const props = defineProps(['modal']);

  const state = reactive({
    status: 'all',
    statusList: {
      all: {
        label: '全部',
      },
      nosend: {
        label: '待发货',
      },
      success: {
        label: '成功',
      },
      error: {
        label: '失败',
      },
    },
    all: props.modal.params.data,
    nosend: cloneDeep(props.modal.params.data),
    success: [],
    error: [],
  });

  const loop = reactive({
    flag: false,
    index: 0,
    item: {},
  });

  // 开始
  function onStartDispatch() {
    loop.flag = true;
    loopDispatch('start');
  }

  function onSuspendDispatch() {
    loop.flag = false;
  }

  // 重新发货
  function onAgainDispatch() {
    loop.flag = true;
    loop.index = 0;
    state.error = [];
    loopDispatch('again');
  }

  // 循环发货
  async function loopDispatch(type) {
    // type = start | again
    if (loop.index >= state.all.length) {
      loop.index++;
    } else {
      // 1.开始直接循环 2.批量重新发货(过滤掉成功的)循环
      if (type == 'start' || (type == 'again' && state.all[loop.index].dispatch_status != 0)) {
        await onDispatch(loop.index, type);
      }
      loop.index++;
      if (loop.flag) {
        loopDispatch(type);
      }
    }
  }
  // 发货
  async function onDispatch(index = loop.index, type) {
    // 当前item
    loop.item = state.all[index];

    const { code } = await dispatchApi(index);

    // 数据分组 0成功 !0失败 error已发货
    if (code == '200') {
      state.success.push(state.all[index]);
    }
    if (code != '200') {
      state.error.push(state.all[index]);
    }

    if (type == 'start') {
      state.nosend = state.all.slice(index + 1);
    }
  }

  // 单独重新发货
  async function onAloneDispatch(index) {
    loop.item = state[state.status][index];
    let idx = state.all.findIndex((a) => a.order_id == loop.item.order_id);

    const { code } = await dispatchApi(idx);

    if (code == '200') {
      state.success.push(state.all[idx]);
      state.error.splice(index, 1);
    }
  }

  async function dispatchApi(index) {
    const { code, msg, data } = await api.order.dispatch({
      order_id: loop.item.order_id,
      order_item_ids: loop.item.order_item_ids,
      action: 'confirm',
      method: props.modal.params.method,
      express: loop.item.express,
    });

    state.all[index].dispatch_status = code;
    state.all[index].dispatch_status_text = msg;

    if (code == '200' && props.modal.params.method == 'api') {
      state.all[index].express = {
        name: data.name,
        code: data.code,
        no: data.no,
      };
    }

    return { code };
  }
</script>
<style lang="scss" scoped>
  .batchtable {
    .sa-header {
      .sa-tabs {
        margin-left: 0;
        margin-right: 0;
      }
    }
    .sa-tabs {
      :deep() {
        .el-tabs__nav-scroll {
          padding: 0;
        }
      }
    }
    .code-0 {
      color: #70c140;
    }
    .code-1 {
      color: #ff4d4f;
    }
    .code-nosend {
      color: #999;
    }
    :deep() {
      .el-progress__text {
        display: none;
      }
    }
  }
</style>
