<template>
  <div class="ws-product-distribute">
    <v-stepper
      v-model="step"
      class="elevation-0 transparent"
    >
      <v-stepper-header class="elevation-0">
        <v-stepper-step
          step="1"
          editable
        >
          商品分配設定
        </v-stepper-step>
        <v-divider></v-divider>
        <v-stepper-step
          step="2"
          editable
        >
          分配數量
        </v-stepper-step>
      </v-stepper-header>
      <v-stepper-items class="mt-5">
        <v-stepper-content
          step="1"
          class="pa-0"
        >
          <WsCard>
            <v-card-title>商品分配</v-card-title>
            <v-card-text style="min-height:390px">
              <v-row>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <WsState
                    type="select"
                    label="分配模式"
                    v-model="distributeMode"
                    :items="distributeItems"
                  ></WsState>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <WsState
                    type="belongsTo"
                    label="選擇商品"
                    v-model="product"
                    :modelName="productName"
                  ></WsState>
                </v-col>
                <v-col
                  cols="12"
                  sm="4"
                >
                  <WsState
                    type="number"
                    label="分配數量"
                    v-model="distributeCount"
                  ></WsState>
                </v-col>
              </v-row>
            </v-card-text>
          </WsCard>
        </v-stepper-content>
        <v-stepper-content
          step="2"
          class="pa-0"
        >
          <WsCard>
            <v-card-title>分配調整</v-card-title>
            <v-card-text style="min-height:390px">
              <p>商品數量：{{distributeCount}}</p>
              <p>分配總量：{{_distributeInputCount}}</p>
              <p>剩餘總量：{{distributeCount-_distributeInputCount}}</p>
              <v-row>
                <v-col
                  cols="12"
                  sm="3"
                >訂單建立時間</v-col>
                <v-col
                  cols="12"
                  sm="3"
                >平台及訂單號碼</v-col>
                <v-col
                  cols="12"
                  sm="3"
                >訂購人名稱</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >預定數量</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >已分配數量</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >本次分配數量</v-col>
              </v-row>
              <v-row
                v-for="(distribute,distributeIndex) in distributeList"
                :key="distributeIndex"
              >
                <v-col
                  cols="12"
                  sm="3"
                >{{$moment(distribute.order.created_at).format('YYYY.MM.DD')}}</v-col>
                <v-col
                  cols="12"
                  sm="3"
                >{{distribute.order.from_service}}-{{distribute.order.from_service_order_no}}</v-col>
                <v-col
                  cols="12"
                  sm="3"
                >{{distribute.order.receiver_name}}</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >{{distribute.order.count}}</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >{{$_getDistributedCount(distribute.order)}}</v-col>
                <v-col
                  cols="12"
                  sm="1"
                >
                  <WsState
                    type="number"
                    v-model="distributeList[distributeIndex].count"
                  ></WsState>
                </v-col>
              </v-row>
            </v-card-text>
          </WsCard>
        </v-stepper-content>
      </v-stepper-items>
    </v-stepper>
    <WsMainBottomNav>
      <template v-if="step==1">
        <WsBtn
          :loading="distributeLoading"
          @click="$_onDistributeClick()"
          minWidth="100px"
          color="primary"
          :disabled="!distributeCount||!product"
        >開始分配</WsBtn>
      </template>
      <template v-else-if="step==2">
        <WsBtn
          @click="$_onResetClick()"
          color="textSecondary"
          outlined
        >重新分配</WsBtn>
        <WsBtn
          :loading="distributeSubmitLoading"
          @click="$_onDistributeSubmit()"
          minWidth="100px"
          color="primary"
        >送出分配結果</WsBtn>
      </template>
      <!-- <template v-else-if="step==3">
        <WsBtn
          :loading="shipSubmitLoading"
          @click="$_onDistributeSubmitClick()"
          minWidth="100px"
          color="primary"
          :disabled="!shipDate"
        >建立出貨</WsBtn>
      </template> -->
    </WsMainBottomNav>
  </div>
</template>

