// pages/merchant-regular-dispatch/merchant-regular-dispatch.js
import { createPage, request } from '../../utils/base-page.js';
import {
  STAFF_API, isStaffMode, refreshStaffContext, getStaffContext,
  restoreStaffContextAfterAuth, isMerchantPortalUser, staffOrOwner,
} from '../../utils/staff-api.js';

const PAGE_SIZE = 50;

function apiOk(res) {
  const code = res && res.data && res.data.code;
  return code === 200 || code === 0;
}

Page(createPage({
  data: {
    sjyue: '0.00',
    isStaffMode: false,
    balanceLabel: '可用余额',
    balanceTip: '派单将从此余额扣除',

    shangpinList: [],
    selectedTypeId: null,
    selectedHuiyuanId: null,
    selectedYaoqiuleixing: null,
    currentTypeChenghaoList: [],

    dingdanJieshao: '',
    dingdanBeizhu: '',
    laobanName: '',
    waibuDingdanId: '',
    zhidingUid: '',
    jiage: '',
    selectedLabelId: '',
    selectedLabelName: '',
    commissionEnabled: false,
    commissionValue: '',

    showTemplateSheet: false,
    templateKeyword: '',
    templateList: [],
    templatePage: 1,
    templateHasMore: true,
    templateLoading: false,

    isLoading: false,
    isSubmitting: false,
  },

  async onLoad() {
    if (wx.getStorageSync('token')) {
      await restoreStaffContextAfterAuth();
    }
    if (!isMerchantPortalUser()) {
      wx.showToast({ title: '请先成为商家或绑定客服', icon: 'none' });
      setTimeout(() => wx.navigateBack(), 1500);
      return;
    }
    this.loadShangjiaYue();
    this.loadShangpinTypes();
  },

  onShow() {
    this.loadShangjiaYue();
    this.registerNotificationComponent();
  },

  loadShangjiaYue() {
    const staff = isStaffMode();
    this.setData({
      isStaffMode: staff,
      balanceLabel: staff ? '可用额度' : '可用余额',
      balanceTip: staff ? '派单将从您的客服额度扣除（需老板先划额度）' : '派单将从此余额扣除',
    });
    if (staff) {
      const ctx = getStaffContext() || {};
      const wallet = ctx.wallet || {};
      this.setData({ sjyue: wallet.quota_available || '0.00' });
      refreshStaffContext(request).then((fresh) => {
        const w = (fresh && fresh.wallet) || wallet;
        this.setData({ sjyue: w.quota_available || '0.00' });
      }).catch(() => {});
      return;
    }
    const app = getApp();
    const shangjiaData = app.globalData.shangjia || {};
    this.setData({ sjyue: shangjiaData.sjyue || '0.00' });
  },

  async loadShangpinTypes() {
    this.setData({ isLoading: true });
    const staff = isStaffMode();
    try {
      const res = await request({
        url: staff ? STAFF_API.productTypes : '/dingdan/sjspleixing',
        method: 'POST',
      });
      if (apiOk(res)) {
        let list = res.data.data || [];
        if (!Array.isArray(list) && list.list) list = list.list;
        list.reverse();
        this.setData({ shangpinList: list, isLoading: false });
        if (list.length > 0) {
          this.setSelectedType(list[0]);
        }
      } else {
        throw new Error((res.data && res.data.msg) || '加载失败');
      }
    } catch (error) {
      console.error('加载商品类型失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({ title: error.message || '加载类型失败', icon: 'none' });
    }
  },

  setSelectedType(item) {
    this.setData({
      selectedTypeId: item.id,
      selectedHuiyuanId: item.huiyuan_id,
      selectedYaoqiuleixing: item.yaoqiuleixing,
      currentTypeChenghaoList: item.chenghaoList || [],
      dingdanJieshao: '',
      jiage: '',
      selectedLabelId: '',
      selectedLabelName: '',
      commissionEnabled: false,
      commissionValue: '',
    });
  },

  onSelectType(e) {
    const { item } = e.currentTarget.dataset;
    this.setSelectedType(item);
  },

  openTemplateSheet() {
    if (!this.data.selectedTypeId) {
      wx.showToast({ title: '请先选择订单类型', icon: 'none' });
      return;
    }
    this.setData({
      showTemplateSheet: true,
      templateKeyword: '',
      templateList: [],
      templatePage: 1,
      templateHasMore: true,
    }, () => this.loadTemplates(true));
  },

  closeTemplateSheet() {
    this.setData({ showTemplateSheet: false });
  },

  onTemplateKeywordInput(e) {
    this.setData({ templateKeyword: e.detail.value });
  },

  onTemplateSearch() {
    this.setData({ templateList: [], templatePage: 1, templateHasMore: true }, () => {
      this.loadTemplates(true);
    });
  },

  onTemplateScrollLower() {
    const { templateHasMore, templateLoading } = this.data;
    if (!templateHasMore || templateLoading) return;
    this.setData({ templatePage: this.data.templatePage + 1 }, () => this.loadTemplates(false));
  },

  async loadTemplates(reset) {
    const { selectedTypeId, templatePage, templateKeyword } = this.data;
    if (!selectedTypeId) return;
    this.setData({ templateLoading: true });
    try {
      const postData = {
        shangpinTypeId: selectedTypeId,
        page: templatePage,
        pageSize: PAGE_SIZE,
        getType: 1,
      };
      if (templateKeyword.trim()) {
        postData.keyword = templateKeyword.trim();
      }
      const res = await request({
        url: staffOrOwner(STAFF_API.templateList, '/peizhi/sjddmblb'),
        method: 'POST',
        data: postData,
      });
      if (apiOk(res)) {
        const data = res.data.data || {};
        const newTemplates = (data.list || []).map((item) => ({
          mobanId: item.mobanId || item.id,
          jieshao: item.jieshao || item.moban_jieshao || '',
          jiage: item.jiage || item.price || '',
          labelId: item.labelId || '',
          labelName: item.labelName || '',
          commissionEnabled: !!item.commissionEnabled,
          commissionValue: item.commissionValue || '',
        }));
        const merged = reset || templatePage === 1
          ? newTemplates
          : [...this.data.templateList, ...newTemplates];
        this.setData({
          templateList: merged,
          templateHasMore: data.hasMore !== false && newTemplates.length === PAGE_SIZE,
          templateLoading: false,
        });
      } else {
        this.setData({ templateLoading: false, templateHasMore: false });
      }
    } catch (e) {
      console.error(e);
      this.setData({ templateLoading: false });
      wx.showToast({ title: '加载模板失败', icon: 'none' });
    }
  },

  onSelectTemplate(e) {
    const { item } = e.currentTarget.dataset;
    if (!item) return;
    this.setData({
      dingdanJieshao: item.jieshao || '',
      jiage: String(item.jiage || ''),
      selectedLabelId: item.labelId || '',
      selectedLabelName: item.labelName || this.getLabelNameById(item.labelId),
      commissionEnabled: !!item.commissionEnabled,
      commissionValue: item.commissionValue || '',
      showTemplateSheet: false,
    });
  },

  getLabelNameById(labelId) {
    if (!labelId) return '';
    const found = this.data.currentTypeChenghaoList.find((x) => x.id == labelId);
    return found ? found.mingcheng : '';
  },

  onDingdanBeizhuInput(e) { this.setData({ dingdanBeizhu: e.detail.value }); },
  onLaobanNameInput(e) { this.setData({ laobanName: e.detail.value }); },
  onWaibuDingdanIdInput(e) { this.setData({ waibuDingdanId: e.detail.value }); },
  onZhidingUidInput(e) { this.setData({ zhidingUid: e.detail.value }); },

  validateForm() {
    const { selectedTypeId, dingdanJieshao, laobanName, jiage, sjyue } = this.data;
    if (!selectedTypeId) {
      wx.showToast({ title: '请选择订单类型', icon: 'none' });
      return false;
    }
    if (!dingdanJieshao.trim()) {
      wx.showToast({ title: '请选择订单模板', icon: 'none' });
      return false;
    }
    if (!laobanName.trim()) {
      wx.showToast({ title: '请输入老板游戏昵称', icon: 'none' });
      return false;
    }
    if (!jiage) {
      wx.showToast({ title: '模板价格无效', icon: 'none' });
      return false;
    }
    const price = parseFloat(jiage);
    if (isNaN(price) || price < 0.1 || price > 10000) {
      wx.showToast({ title: '价格需在0.1-10000元之间', icon: 'none' });
      return false;
    }
    const balance = parseFloat(sjyue);
    if (price > balance) {
      if (this.data.isStaffMode) {
        wx.showModal({
          title: '额度不足',
          content: `当前可用额度${sjyue}元，需要${jiage}元。请联系商家老板划额度。`,
          showCancel: false,
        });
      } else {
        wx.showModal({
          title: '余额不足',
          content: `当前余额${sjyue}元，需要${jiage}元。请先充值。`,
          confirmText: '去充值',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({ url: '/pages/merchant-recharge/merchant-recharge' });
            }
          },
        });
      }
      return false;
    }
    return true;
  },

  resetForm() {
    this.setData({
      dingdanJieshao: '',
      dingdanBeizhu: '',
      laobanName: '',
      waibuDingdanId: '',
      zhidingUid: '',
      jiage: '',
      selectedLabelId: '',
      selectedLabelName: '',
      commissionEnabled: false,
      commissionValue: '',
    });
    if (this.data.shangpinList.length > 0) {
      this.setSelectedType(this.data.shangpinList[0]);
    }
  },

  async onSubmit() {
    if (this.data.isSubmitting) return;
    if (!this.validateForm()) return;
    this.setData({ isSubmitting: true });

    const postData = {
      shangpinTypeId: this.data.selectedTypeId,
      huiyuanId: this.data.selectedHuiyuanId,
      yaoqiuleixing: this.data.selectedYaoqiuleixing,
      dingdanJieshao: this.data.dingdanJieshao.trim(),
      dingdanBeizhu: this.data.dingdanBeizhu.trim() || '',
      laobanName: this.data.laobanName.trim(),
      zhidingUid: this.data.zhidingUid.trim() || '',
      waibuDingdanId: this.data.waibuDingdanId.trim() || '',
      jiage: this.data.jiage,
      labelId: this.data.selectedLabelId || '',
      labelName: this.data.selectedLabelName || '',
      commissionEnabled: this.data.commissionEnabled,
      commissionValue: this.data.commissionEnabled ? this.data.commissionValue : '',
    };

    try {
      const res = await request({
        url: isStaffMode() ? STAFF_API.orderDispatch : '/dingdan/sjpaifa',
        method: 'POST',
        data: postData,
      });
      if (res && res.data.code === 200) {
        wx.showToast({ title: '派单成功', icon: 'success', duration: 2000 });
        const orderAmount = parseFloat(this.data.jiage);
        if (this.data.isStaffMode) {
          this.loadShangjiaYue();
        } else {
          const app = getApp();
          if (app.globalData.shangjia) {
            const newBalance = parseFloat(app.globalData.shangjia.sjyue || '0') - orderAmount;
            app.globalData.shangjia.sjyue = newBalance.toFixed(2);
            app.globalData.shangjia.fadanzong = (parseInt(app.globalData.shangjia.fadanzong || '0') + 1).toString();
            app.globalData.shangjia.riliushui = (parseFloat(app.globalData.shangjia.riliushui || '0') + orderAmount).toFixed(2);
            app.globalData.shangjia.yueliushui = (parseFloat(app.globalData.shangjia.yueliushui || '0') + orderAmount).toFixed(2);
            this.setData({ sjyue: app.globalData.shangjia.sjyue });
          }
        }
        setTimeout(() => {
          this.resetForm();
          this.setData({ isSubmitting: false });
        }, 1500);
      } else {
        wx.showModal({
          title: '派单失败',
          content: res.data.msg || '请稍后重试',
          showCancel: false,
        });
        this.setData({ isSubmitting: false });
      }
    } catch (error) {
      console.error('派单请求失败:', error);
      wx.showModal({
        title: '请求失败',
        content: error.message || '网络错误，请检查连接',
        showCancel: false,
      });
      this.setData({ isSubmitting: false });
    }
  },
}));
