<template>
  <WsMain>
    <WsTitle>等待出貨項目</WsTitle>
    <v-snackbar
      right
      top
      v-model="copyCompleteSnackbar"
      :timeout="2000"
    >訊息複製成功</v-snackbar>
    <v-row>
      <v-col
        cols="12"
        v-for="(user,userIndex) in _userWithDistributes"
        :key="userIndex"
      >
        <v-card>
          <v-card-text>
            <v-row>
              <v-col cols="6">
                <h5>收件人</h5>
                <div>{{user.receiver_name}}</div>
              </v-col>
              <v-col cols="6">
                <h5>瑪吉會員名稱</h5>
                <div>{{user.name}}</div>
              </v-col>
              <v-col cols="6">
                <h5>付款方式</h5>
                <div>{{user.pay_way}}</div>
              </v-col>
              <v-col cols="6">
                <h5>收件地址</h5>
                <div>{{user.receiver_address}}</div>
              </v-col>
            </v-row>
            <div
              v-for="(distribute,distributeIndex) in user.distributes"
              :key="distributeIndex"
            >
              <v-row>
                <v-col cols="6">{{distribute.product.name}}</v-col>
                <v-col cols="6">x {{distribute.count}}</v-col>
              </v-row>
            </div>
          </v-card-text>
          <v-card-actions>
            <v-spacer></v-spacer>
            <WsBtn
              outlined
              @click="$_onDeleteOpen(user)"
              color="deleteBtn white--text"
            >刪除</WsBtn>
            <WsBtn
              color="textSecondary"
              outlined
              @click="$_onIsCompleteTextCopyClick(user)"
            >已到齊訊息</WsBtn>
            <WsBtn
              color="textSecondary"
              outlined
              @click="$_onNotCompleteTextCopyClick(user)"
            >未到齊訊息</WsBtn>
            <WsBtn @click="$_onShipOpen(user)">確認出貨</WsBtn>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>
    <WsDialog ref="shipDialog">
      <template v-slot:content>
        <div style="min-height:380px">
          <ValidationObserver ref="shipDataForm">
            <v-form @submit.prevent>
              <WsState
                label="出貨日期"
                type="date"
                rules="required"
                v-model="shipData.date"
              ></WsState>
              <WsState
                label="備註"
                type="textarea"
                v-model="shipData.remark"
              ></WsState>
            </v-form>
          </ValidationObserver>
        </div>
      </template>
      <template v-slot:rightActions>
        <WsBtn
          @click="$_onShipCancel()"
          minWidth="100px"
          color="textSecondary"
          outlined
        >取消</WsBtn>
        <WsBtn
          @click="$_onShipSubmit()"
          minWidth="100px"
          :loading="shipSubmitLoading"
          color="primary"
        >送出</WsBtn>
      </template>
    </WsDialog>
    <!-- Delete Dialog -->
    <WsAlertDialog
      ref="deleteDialog"
      title="確定要刪除嗎？"
      description="刪除後資料將無法回覆"
      @submit="$_onDeleteSubmit($event)"
    />
  </WsMain>
</template>

