<script>
import { createNamespace } from '@qg/cherry-ui/src/utils';
import Tab from '@qg/cherry-ui/src/tab';
import Tabs from '@qg/cherry-ui/src/tabs';
import Button from '@qg/cherry-ui/src/button';
import RadioGroup from '@qg/cherry-ui/src/radio-group';
import Radio from '@qg/cherry-ui/src/radio';
import Empty from '@qg/cherry-ui/src/empty';
import Image from '@qg/cherry-ui/src/image';
const { name, bem } = createNamespace('coupon-list');

export default {
  name,
  model: {
    prop: 'value',
    event: 'change'
  },
  inject: ['pay'],
  props: {
    showCoupon: Boolean,
    value: {
      type: [String, Number],
      default: ''
    },
    title: {
      type: String,
      default: '选择优惠券'
    },
    buttonText: {
      type: String,
      default: '确定'
    },
    currency: {
      type: String,
      default: '¥'
    },
    emptyImage: {
      type: String,
      default: 'coupon'
    },
    showCount: Boolean,
    enableTitle: {
      type: String,
      default: '可用优惠券'
    },
    disableTitle: {
      type: String,
      default: '不可用优惠券'
    },
    enableList: {
      type: Array,
      default() {
        return [];
      }
    },
    disableList: {
      type: Array,
      default() {
        return [];
      }
    },
    noRenderDisableTab: {
      type: Boolean,
      default() {
        return false;
      }
    },
    safeAreaInsetBottom: Boolean,
    couponInfo: {
      type: Object,
      default: () => ({})
    },
    selectedNewPerson: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      tabActive: 0,
      selectId: '',
      selectInfo: {},
      selectNewPerson: true
    };
  },
  watch: {
    showCoupon(val) {
      if (val) {
        this.selectId = this.value;
        this.selectNewPerson = this.pay.selectNewPerson;
        !this.noRenderDisableTab &&
          this.$nextTick(() => {
            this.$refs['couponTabs'].setLine();
          });
      }
    },
    value: {
      handler(val) {
        this.selectId = val;
        val && this.getSelectInfo(val);
      },
      immediate: true
    },
    'pay.selectNewPerson'(v) {
      this.selectNewPerson = v;
    }
  },
  methods: {
    getSelectInfo(v) {
      [...this.enableList, ...this.disableList].forEach(item => {
        if (item.id === v) {
          this.selectInfo = item;
        }
      });
    },
    handleButtonClick() {
      this.$emit('change', this.selectId, this.selectId ? this.selectInfo : {});
      this.$emit('toggleNewPerson', this.selectNewPerson);
    },
    handleCellClick(info, flag) {
      if (!info.pickupAble) return;
      if (this.selectId === info.id) {
        this.selectId = '';
      } else {
        this.selectId = info.id;
      }
      this.selectInfo = info;
      this.$refs[flag].toggle();
    },
    renderHeader() {
      return <div class={bem('header')}>{this.title}</div>;
    },
    renderBody() {
      const { enableTitle, disableTitle, enableList, disableList, noRenderDisableTab } = this;
      const enableInfo = this.renderTab(enableTitle, enableList, 'enable');
      const disableInfo = this.renderTab(disableTitle, disableList, 'disable');
      return !noRenderDisableTab ? (
        <Tabs ref="couponTabs">
          <RadioGroup value={this.selectId} direction="vertical">
            {enableInfo}
            {disableInfo}
          </RadioGroup>
        </Tabs>
      ) : (
        <RadioGroup value={this.selectId} direction="vertical">
          {enableInfo}
        </RadioGroup>
      );
    },
    renderBottom() {
      return (
        <div
          class={bem('bottom', {
            safe: this.safeAreaInsetBottom
          })}
        >
          <Button type="primary" block shape="circle" onClick={this.handleButtonClick}>
            {this.buttonText}
          </Button>
        </div>
      );
    },
    // 显示VCC新人券
    renderNewPersonConpon(list) {
      const info = this.couponInfo;

      return (
        <div
          class={[bem('item'), bem('new')]}
          onClick={() => (this.selectNewPerson = !this.selectNewPerson)}
        >
          <div class={[bem('content'), bem('new__content')]}>
            <div class={bem('desc')}>{info.promotionTxt}</div>
            <div class={bem('date')}>{info.description}</div>
          </div>
          {(!this.selectNewPerson && list.length && (
            <div class={bem('addition')}>
              <img
                class={bem('addition--img')}
                src="https://img.lkbang.net/icon-addition.372343c5c37e91b487a.372343c5.png"
              />
            </div>
          )) ||
            ''}
          <div class={bem('right')}>
            <cr-checkbox value={this.selectNewPerson} shape="round" />
          </div>
        </div>
      );
    },
    renderConpon(list, itemList) {
      const arr = [];
      if (this.couponInfo && this.couponInfo.id) {
        arr.push(this.renderNewPersonConpon(list));
      }
      if (list.length) {
        arr.push(itemList);
      }
      if (arr.length) {
        return arr;
      } else {
        return <Empty image={this.emptyImage} description="暂无优惠券" />;
      }
    },
    renderTab(title = '', list = [], flag = 'enable') {
      const itemList = list.map((item, index) => this.renderItem(item, `${flag}_${index}`));
      let tabTitle = title;
      if (this.showCount) {
        tabTitle = `${title} (${list.length})`;
      }
      return !this.noRenderDisableTab ? (
        <Tab title={tabTitle}>
          <div class={bem('list')}>{this.renderConpon(list, itemList)}</div>
        </Tab>
      ) : (
        <div class={bem('list')}>{this.renderConpon(list, itemList)}</div>
      );
    },
    renderItem(info = {}, flag) {
      const radio = info.pickupAble ? (
        <div class={bem('right')}>
          <Radio ref={flag} name={info.id} />
        </div>
      ) : null;
      return (
        <div
          class={bem('item', { disabled: !info.pickupAble })}
          onClick={() => this.handleCellClick(info, flag)}
        >
          {info.iconUrl && (
            <Image src={info.iconUrl} class={bem('icon')} width="44px" height="16px" />
          )}
          <div class={bem('left')}>
            <h3 class={bem('amount')}>
              <small>{this.currency}</small>
              {info.faceValue}
            </h3>
            <p class={bem('limit')}>{info.limitDesc}</p>
          </div>
          <div class={bem('content')}>
            <div class={bem('desc')}>{info.name}</div>
            <div class={bem('date')}>{info.couponValidTime}</div>
          </div>
          {radio}
          {((!this.selectId || !this.selectNewPerson) && (
            <div class={bem('addition')}>
              <img
                class={bem('addition--img')}
                src="https://img.lkbang.net/icon-addition.372343c5c37e91b487a.372343c5.png"
              />
            </div>
          )) ||
            ''}
        </div>
      );
    }
  },
  render() {
    return (
      <div class={bem()}>
        {this.showCoupon && (
          <div>
            {this.renderHeader()}
            {this.renderBody()}
            {this.renderBottom()}
          </div>
        )}
      </div>
    );
  }
};
</script>
<style lang="less" scoped>
@import '../../../style/var.less';
@import '../../../style/mixins';
@padding-base: 4px;
@coupon-list-header-height: 20px;
@coupon-list-header-padding: @padding-sm + 2;
@coupon-list-bottom-padding: @padding-xs @padding-lg;
@coupon-list-list-padding: @padding-xs + 2 @padding-sm;
@coupon-list-list-height: 50vh;
@coupon-list-item-background: #ffece6;
@coupon-list-item-padding: @padding-lg @padding-xs @padding-lg @padding-sm;
@coupon-list-item-margin-bottom: @padding-xs + 2;
@coupon-list-item-border-radius: @border-radius-sm;
@coupon-list-new-padding: @padding-lg + 4 @padding-xs;
@coupon-list-left-color: @red;
@coupon-list-left-line-height: @line-height-lg;
@coupon-list-amount-font-weight: @font-weight-bold;
@coupon-list-limit-color: @red;
@coupon-list-content-padding: @padding-base @padding-md @padding-base @padding-xs;
@coupon-list-desc-color: #333333;
@coupon-list-desc-margin-bottom: @padding-base + 2;
@coupon-list-date-color: @gray-7;
@border-color: @gray-4;

