import { onPageLoadInitAuth, post } from '@/utils/https';
import {
  SaleOrderProcessStateOption,
  PayedStateOption,
  SaleOrderProcessStateObj,
} from '@/utils/config';
import {
  cloneLite,
  getAuthInfo,
  getDataSet,
  getDay,
  searchValueFormat,
  showModal,
  sleep,
  toArray,
  toastSuccess,
  toNumber,
  toObject,
} from '@/utils/util';

const defaultParams = { curr_page: 1, page_count: 20, process_state: [200] };

Page({
  /**
   * 页面的初始数据
   */
  data: {
    params: cloneLite(defaultParams) as any,
    list: [] as any[],
    count: 0,
    amount: {
      tot_tax_last_money: 0,
      tot_discount_money: 0,
      tot_payed_amount: 0,
      tot_un_payed_amount: 0,
    },
    orderStep: [] as any[],
    saleOrderProcessStateOption: SaleOrderProcessStateOption,
    saleOrderProcessStateObj: SaleOrderProcessStateObj,
    payedStateOption: PayedStateOption,
    sort: [
      { label: '自定义单号', value: 'custom_order_no' },
      { label: '订单类型', value: 'category_name' },
      { label: '订单阶段', value: 'order_step_name' },
      { label: '经销商名称', value: 'custom_name' },
      { label: '经销商手机', value: 'custom_phone' },
      { label: '客户名称', value: 'end_user_name' },
      { label: '客户手机', value: 'end_user_phone' },
      { label: '客户手机', value: 'end_user_address' },
      { label: '单据日期', value: 'document_date' },
      { label: '含税合计', value: 'tot_tax_last_money' },
      { label: '优惠金额', value: 'discount_money' },
      { label: '已收金额', value: 'payed_amount' },
      { label: '未收金额', value: 'un_payed_amount' },
      { label: '创建日期', value: 'create_date' },
    ],
  },
  handleLogin(e: any) {
    this.setData({ isLogin: e.detail });
    if (e.detail) {
      this.init();
      this.getList();
    }
  },
  init() {
    this.setData({ authInfo: getAuthInfo() });
    this.getOrderStep();
  },
  searchChange(e: any) {
    const key = getDataSet(e).key;
    const val = searchValueFormat(e.detail.value);
    if (val) {
      this.data.params[key] = val;
    } else {
      delete this.data.params[key];
    }
    this.setData({ params: this.data.params });
  },
  searchOk() {
    this.getList(1);
  },
  searchReset() {
    this.data.params = cloneLite(defaultParams);
    this.getList(1);
  },
  onSort(e: any) {
    this.data.params.order = e.detail.value;
    this.setData({ params: this.data.params });
    this.getList(1);
  },
  paginationChange(e: any) {
    this.getList(e.detail.curr_page);
  },
  getOrderStep() {
    post('OrderStep/list').then((res: any) => {
      this.setData({
        orderStep: toArray(res.data).map((el) => ({
          label: el.order_step_name,
          value: el.order_step_id,
        })),
      });
    });
  },
  getList(curr: number = 1) {
    this.data.params.curr_page = curr;
    this.setData({ params: this.data.params });
    const temp = cloneLite(this.data.params);
    if (temp.order_step && temp.order_step.length) {
      temp.order_step = temp.order_step.join(',');
    } else {
      delete temp.order_step;
    }

    if (temp.process_state && temp.process_state.length) {
      temp.process_state = temp.process_state.join(',');
    } else {
      delete temp.process_state;
    }
    return new Promise<void>((resolve, reject) => {
      post('Orders/list', temp)
        .then((res: any) => {
          const list = toArray(res.data);
          if (list.length == 0 && this.data.params.curr_page > 1) {
            this.getList(this.data.params.curr_page - 1);
          }
          this.setData({
            count: toNumber(res.count),
            list: list,
            amount: toObject(res.amount),
            isLogin: true,
          });
          resolve(res);
        })
        .catch((res) => {
          this.setData({ isLogin: false });
          reject(res);
        });
    });
  },
  onOrderPay(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    wx.navigateTo({
      url: '/pages/orders/ordersList/orderPayment/orderPayment',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('saleOrderPay', { data: item });
      },
    });
  },
  onOrderDetail(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    wx.navigateTo({
      url: `/pages/orders/ordersList/orderDetail/orderDetail?order_no=${item.order_no}`,
    });
  },
  onOrderDel(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    showModal({ content: `确认删除 ${item.order_no} 订单?` }).then(() => {
      post('Orders/delSaleOrders', { order_no: JSON.stringify([item.order_no]) }).then(() => {
        toastSuccess('删除成功');
        sleep(() => {
          this.getList();
        }, 1000);
      });
    });
  },
  onViewAttachment(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    wx.navigateTo({
      url: `/pages/base/viewAttachment/viewAttachment?order_no=${
        item.order_no
      }&title=${encodeURIComponent(`${item.order_no} 附件`)}`,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { type } = options;
    if (type == 'today') {
      this.data.params.create_dateL = getDay();
      this.data.params.create_dateU = getDay();
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    onPageLoadInitAuth(this, () => this.getList());
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