<script>
export default {
  data: () => ({
    distributes: null,
    copyCompleteSnackbar: false,
    shipSubmitLoading: false,
    deleteSubmitLoading: false,
    shippingUser: null,
    shipData: {
      date: null,
      remark: null,
    },
  }),
  methods: {
    async $_onDeleteOpen(user) {
      this.$refs.deleteDialog.open(user);
    },
    async $_onDeleteSubmit(user) {
      try {
        this.$refs.deleteDialog.startLoading();
        const deleteTasks = [];
        user.distributes.forEach((distribute) => {
          deleteTasks.push(
            this.$axios.delete(`distribute_presale/${distribute.id}`)
          );
        });
        await Promise.all(deleteTasks);
        this.$_distributeSet();
        this.$refs.deleteDialog.close();
      } catch (error) {
        alert("刪除錯誤");
      } finally {
        this.$refs.deleteDialog.stopLoading();
      }
    },
    $_onShipCancel() {
      this.$refs.shipDialog.close();
    },
    async $_onShipSubmit() {
      const isValidate = await this.$refs.shipDataForm.validate();
      if (!isValidate) {
        return;
      }
      const distribute_presale_ids = [];
      this.shippingUser.distributes.forEach((distribute) => {
        distribute_presale_ids.push(distribute.id);
      });
      try {
        this.shipSubmitLoading = true;
        await this.$axios.post("ship_presale", {
          remark: this.shipData.remark,
          ship_at: this.$moment(this.shipData.date).format("YYYY-MM-DD"),
          receiver_name: this.shippingUser.distributes[0].order.receiver_name,
          receiver_address: this.shippingUser.distributes[0].order
            .receiver_address,
          pay_way: this.shippingUser.distributes[0].order.pay_way,
          distribute_presale_ids: distribute_presale_ids,
          user: this.shippingUser.distributes[0].user.id,
        });
        this.$refs.shipDialog.close();
        this.shipData.date = null;
        this.shipData.remark = "";
        this.$_distributeSet();
      } catch (error) {
        alert("新增出貨錯誤");
      } finally {
        this.shipSubmitLoading = false;
      }
    },
    $_onShipOpen(user) {
      this.shippingUser = user;
      this.$refs.shipDialog.open();
    },
    $_completeSnackbarOpen() {
      this.copyCompleteSnackbar = false;
      setTimeout(() => {
        this.copyCompleteSnackbar = true;
      }, 0);
    },
    async $_onIsCompleteTextCopyClick(user) {
      let distributeText = "";
      user.distributes.forEach((distribute, distributeIndex) => {
        if (distributeIndex > 0) {
          distributeText += `\n`;
        }
        distributeText += `${distribute.product.name} *${distribute.count}`;
      });
      await this.$copyText(
        `您好~~\n目前已到貨：\n${distributeText}\n今天會盡快為您出貨，不好意思讓您久等了。`
      );
      this.$_completeSnackbarOpen();
    },
    async $_onNotCompleteTextCopyClick(user) {
      let distributeText = "";
      user.distributes.forEach((distribute, distributeIndex) => {
        if (distributeIndex > 0) {
          distributeText += `\n`;
        }
        distributeText += `${distribute.product.name} *${distribute.count}`;
      });
      await this.$copyText(
        `您好~~\n目前已到貨：\n${distributeText}\n如商品到齊會盡快幫您出貨，謝謝您~`
      );
      this.$_completeSnackbarOpen();
    },
    async $_distributeSet() {
      this.distributes = [];
      try {
        const res = await this.$axios.get(this.distributeName, {
          params: {
            ship_id: "null",
          },
        });
        this.distributes = res.data.data;
      } catch (error) {
        alert("取得資料錯誤");
      }
    },
  },
  computed: {
    _userWithDistributes() {
      if (!this.distributes) {
        return null;
      }
      const _userWithDistributes = [];
      this.distributes.forEach((distribute) => {
        // const findReceiver = _userWithDistributes.find((e) => {
        //   return e.id == distribute.user.id&&e.;
        // });
        const findUser = _userWithDistributes.find((e) => {
          return (
            e.id == distribute.user.id &&
            e.distributes[0].order.receiver_name ==
              distribute.order.receiver_name &&
            e.distributes[0].order.receiver_address ==
              distribute.order.receiver_address &&
            e.distributes[0].order.pay_way == distribute.order.pay_way
          );
        });
        if (!findUser) {
          const newUser = distribute.user;
          newUser.receiver_name = distribute.order.receiver_name;
          newUser.receiver_address = distribute.order.receiver_address;
          newUser.pay_way = distribute.order.pay_way;
          newUser.distributes = [];
          newUser.distributes.push(distribute);
          _userWithDistributes.push(newUser);
        } else {
          findUser.distributes.push(distribute);
        }
      });
      return _userWithDistributes;
    },
  },
  mounted() {
    this.$_distributeSet();
  },
  props: {
    distributeName: {
      type: String,
      default: null,
    },
  },
};
</script>

<style>
</style>