.hairline-common() {
  position: absolute;
  box-sizing: border-box;
  content: ' ';
  pointer-events: none;
}

.hairline(@color: @border-color) {
  .hairline-common();

  top: -50%;
  right: -50%;
  bottom: -50%;
  left: -50%;
  border: 0 solid @color;
  transform: scale(0.5);
}

.hairline-top(@color: @border-color, @left: 0, @right: 0) {
  .hairline-common();

  top: 0;
  right: @right;
  left: @left;
  border-top: 1px solid @color;
  transform: scaleY(0.5);
}

.hairline-bottom(@color: @border-color, @left: 0, @right: 0) {
  .hairline-common();

  right: 0;
  bottom: 0;
  left: @left;
  right: @right;
  border-bottom: 1px solid @color;
  transform: scaleY(0.5);
}

.cr-coupon-list {
  .cr-popup--close {
    top: 14px;
  }

  .cr-tabs__content {
    margin-top: 0;
  }

  &__header {
    height: @coupon-list-header-height;
    font-size: .text-size(16);
    line-height: @coupon-list-header-height;
    padding: @coupon-list-header-padding;
    text-align: center;
  }

  .cr-tabs__nav {
    &::after {
      .hairline-bottom();
      bottom: 15px;
    }
  }

  &__bottom {
    padding: @coupon-list-bottom-padding;
    position: relative;

    &::after {
      .hairline-top();
    }

    &--safe {
      .iphonex-fix-padding();
    }
  }

  &__list {
    padding: @coupon-list-list-padding;
    overflow-y: scroll;
    overflow-x: hidden;
    height: 50vh;
  }

  &__item {
    display: flex;
    align-items: center;
    position: relative;
    background: @coupon-list-item-background;
    border-radius: @coupon-list-item-border-radius;
    padding: @coupon-list-item-padding;
    margin-bottom: @coupon-list-item-margin-bottom;

    &--disabled {
      -webkit-filter: grayscale(100%) opacity(0.8); /* Chrome, Safari, Opera */
      filter: grayscale(100%) opacity(0.8);

      .cr-coupon-list__right {
        display: none;
      }
    }
  }
  &__new {
    padding: @coupon-list-new-padding;
    background: none;
  }
  &__new__content {
    padding: 0 !important;
  }

  &__left {
    color: @coupon-list-left-color;
    line-height: 22px;
    width: 95px;
    text-align: center;
  }

  &__icon {
    position: absolute !important;
    left: 0;
    top: 0;
  }

  &__amount {
    .text-size(30);
    font-weight: @coupon-list-amount-font-weight;
    margin: 0;
    word-break: break-all;

    small {
      .text-size(16);
    }
  }

  &__limit {
    .text-size(12);
    color: @coupon-list-limit-color;
    line-height: .text-size(18);
    margin: 0;
  }

  &__content {
    padding: @coupon-list-content-padding;
  }

  &__desc {
    font-weight: bold;
    .text-size(14);
    color: @coupon-list-desc-color;
    margin-bottom: @coupon-list-desc-margin-bottom;
  }

  &__date {
    .text-size(12);
    color: @coupon-list-date-color;
    line-height: .text-size(18);
  }

  &__right {
    margin-left: auto;
    pointer-events: none;
    .cr-radio {
      margin-right: 0;
    }
  }
  &__addition {
    position: absolute;
    top: 0;
    right: 0;
    width: 46px;
    height: 32px;
  }
  &__addition--img {
    display: block;
    width: 100%;
  }
}
</style>