<script>
export default {
  data: () => ({
    step: 1,
    shipSubmitLoading: false,
    distributeSubmitLoading: false,
    distributeCount: 0,
    shipDate: null,
    distributeList: [],
    distributeLoading: false,
    product: null,
    distributeMode: "earlybird",
    distributeItems: [
      {
        text: "早起鳥兒有蟲吃",
        value: "earlybird",
      },
      {
        text: "人人有獎",
        value: "allpeople",
      },
    ],
  }),
  computed: {
    _totalNeedCount() {
      let _totalNeedCount = 0;
      this.distributeList.forEach((tarDistribute) => {
        _totalNeedCount += this.$_getAvailableCount(tarDistribute.order);
      });
      return _totalNeedCount;
    },
    _distributeInputCount() {
      let _distributeInputCount = 0;
      this.distributeList.forEach((tarDistribute) => {
        _distributeInputCount += parseInt(tarDistribute.count);
      });
      return _distributeInputCount;
    },
  },
  methods: {
    $_getDistributedCount(order) {
      let distributedCount = 0;
      if (order.distribute_presales) {
        order.distribute_presales.forEach(
          (distribute_presale) => {
            distributedCount += distribute_presale.count;
          }
        );
      }
      return distributedCount;
    },
    async $_onDistributeSubmit() {
      this.distributeSubmitLoading = true;
      const postTasks = [];
      this.distributeList.forEach((distribute) => {
        if (distribute.count <= 0) {
          return;
        }
        postTasks.push(
          this.$axios.post(this.distributeName, {
            product: this.product,
            user: distribute.user.id,
            order: distribute.order.id,
            count: distribute.count,
          })
        );
      });
      try {
        await Promise.all(postTasks);
        this.distributeList = [];
        this.distributeCount = 0;
        this.product = null;
        this.step = 1;
      } catch (error) {
        alert("分配送出錯誤");
      } finally {
        this.distributeSubmitLoading = false;
      }
    },
    $_onResetClick() {
      this.distributeList = [];
      this.step = 1;
    },
    async $_onDistributeSubmitClick() {
      const shipDatas = [];
      this.distributeList.forEach((distribute) => {
        if (distribute.count > 0) {
          shipDatas.push({
            product: this.product,
            user: distribute.user.id,
            order: distribute.order.id,
            count: distribute.count,
            ship_date: this.$moment(this.shipDate).format("YYYY-MM-DD"),
          });
        }
      });

      try {
        this.distributeSubmitLoading = true;
        await this.$axios.post(`${this.shipName}/create/batch`, {
          datas: shipDatas,
        });
        this.$router.push(this.redirectRoute);
      } catch (error) {
        alert("建立出貨錯誤");
      } finally {
        this.distributeSubmitLoading = false;
      }
    },
    $_getAvailableCount(order) {
      let availableCount = parseInt(order.count);
      if (order.distribute_presales) {
        order.distribute_presales.forEach(
          (distribute_presale) => {
            availableCount -= distribute_presale.count;
          }
        );
      }
      return availableCount;
    },
    $_distributeSet() {
      if (this.distributeCount >= this._totalNeedCount) {
        this.distributeList.forEach((tarDistribute) => {
          tarDistribute.count = this.$_getAvailableCount(tarDistribute.order);
        });
      } else if (this.distributeMode == "earlybird") {
        let totalCount = this.distributeCount;
        let countingIndex = 0;
        while (totalCount > 0) {
          const tarDistribute = this.distributeList[countingIndex];
          if (totalCount >= this.$_getAvailableCount(tarDistribute.order)) {
            tarDistribute.count = this.$_getAvailableCount(tarDistribute.order);
            totalCount -= this.$_getAvailableCount(tarDistribute.order);
          } else {
            tarDistribute.count = totalCount;
            totalCount = 0;
          }
          countingIndex++;
          if (countingIndex >= this.distributeList.lengh) {
            countingIndex = 0;
          }
        }
      } else if (this.distributeMode == "allpeople") {
        let totalCount = this.distributeCount;
        let countingIndex = 0;
        while (totalCount > 0) {
          const tarDistribute = this.distributeList[countingIndex];
          tarDistribute.count += 1;
          totalCount--;
          countingIndex++;
          if (countingIndex >= this.distributeList.lengh) {
            countingIndex = 0;
          }
        }
      }
    },
    $_getDistributeListFromOrders(orders) {
      const _distributeList = [];
      orders.forEach((order) => {
        _distributeList.push({
          order: order,
          user: order.user,
          product: null,
          count: 0,
        });
      });
      return _distributeList;
    },
    async $_onDistributeClick() {
      try {
        this.distributeLoading = true;
        const params = {
          product: this.product,
          order_by: "created_at",
          order_way: "asc",
          done: 0,
        };
        const res = await this.$axios.get(`${this.orderName}`, {
          params: params,
        });
        this.distributeList = this.$_getDistributeListFromOrders(res.data.data);
        this.$_distributeSet();
        this.step = 2;
      } catch (error) {
        alert("讀取訂單錯誤");
      } finally {
        this.distributeLoading = false;
      }
    },
  },
  props: {
    orderName: {
      type: String,
      default: "order",
    },
    productName: {
      type: String,
      default: "product",
    },
    distributeName: {
      type: String,
      default: "distribute",
    },
    shipName: {
      type: String,
      default: "ship",
    },
    redirectRoute: {
      type: String,
      default: "/ship",
    },
  },
};
</script>

<style lang="scss">
@import "../assets/scss/ws-product-distribute.scss";
</style>