<template>
  <div>
    <h3
      v-if="flashSaleData.title"
      class="text-warning"
    >
      {{ flashSaleData.title }}
    </h3>

    <div
      style="text-align: right"
      class="mb-20 mr-20"
    >
      <Button
        v-if="isPrevStep"
        type="warning"
        class="mr-5"
        :loading="step.loading"
        :disabled="!isValidNext"
        @click="prevStep"
      >
        <Icon type="md-arrow-back" />
        {{ $t('STEP_PREVIOUS_BTN') }}
      </Button>
      <Button
        v-if="isNextStep"
        type="info"
        :loading="step.loading"
        :disabled="!isValidNext"
        @click="nextStep"
      >
        {{ $t('STEP_NEXT_BTN') }}
        <Icon type="md-arrow-forward" />
      </Button>
    </div>

    <div class="mb-20">
      <Steps :current="step.current">
        <Step
          v-for="item in stepList"
          :key="item.key"
          :name="item.key"
          :title="item.label"
        />
      </Steps>
    </div>

    <div class="mt-50">
      <!--Tutorial-->
      <div v-if="stepKey === 'step-tutorial'">
        <Row>
          <Col
            :span="12"
            :offset="6"
          >
            <div class="mb-20 row-end">
              <Button
                type="info"
                ghost
                @click="openExternalUrl(configApp.docUrl.shopeeFlashSale, true)"
              >
                <Icon type="md-help-circle" />
                {{ $t('TUTORIAL_GUIDE') }}
              </Button>
            </div>

            <div class="mb-20">
              <Alert
                :show-icon="false"
                type="warning"
              >
                <b>{{ $t('FLASHSALE_STEP_TUTORIAL.NOTE') }}</b>
                <template #desc>
                  <ul class="ml-10">
                    <li
                      v-for="(lineContent, indexLine) in $t('FLASHSALE_RULE_NOTE')"
                      :key="indexLine"
                    >
                      {{ lineContent }}
                    </li>
                    <li class="mt-20">
                      <b>{{ $t('FLASHSALE_STEP_TUTORIAL.TIP') }}</b>
                    </li>
                  </ul>
                </template>
              </Alert>

              <!-- Select Option -->
              <div class="mb-10">
                <RadioGroup v-model="selected.priceOrginalBy">
                  <Row :gutter="5">
                    <Col
                      v-for="item in options.listPriceOrignalType"
                      :key="item.value"
                      :span="8"
                      style="width: 400px"
                    >
                      <Card>
                        <Radio :label="item.value">
                          {{ item.text }}
                        </Radio>
                      </Card>
                    </Col>
                  </Row>
                </RadioGroup>
              </div>

              <div
                class="mb-10"
              >
                <RadioGroup
                  v-model="selected.setMethod"
                >
                  <Row :gutter="5">
                    <Col
                      v-for="item in options.listSetMethod"
                      :key="item.value"
                      :span="12"
                      style="width: 500px"
                    >
                      <Card>
                        <Radio
                          :label="item.value"
                          :disabled="item.disabled"
                        >
                          {{ item.text }}
                        </Radio>
                      </Card>
                    </Col>
                  </Row>
                </RadioGroup>
                <div v-if="isSchedulerFlashSale">
                  <div class="mt-10 row-end">
                    <span class="mr-5">{{ $t('FLASHSALE_TIME_CREATE_BEFORE') }}</span>
                    <InputNumber
                      v-model="schedulerConfig.timeBefore"
                      controls-outside
                    />
                  </div>
                </div>
                <div
                  v-else
                  class="mt-10 row-end"
                >
                  <span class="mr-5">{{ $t('FLASHSALE_DELAY_BETWEEN_CREATE') }}</span>
                  <InputNumber
                    v-model="delayCreateFlashSale"
                    :min="1"
                    :max="300"
                    controls-outside
                  />
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>

      <!--Select Time-->
      <div v-if="stepKey === 'step-select-time'">
        <Row>
          <Col
            span="8"
            offset="9"
          >
            <div class="mb-10">
              <h3 class="mb-20">
                {{ $t('FLASHSALE_SELECT_TIME') }}
                <span>
                  {{ $t('TOTAL_SELECTED', { total: countTimeTotal, selected: countTimeSelected }) }}
                </span>
              </h3>

              <div class="row-end mb-20">
                <check-all
                  @select-all="timeSlotCheck(true)"
                  @deselect-all="timeSlotCheck(false)"
                />
              </div>
            </div>
            <div class="fsc-timeslot">
              <CheckboxGroup v-model="selected.listTimeId">
                <div
                  v-for="item in listSlotTime"
                  :key="item.value"
                >
                  <b
                    v-if="item.isParent"
                    class="hand-hover"
                    @click="timeSlotDate(item.value)"
                  >
                    <i
                      class="fa fa-check-square"
                      style="margin-right: 2px"
                    />
                    <span>{{ item.text }}</span>
                  </b>
                  <Checkbox
                    v-else
                    :label="item.value"
                    :disabled="item.disabled"
                  >
                    <span>{{ item.text }}</span>
                  </Checkbox>
                </div>
              </CheckboxGroup>
            </div>
          </Col>
        </Row>
      </div>

      <!--Select Product-->
      <div v-if="stepKey === 'step-select-product'">
        <Row>
          <Col span="24">
            <div class="mb-20">
              <Form
                ref="formInline"
                inline
              >
                <FormItem>
                  <Select
                    v-model="searchProduct.by"
                    style="width: 200px"
                  >
                    <Option
                      v-for="item in options.listSearchProductType"
                      :key="item.value"
                      :value="item.value"
                    >
                      {{ item.text }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem>
                  <Input
                    v-model="searchProduct.keyword"
                    type="text"
                    :placeholder="$t('SEARCH_INPUT')"
                    style="width: 500px"
                  />
                </FormItem>

                <FormItem>
                  <Button
                    type="primary"
                    :loading="searchProduct.loading"
                    @click="handlerSearchProduct"
                  >
                    {{ $t('SEARCH_BTN') }}
                  </Button>
                </FormItem>

                <span class="row-end">
                  <Button
                    type="info"
                    :loading="searchProduct.loading"
                    ghost
                    @click="loadSearchProduct"
                  >
                    {{
                      $t('LOAD_MORE_PRODUCT', {
                        page: searchProduct.product,
                        total: searchProduct.total
                      })
                    }}
                  </Button>
                </span>
              </Form>
            </div>
            <Table
              :loading="tableProduct.loading"
              :columns="tableProduct.column"
              :data="tableProduct.data"
              border
              highlight-row
              height="800"
              size="small"
            >
              <template
                slot="name"
                slot-scope="{ row }"
              >
                <Avatar
                  :src="row.image"
                  style="margin: 10px"
                />
                <a
                  :href="row.url"
                  target="_blank"
                >
                  {{ row.name }}
                </a>
              </template>
              <template
                slot="action"
                slot-scope="{ row }"
              >
                <div v-if="row.active">
                  <Button
                    v-if="row.added || checkProductWasAdded(row.id)"
                    type="error"
                    size="small"
                    ghost
                    @click="removeProductPromotion(row)"
                  >
                    <span>{{ $t('REMOVE_PRODUCT_BTN') }}</span>
                  </Button>
                  <Button
                    v-else
                    type="primary"
                    size="small"
                    ghost
                    @click="addProductPromotion(row)"
                  >
                    {{ $t('ADD_PRODUCT') }}
                  </Button>
                </div>
                <div v-else>
                  {{ row.status }}
                </div>
              </template>
            </Table>
          </Col>
        </Row>
      </div>

      <!--Config Promotion-->
      <div v-if="stepKey === 'step-change-promotion'">
        <Row>
          <Col span="24">
            <div class="mb-20">
              <Form inline>
                <FormItem :label="$t('PROMOTION_MASS_PRICE_CHANGE')">
                  <Input
                    v-model="formPromotion.pricePercent"
                    type="number"
                    @on-change="onChangePricePercent"
                  >
                    <template #append>
                      {{ $t('PERCENT_UINIT') }}
                    </template>
                  </Input>
                </FormItem>

                <FormItem :label="$t('PROMOTION_MASS_STOCK_LIMIT')">
                  <Input
                    v-model="formPromotion.stockLimit"
                    type="number"
                  />
                </FormItem>

                <FormItem :label="$t('PROMOTION_MASS_PURCHASE_LIMIT')">
                  <Input
                    v-model="formPromotion.purchaseLimit"
                    type="number"
                  />
                </FormItem>

                <FormItem :label="$t('PROMOTION_MASS_STATUS')">
                  <Checkbox v-model="formPromotion.status" />
                  <span>
                    {{ $t('STATUS_ACTIVE') }}
                  </span>
                </FormItem>

                <FormItem :label="$t('PROMOTION_MASS_APPLY')">
                  <Button
                    type="primary"
                    :loading="formPromotion.isLoading"
                    ghost
                    @click="onPromotionMass"
                  >
                    <span>{{ $t('PROMOTION_MASS_CHANGE_BTN') }}</span>
                  </Button>
                </FormItem>
              </Form>
            </div>
            <div>
              <Alert
                :show-icon="false"
                type="warning"
              >
                <span>{{ $t('FLASHSALE_PERCENT_MIN_LABEL') }}:</span>
                <InputNumber
                  v-model="flahsalePercentMinNumber"
                  :min="0"
                  :max="100"
                  :step="1"
                  size="small"
                  controls-outside
                  style="width: 80px; margin: 0 8px"
                >
                  <template #append>
                    {{ $t('PERCENT_UINIT') }}
                  </template>
                </InputNumber>
                <span>{{ flahsalePercentMinText }}</span>
              </Alert>
            </div>
            <div
              v-if="tablePromotion.loading"
              class="fsc-empty"
            >
              <Spin size="large" />
            </div>
            <div
              v-else-if="!listPromotionGroup.length"
              class="fsc-empty"
            >
              <Icon
                type="ios-cube-outline"
                size="36"
              />
              <p>{{ $t('FLASHSALE_ERROR.EMPTY_SELECT_PRODUCT') }}</p>
            </div>
            <div
              v-else
              class="fsc-list"
            >
              <div
                v-for="(group, groupIndex) in listPromotionGroup"
                :key="group.itemId"
                class="fsc-card"
              >
                <div class="fsc-card__header">
                  <span class="fsc-card__index">{{ groupIndex + 1 }}</span>
                  <Avatar
                    :src="group.image"
                    shape="square"
                    size="large"
                    class="fsc-card__thumb"
                  />
                  <div class="fsc-card__info">
                    <a
                      :href="group.url"
                      target="_blank"
                      class="fsc-card__name"
                    >
                      {{ group.name }}
                    </a>
                    <span class="fsc-card__meta">
                      {{ group.listModel.length }} {{ $t('PRODUCT_MODEL') }}
                    </span>
                  </div>
                </div>
                <div class="fsc-card__table">
                  <div class="fsc-card__row fsc-card__row--head">
                    <span>{{ $t('PRODUCT_MODEL') }}</span>
                    <span class="fsc-card__num">{{ $t('PRODUCT_STOCK') }}</span>
                    <span class="fsc-card__num">{{ $t('PRODUCT_PRICE_ORIGINAL') }}</span>
                    <span class="fsc-card__num">{{ $t('PRODUCT_PRICE_PROMOTION') }}</span>
                    <span>{{ $t('PRODUCT_PERCENT_FLASHSALE') }}</span>
                    <span>{{ $t('PRODUCT_PRICE_FLASHSALE') }}</span>
                    <span>{{ $t('PRODUCT_PROMOTION_STOCK_LIMIT') }}</span>
                    <span>{{ $t('PRODUCT_PROMOTION_PURCHASE_LIMIT') }}</span>
                    <span>{{ $t('PRODUCT_PROMOTION_STATUS') }}</span>
                  </div>
                  <div
                    v-for="model in group.listModel"
                    :key="`${model.itemId}-${model.modelId}`"
                    class="fsc-card__row"
                    :class="rowStatePromotion(model)"
                  >
                    <span class="fsc-card__model">{{ model.modelName }}</span>
                    <span class="fsc-card__num">{{ $n(model.stock) }}</span>
                    <span class="fsc-card__num">{{ $n(model.priceOrginal) }}</span>
                    <span class="fsc-card__num">{{ $n(model.priceDiscounted) }}</span>
                    <div class="fsc-card__field">
                      <Input
                        :value="renderPercent(model)"
                        type="number"
                        size="small"
                        @on-change="onChangePercentRow(model, $event)"
                      >
                        <template #append>
                          {{ $t('PERCENT_UINIT') }}
                        </template>
                      </Input>
                      <div
                        v-if="renderPercent(model) >= 95 && renderPercent(model) < 100"
                        class="fsc-card__note is-warning"
                      >
                        {{ $t('PROMOTION_PERCENT_WARNING') }}
                      </div>
                      <div
                        v-if="renderPercent(model) > 100 || renderPercent(model) < 0"
                        class="fsc-card__note is-error"
                      >
                        {{ $t('PROMOTION_PERCENT_INVALID') }}
                      </div>
                    </div>
                    <div class="fsc-card__field">
                      <Input
                        v-model="model.pricePromotion"
                        type="number"
                        size="small"
                        @on-change="onChangeRow(model)"
                      />
                    </div>
                    <div class="fsc-card__field">
                      <Input
                        v-model="model.stockLimit"
                        type="number"
                        size="small"
                        @on-change="onChangeRow(model)"
                      >
                        <template #append>
                          <span>{{ $t('MAX_LABEL', { max: model.stockMax }) }}</span>
                        </template>
                      </Input>
                    </div>
                    <div class="fsc-card__field">
                      <Input
                        v-model="model.purchaseLimit"
                        type="number"
                        size="small"
                        @on-change="onChangeRow(model)"
                      >
                        <template #append>
                          <span>{{ $t('MAX_LABEL', { max: model.purchaseMax }) }}</span>
                        </template>
                      </Input>
                    </div>
                    <div class="fsc-card__field fsc-card__field--status">
                      <Checkbox
                        v-model="model.status"
                        @on-change="onChangeRow(model)"
                      />
                      <span>{{ $t('STATUS_ACTIVE') }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </Col>
        </Row>
      </div>
      <!--Final-->
      <div v-if="stepKey === 'step-final'">
        <Row>
          <Col
            span="12"
            offset="6"
          >
            <div class="mb-10 row-end">
              <Button
                type="primary"
                class="mr-5"
                :loading="excuteProcess.loading"
                :disabled="isProcessDone || excuteProcess.loading"
                @click="applyPromotion"
              >
                {{ $t('FLASHSALE_CREATE_BTN') }}
                <span>
                  {{
                    $t('TOTAL_SELECTED', {
                      total: excuteProcess.total,
                      selected: excuteProcess.current
                    })
                  }}
                </span>
              </Button>
            </div>

            <div class="mb-20">
              <Input
                v-model="processLogger"
                type="textarea"
                :rows="30"
                readonly
                :placeholder="$t('PROCESSING_LOG')"
              />
            </div>

            <div
              v-if="!isSchedulerFlashSale && isProcessDone"
              class="row-end"
            >
              <Button
                type="info"
                class="mr-5"
                style="margin-right:auto"
                @click="showErrorLog"
              >
                {{ $t('FLASHSALE_SHOW_ERROR_LOG') }}
              </Button>

              <excel-download
                :data="exportExcel.data"
                :fields="exportExcel.column"
                :worksheet="exportExcel.sheet"
                :name="exportExcel.file"
              >
                <Button type="success">
                  {{ $t('EXPORT_EXCEL_RESULT') }}
                </Button>
              </excel-download>
            </div>

            <div class="mt-10">
              <Alert
                :show-icon="false"
                type="warning"
              >
                <template #desc>
                  <ul class="ml-10">
                    <li
                      v-for="(lineContent, indexLine) in $t('FLASHSALE_RULE_NOTE')"
                      :key="indexLine"
                    >
                      {{ lineContent }}
                    </li>
                  </ul>
                </template>
              </Alert>
            </div>

            <Input
              v-if="false && isDevMode"
              class="mt-10"
              :value="JSON.stringify(exportExcel.data)"
              :rows="4"
              readonly
            />
          </Col>
        </Row>
      </div>
    </div>
    <div>
      <Modal
        v-model="errorLog.show"
        :title="$t('FLASHSALE_ERROR_TITLE')"
        width="60%"
        class="fsc-errorlog-modal"
      >
        <div
          v-if="errorLog.data.length"
          class="fsc-errorlog"
        >
          <div
            v-for="(flashsaleError, index) in errorLog.data"
            :key="index"
            class="fsc-errorlog__group"
          >
            <h3 class="fsc-errorlog__title">
              <a
                :href="flashsaleError.fashsaleUrl"
                target="_blank"
                class="fsc-errorlog__link"
              >
                <span>{{ $t('FLASHSALE_TITLE_TIME', { time: flashsaleError.fashsaleName }) }}</span>
              </a>
              <span class="fsc-errorlog__count">{{ $t('ERORR_COUNT_TOTAL', { count: flashsaleError.list.length, total: flashsaleError.total }) }}</span>
            </h3>
            <Table
              :columns="errorLog.table"
              :data="flashsaleError.list"
              size="small"
              border
            />
          </div>
        </div>
        <div v-else>
          <Alert
            type="warning"
          >
            {{ $t('FLASHSALE_ERROR_LOG_EMPTY') }}
          </Alert>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
import ExcelDownload from 'vue-json-excel';
import mixin from './mixin/Create';

export default {
  name: 'ShopeeFlashSaleCreate',
  components: {
    'excel-download': ExcelDownload,
  },
  props: {
    flashSaleId: {
      type: String,
      require: true,
    },
  },
  mixins: [mixin],
};
</script>

<style lang="scss" scoped>
@import '@/vue/styles/tokens.scss';

.fsc-empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 48px 0;
  color: $c-text-placeholder;
}

.fsc-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 800px;
  overflow-y: auto;
  padding: 4px;

  @include scrollbar;
}

