/* eslint-disable arrow-parens */
import history from './../../utils/history';
import * as Api from './service';
import showToast from '../../utils/showToast';
import { createSubscribe } from 'applet-page-component';
import { connect } from 'herculex';
import { getMeter } from '../../utils';
import { isPhoneNumber } from './check';
Component(createSubscribe({
  async onShow() {
    const {
      globalAddress = []
    } = this.$store.stateConfig.$global;
    const {
      globalShopId,
      deliverType
    } = this.data;

    if (globalAddress && globalAddress.length && deliverType === 'DELIVERY_LOGISTICS') {
      const item = globalAddress[0];
      this.setData({
        addressList: [{ ...item,
          provinceName: item.region[0] || '',
          cityName: item.region[1] || '',
          districtName: item.region[2] || ''
        }],
        showMsg: true
      });

      if (deliverType === 'DELIVERY_LOGISTICS') {
        await this.queryDistance({
          id: globalAddress[0].id,
          globalShopId
        });
      }
    }
  }

})(connect({
  mapStateToProps: {
    globalAddress: state => state.globalAddress || [],
    globalShopId: state => state.$global.globalShopId || ''
  }
})({
  props: {
    componentData: {}
  },

  didUnmount() {
    this.commitGlobal && this.commitGlobal({
      globalAddress: null
    });
  },

  async didMount() {
    const {
      carCheckedList,
      totalPrice,
      disCountTotalPrice,
      deliverType,
      deliveryCost,
      deliverTypeItem,
      packingFee,
      componentExtInfo: {
        getPhone = 'N'
      } = {}
    } = this.props.componentData || {}; // 自提 尝试获取以往电话号码

    if (deliverType === 'SELF_PICK_UP_DELIVERY') {
      const {
        phone,
        isPhoneReady,
        phoneFromOrderId
      } = await Api.getPhoneNumber();
      this.setData({
        phone,
        totalPrice,
        deliveryCost,
        isPhoneReady,
        phoneFromOrderId,
        deliverType,
        packingFee,
        deliverTypeItem,
        disCountTotalPrice,
        list: carCheckedList,
        hasPermission: getPhone === 'Y'
      });
    } else {
      // 尝试收货地址和信息
      const {
        list: defaultList = []
      } = (await Api.queryForAddressList()) || {};
      let addressResList = [...defaultList];

      if (!defaultList.length) {
        const res = (await Api.queryForLastAddressList()) || {};
        addressResList = Object.keys(res).length ? [{ ...res
        }] : [];
      }

      this.setData({
        totalPrice,
        disCountTotalPrice,
        deliverType,
        deliveryCost,
        packingFee,
        deliverTypeItem,
        list: carCheckedList,
        addressList: this.mapListToAddressList(addressResList)
      });

      if (addressResList.length && deliverType === 'DELIVERY_LOGISTICS') {
        const {
          id = -1
        } = addressResList[0];
        const {
          globalShopId
        } = this.data;
        await this.queryDistance({
          id,
          globalShopId
        });
      }
    }
  },

  data: {
    list: [],
    addressList: null,
    phone: '',
    isPhoneReady: false,
    totalPrice: 0,
    startPoll: false,
    btnText: '提交订单',
    phoneFromOrderId: '',
    disCountTotalPrice: 0,
    distance: '',
    flag: false,
    remark: '',
    showMsg: true
  },
  methods: {
    // 查询距离
    async queryDistance({
      id,
      globalShopId
    }) {
      const {
        distance = '',
        overDistance = false
      } = await Api.queryForAddressDistance({
        id,
        shopId: globalShopId
      });
      this.setData({
        distance: getMeter(distance),
        flag: overDistance
      });
    },

    // 点击消息关闭按钮
    handleCloseClick() {
      this.setData({
        showMsg: false
      });
    },

    // 输入备注
    handleItemChange(e) {
      const {
        value
      } = e.detail;
      this.setData({
        remark: value
      });
    },

    handleItemClear() {
      this.setData({
        remark: ''
      });
    },

    // 将组件传出的转为 addressList
    mapListToAddressList(list = []) {
      if (!list.length) {
        return [];
      }

      return list.map(v => ({
        name: v.userName,
        mobile: v.userPhone,
        region: [v.provinceName || '', v.cityName || '', v.districtName || ''],
        regionCode: [v.provinceCode || '', v.cityCode || '', v.districtCode || ''],
        latitude: v.latitude,
        longitude: v.longitude,
        address: v.detail,
        isDefault: v.status,
        addressNumber: v.addressNumber,
        id: v.id,
        provinceName: v.provinceName || '',
        cityName: v.cityName || '',
        districtName: v.districtName || ''
      }));
    },

    // 跳转到地址页面
    gotoAddress() {
      const {
        deliverType
      } = this.data;
      history.push({
        title: '收货地址',
        pageType: 'receiveAddressComponent',
        header: '',
        componentData: {
          isChoose: true,
          deliverType
        }
      });
    },

    // 子手机号组件实例
    saveRef(ref) {
      this.childRef = ref;
    },

    // 跳转订单详情 param orderId
    navToDetail() {
      this.commitGlobal && this.commitGlobal({
        globalAddress: null
      });
      history.replace({
        title: '订单详情',
        pageType: 'mallOrderDetail',
        query: {
          orderId: this.orderId
        },
        header: ''
      });
    },

    // 点击提交订单
    handelSubmit(formId = '') {
      const {
        list,
        phoneFromOrderId,
        deliverType
      } = this.data; // 从手机号组件中 获取 手机号和类型 : LAST_ORDER/CUSTOM/MY,

      const {
        inputPhone,
        phoneType = 'CUSTOM'
      } = this.childRef ? this.childRef.data : {};

      if (deliverType === 'SELF_PICK_UP_DELIVERY' && !isPhoneNumber(inputPhone)) {
        return showToast({
          content: '请输入正确的电话号',
          type: 'none'
        });
      } // 组装提交的商品列表


      const createList = list.map(v => ({
        skuId: v.skuId,
        num: v.quantity
      })); // 获取authCode

      my.getAuthCode({
        scopes: ['order_service'],
        // 同意订单流转
        success: async res => {
          // 获取 authcode成功
          const {
            authCode
          } = res;
          this.createOrder({
            authCode,
            formId,
            createList,
            phoneFromOrderId,
            inputPhone,
            phoneType
          });
        },
        fail: () => {
          // 拒绝
          this.createOrder({
            authCode: '',
            formId: '',
            createList,
            inputPhone,
            phoneFromOrderId,
            phoneType
          });
        }
      });
    },

    // 创建订单
    async createOrder({
      authCode,
      inputPhone,
      phoneType = 'CUSTOM',
      createList,
      phoneFromOrderId = '',
      formId
    }) {
      const {
        addressList = [],
        remark = '',
        deliverType = ''
      } = this.data;

      if (addressList && !addressList.length && deliverType === 'DELIVERY_LOGISTICS') {
        my.showToast({
          type: 'none',
          content: `请选择${deliverType === 'DELIVERY_LOGISTICS' ? '地址信息' : '提货人信息'}`
        });
      }

      const userPhone = deliverType === 'DELIVERY_LOGISTICS' ? addressList[0].mobile || '' : inputPhone; // 加载条 。。。

      my.showLoading({
        content: '提交中...'
      });

      try {
        // 发起请求 创建订单
        const {
          orderId = '',
          alipayTradeNo = ''
        } = await Api.createOrder({
          authCode,
          formId,
          phoneType,
          list: createList,
          phoneFromOrderId,
          phone: userPhone,
          addressId: deliverType === 'DELIVERY_LOGISTICS' ? addressList[0].id : null,
          remark,
          deliverType
        });
        this.orderId = orderId;
        my.hideLoading(); // 支付单号不为空 尝试支付

        if (alipayTradeNo) {
          // 成功 跳转详情页面，支付 默认开启轮询
          history.replace({
            title: '订单详情',
            pageType: 'mallOrderDetail',
            query: {
              orderId: this.orderId,
              alipayTradeNo,
              poll: true
            },
            header: ''
          });
        } else {
          // 支付单号为空 表示商家配置获取等存在问题 99% 不出现
          // 直接跳转订单详情
          this.navToDetail(orderId);
        }
      } catch (err) {
        // 支付失败或者订单异常
        const {
          orderId = '',
          alipayTradeNo = '',
          alipayMsg = ''
        } = err;

        if (alipayMsg) {
          return my.showToast({
            content: alipayMsg,
            type: 'none',
            duration: '50000'
          });
        }

        if (orderId) {
          history.replace({
            title: '订单详情',
            pageType: 'mallOrderDetail',
            query: {
              orderId,
              alipayTradeNo
            },
            header: ''
          });
        } // if (orderId) {
        //   return this.navToDetail(orderId);
        // }
        // 服务器创建订单失败


        showToast({
          type: 'fail',
          content: err.msg ? err.msg : err || '请求失败'
        });
        my.hideLoading();
      }
    }

  }
})));