import { Component } from 'rax';
import request from 'universal-request';
import { Message } from '@alifd/meet';
interface PropsData {
  componentData: any;
  // 在星环容器场景下会下发onChange方法来触发异步请求
  onChange?: Function;
  // 在星环容器场景下会下发onSubmit方法来触发提交请求
  onSubmit?: Function;
  fields: any;
  navigateBySchema: Function;
  history: any;
  apiHost: any;
  sessionId: any;
}

interface StateData {
  time: number;
  list: any;
  btnText: any;
  btnClick: boolean;
  btnHidden: boolean;
}


class MyComponent extends Component<PropsData, StateData> {
  public state: StateData = {
    time: 0,
    list: [],
    btnText: '一键领取',
    btnClick: false,
    btnHidden: false
  }
  prefix = null;
  public getData() {
    return {
      list: this.state.list,
      btnText: this.state.btnText,
      btnHidden: this.state.btnHidden
    };
  }
  componentWillReceiveProps (newProps) {
    if (this.props.fields.couponGroupId !== newProps.fields.couponGroupId) {
      console.log('newProps:', newProps);
      this.couponListGet(newProps);
    }
    if (this.props.fields.apiHost !== newProps.fields.apiHost) {
      console.log('newProps apiHost:', newProps);
      this.getApiHost(newProps);
      this.couponListGet(newProps);
    }
  }
  constructor(props) {
    super(props);
  }
  getApiHost = (props) => {
    const { fields } = props;
    const { apiHost } = fields;
    if (apiHost && apiHost.slice(apiHost.length - 1, apiHost.length) === '/') {
      this.prefix = apiHost.slice(0, apiHost.length - 1);
    } else {
      this.prefix = apiHost ? apiHost : `${location ? `${location.protocol}//${location.host}` : ''}`;
      // this.prefix = 'https://mall.vgktq.cn';
    }
    console.log('prefix:', this.prefix);
  }
  componentWillMount () {
    console.log('coupon version 0.0.39 left right style!');
    this.getApiHost(this.props);
    this.couponListGet(this.props);
  }
  H5Login = (cb?: Function) => {
    request({
      url: `${this.prefix}account/login/auth?phone=15922260314&password=asdasd&loginType=3`,
      method: 'POST',
      data: {}
    }).then(res => {
      cb && cb();
    })
  }
  couponListGet = async (props) => {
    const { fields = {} } = props;
    const { couponGroupId, layout } = fields;
    let _id = '';
    console.log('couponGroupId:', couponGroupId);
    if (couponGroupId && couponGroupId instanceof String && !couponGroupId.includes('coupon|')) {
      Message.show({content: '优惠券ID选择错误，请重新选择', type: 'error'});
      return;
    } else if (couponGroupId && couponGroupId instanceof Object && couponGroupId.type && couponGroupId.type !== 'coupon') {
      Message.show({content: '优惠券ID选择错误，请重新选择', type: 'error'});
      return;
    } else if (couponGroupId instanceof String) {
      _id = couponGroupId.split('coupon|')[1];
    } else if (couponGroupId instanceof Object && couponGroupId.id) {
      _id = couponGroupId.id;
    }
    if (!_id) return;
    const res = await request({
      url: `${this.prefix}/promotion/coupon/list`,
      method: 'POST',
      data: {couponGroupId: _id},
      headers: {
        'content-type': 'application/json',
        Cookie: `CR-SESSION=${this.props.sessionId}`
      }
    });
    console.log('coupon listsxxx:', res);
    const {data = {}} = res;
    const {success, message} = data;
    if (!success) {
      Message.show({content: message, type: 'error'});
      return;
    }
    this.setState({
      btnHidden: (data.result ? data.result : []).length ? true : false,
      list: (data.result ? data.result : []).map(item => {
        item.btnText = '立即领取';
        if (item.amount && item.discountType === 2) {
         item.amount = (+item.amount).toFixed(0);
        } else if (item.discountType === 1) {
          item.amount = item.amount;
        } else {
          item.amount = 0;
        }
        if (item.amount % 1) {
          item.letter = true;
        } else {
          item.letter = false;
        }
        // if (item.thresholdDesc && item.thresholdDesc.includes('使用') && `${layout}` === '2') {
        //   item.thresholdDesc = item.thresholdDesc.split('使用')[0];
        // }
        return item;
      })
    }, () => {
      console.log('state:', this.state);
    })
  }
  couponItemGet = (item?:any, idx?: number) => {
    const { btnClick } = this.state;
    if (btnClick) return;
    this.setState({btnClick: true}, () => {
      let couponIdList:any = [{
        couponId: item.couponId,
        sellerId: item.sellerId
      }];
      console.log('couponIdList:', couponIdList);
      request({
        url: `${this.prefix}/promotion/coupon/receive`,
        method: 'POST',
        data: {couponIdList: couponIdList},
        headers: {
          'content-type': 'application/json',
          Cookie: `CR-SESSION=${this.props.sessionId}`
        }
      }).then(res => {
        console.log('receive item:', res);
        const {data} = res;
        const {success, message, errorCode } = data;
        this.setState({btnClick: false});
        if (!success) {
          if (errorCode === '19-C-010-01-11-005') {
            Message.show({content: message, type: 'warning'});
            return;
          }
          Message.show({content: message,  type: 'error'});
          return;
        }
        Message.success({content: '领取成功'});

        const { navigateBySchema = () => {} } = this.props;
        navigateBySchema({actionLink: 'notice#GET_COUPON'});

        const {list = []} = this.state;
        this.setState({
          list: list.map((coupon, index) => {
            if (index === idx) {
              return {
                ...coupon,
                // btnText: '已领取',
                received: true
              }
            }
            return coupon;
          })
        })
      }).catch(e => {
        console.log('item e:', e);
        this.setState({btnClick: false})
      });
    })
  }
  couponsReceiveGet = () => {
    const { btnClick, list = [] } = this.state;
    if (!list.length) return;
    if (btnClick) return;
    this.setState({btnClick: true}, () => {
      let couponIdList:any = []
      const {list} = this.state;
      list.forEach(ele => {
        couponIdList.push({
          couponId: ele.couponId,
          sellerId: ele.sellerId
        })
      });
      console.log('couponIdList:', couponIdList);
      request({
        url: `${this.prefix}/promotion/coupon/receive`,
        method: 'POST',
        data: {couponIdList: couponIdList},
        headers: {
          'content-type': 'application/json',
          Cookie: `CR-SESSION=${this.props.sessionId}`
        }
      }).then(res => {
        console.log('receives:', res);
        const {data} = res;
        const {success, message, errorCode, result } = data;
        this.setState({btnClick: false});
        if (!success) {
          if (errorCode === '19-C-010-01-11-005') {
            Message.show({content: message, type: 'warning'});
            return;
          }
          Message.show({content: message,  type: 'error'});
          return;
        }
        const {receiveFailList = [], receiveSuccessList = []} = result;
        if (receiveFailList && receiveFailList.length) {
          Message.show({content: message,  type: 'warning'});
        } else {
          Message.success({content: '领取成功'});
        }

        const { navigateBySchema = () => {} } = this.props;
        navigateBySchema({actionLink: 'notice#GET_COUPON'});
        
        // this.setState({btnText: '已领取'});
        const {list = []} = this.state;
        this.setState({
          list: list.map(coupon => {
            if (coupon.couponId && receiveSuccessList.includes(coupon.couponId)) {
              return {
                ...coupon,
                // btnText: '已领取',
                received: true
              }
            }
            return {
              ...coupon
            }
          })
        })
      }).catch(e => {
        console.log('item e:', e);
        this.setState({btnClick: false})
      });
    })
  }
  public getMethod() {
    return {
      couponItemGet: this.couponItemGet.bind(this),
      couponsReceiveGet: this.couponsReceiveGet.bind(this)
    };
  }
};

export default MyComponent;
