import { onPageLoadInitAuth, post } from '@/utils/https';
import {
  cloneLite,
  getAuthInfo,
  getDataSet,
  searchValueFormat,
  sleep,
  toArray,
  toastSuccess,
  toNumber,
} from '@/utils/util';

const defaultParams = { curr_page: 1, page_count: 20 };

Page({
  /**
   * 页面的初始数据
   */
  data: {
    params: cloneLite(defaultParams) as any,
    list: [] as any[],
    count: 0,
    sort: [{ label: '创建日期', value: 'create_date' }],
    depots: [] as any[],
    goodsClass: [] as any[],
  },
  handleLogin(e: any) {
    this.setData({ isLogin: e.detail });
    if (e.detail) {
      this.init();
      this.getList();
    }
  },
  init() {
    this.setData({ authInfo: getAuthInfo() });

    this.getData();
  },
  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);
  },
  /**
   * 根据父级ID排序树形结构的一维数组
   */
  sortTreeArrayByParentId(
    arr: any[],
    rootParentId = 0,
    idKey = 'cate_id',
    parentIdKey = 'parent_cate_id',
  ) {
    // 1. 构建映射表，快速查找子节点
    const nodeMap = new Map();
    arr.forEach((node) => {
      nodeMap.set(node[idKey], { ...node, children: [] });
    });

    // 2. 构建树形结构
    const tree: any[] = [];
    arr.forEach((node) => {
      const currentNode = nodeMap.get(node[idKey]);
      const parentNode = nodeMap.get(node[parentIdKey]);

      if (parentNode) {
        // 有父节点，添加到父节点的children中
        parentNode.children.push(currentNode);
      } else if (node[parentIdKey] === rootParentId) {
        // 根节点，直接加入树形结构
        tree.push(currentNode);
      }
    });

    // 3. 递归扁平化树形结构，按层级输出
    function flattenTree(nodes: any[]) {
      const result: any[] = [];
      nodes.forEach((node) => {
        // 先加入当前节点
        result.push({ ...node, children: undefined }); // 移除children属性，还原原始结构
        // 递归处理子节点
        if (node.children && node.children.length > 0) {
          result.push(...flattenTree(node.children));
        }
      });
      return result;
    }

    return flattenTree(tree);
  },
  getData() {
    post('ErpDepot/list').then((res: any) => {
      const depots = toArray(res.data?.list).map((el) => {
        return { label: el.depot_name, value: el.depot_id };
      });
      this.setData({ depots });
    });
    post('GoodsCategory/list').then((res: any) => {
      // const goodsClass = toArray(res.data?.list).map((el) => {
      //   return { label: el.cate_name, value: el.cate_id };
      // });
      const sortedArray = this.sortTreeArrayByParentId(toArray(res.data?.list)).map((el) => {
        return { label: el.cate_name, value: el.cate_id };
      });

      this.setData({ goodsClass: sortedArray });
    });
  },
  getList(curr: number = 1) {
    this.data.params.curr_page = curr;
    this.setData({ params: this.data.params });
    const temp = cloneLite(this.data.params);
    if (!temp.depot_id) {
      delete temp.depot_id;
    }
    if (!temp.goods_class) {
      delete temp.goods_class;
    }
    return new Promise<void>((resolve, reject) => {
      post('ErpGoods/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,
            isLogin: true,
          });
          resolve(res);
        })
        .catch((res) => {
          this.setData({ isLogin: false });
          reject(res);
        });
    });
  },

  onDetail(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    wx.navigateTo({
      url: `/pages/other/goodsDetail/goodsDetail?goods_id=${
        item.goods_id
      }&title=${encodeURIComponent(item.goods_name)}`,
    });
  },
  onDelete(e: any) {
    const data = getDataSet(e);
    const index = data.index;
    const item = this.data.list[index];
    wx.showModal({
      title: '提示',
      content: `确认删除 ${item.goods_name}?`,
      success: (res) => {
        if (res.confirm) {
          post('ErpGoods/deleteGoods', { goods_id: JSON.stringify([item.goods_id]) }).then(() => {
            toastSuccess('删除成功');
            sleep(() => {
              this.getList(this.data.params.curr_page);
            }, 1500);
          });
        }
      },
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(_options) {
    onPageLoadInitAuth(this, () => this.getList());
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

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

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

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

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

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