.fsc-card {
  background: $c-surface;
  border: 1px solid $c-border;
  border-radius: $radius-card;
  box-shadow: $shadow-card;
  transition: box-shadow $motion-base, border-color $motion-base;

  &:hover {
    box-shadow: $shadow-hover;
    border-color: $c-border-strong;
  }

  &__header {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 16px;
    border-bottom: 1px solid $c-border;
  }

  &__index {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    min-width: 24px;
    height: 24px;
    padding: 0 6px;
    border-radius: $radius-pill;
    background: $c-surface-alt;
    color: $c-text-muted;
    font-size: 12px;
    font-weight: 600;
  }

  &__thumb.ivu-avatar {
    flex-shrink: 0;
    border-radius: $radius-sm;
    background: $c-surface-alt;
  }

  &__info {
    display: flex;
    flex-direction: column;
    gap: 2px;
    min-width: 0;
  }

  &__name {
    font-size: 14px;
    font-weight: 600;
    line-height: 1.4;
    color: $c-text-strong;
    transition: color $motion-fast;

    @include line-clamp(2);

    &:hover {
      color: $c-link;
    }
  }

  &__meta {
    font-size: 12px;
    color: $c-text-muted;
  }

  &__table {
    padding: 8px 12px 12px;
    overflow-x: auto;

    @include scrollbar;
  }

  &__row {
    display: grid;
    grid-template-columns: minmax(110px, 1.2fr) 80px 90px 90px 140px 110px minmax(150px, 1fr) minmax(150px, 1fr) 100px;
    gap: 8px;
    align-items: center;
    min-width: 1080px;
    padding: 6px 8px;
    border-radius: $radius-item;
    transition: background $motion-fast;

    &--head {
      color: $c-text-muted;
      font-size: 12px;
      font-weight: 600;
    }

    &:not(&--head):hover {
      background: $c-surface-alt;
    }

    &.is-danger {
      background: $c-error-bg;
    }

    &.is-success {
      background: $c-success-bg;
    }
  }

  &__model {
    font-size: 13px;
    font-weight: 500;
    color: $c-text-strong;

    @include ellipsis;
  }

  &__num {
    font-size: 13px;
    color: $c-text;
    text-align: center;
  }

  &__field {
    min-width: 0;

    &--status {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 13px;
      color: $c-text;
    }
  }

  &__note {
    margin-top: 2px;
    font-size: 11px;

    &.is-warning {
      color: $c-warning;
    }

    &.is-error {
      color: $c-error;
    }
  }
}

.fsc-timeslot {
  height: 700px;
  overflow-y: auto;
  padding: 6px;
  border: 1px solid $c-border;
  border-radius: $radius-card;
  background: $c-surface;

  @include scrollbar;

  .ivu-checkbox-wrapper {
    display: block;
    padding: 4px 6px;
    border-radius: $radius-sm;
    color: $c-text;
    transition: background $motion-fast, color $motion-fast;

    &:hover {
      background: $c-surface-alt;
      color: $c-text-strong;
    }
  }
}

.fsc-errorlog {
  max-height: 650px;
  overflow-y: auto;
  padding: 16px;

  @include scrollbar;

  &__group {
    margin-bottom: 16px;
  }

  &__title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 8px;
    font-size: 15px;
    font-weight: 600;
    color: $c-text-strong;
  }

  &__link {
    cursor: pointer;
    text-decoration: none;
    color: $c-link;
    transition: color $motion-fast;

    @include ellipsis;

    &:hover {
      color: $c-link-hover;
      text-decoration: underline;
    }
  }

  &__count {
    flex-shrink: 0;
    font-size: 12px;
    font-weight: 500;
    color: $c-text-muted;
  }
}
</style>
