import { post } from '@/utils/https';
import { getAuthInfo, toArray } from '@/utils/util';

Component({
  options: { multipleSlots: true },
  /**
   * 组件的属性列表
   */
  properties: {
    value: null,
  },
  observers: {
    value: function () {
      this.setData({ label: this.data.listToObj[this.data.value]?.label || '' });
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    visible: false,
    list: [] as any[],
    listToObj: {} as any,
    label: '',
  },
  lifetimes: {
    attached() {
      const auth = getAuthInfo();
      const SF_ERP_ACCOUNT_VIEW = auth.SF_ERP_ACCOUNT_VIEW;
      post('ErpAccount/list', { state: 1 }).then((res: any) => {
        let accountDefaultObj: any = {};
        const list = toArray(res?.data?.list).map((el) => {
          if (el.if_default == 2) {
            accountDefaultObj = el;
          }
          const label = `${el.account_name}${
            SF_ERP_ACCOUNT_VIEW ? `(余额: ${el.current_amount})` : ''
          }`;
          el.label = label;
          this.data.listToObj[el.account_id] = el;
          return {
            label: label,
            value: el.account_id,
          };
        });
        if (!accountDefaultObj) {
          accountDefaultObj = list[0] || {};
        }
        this.setData({ list: list, label: this.data.listToObj[this.data.value]?.label || '' });
        this.triggerEvent('default', accountDefaultObj);
      });
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onShowPicker() {
      this.setData({ visible: true });
    },
    onPickerCancel() {
      this.setData({ visible: false });
    },
    onPickerConfirm(e: any) {
      // console.log(e);
      const item = this.data.listToObj[e.detail.value[0]];
      this.triggerEvent('ok', item);
      this.setData({ visible: false });
    },
  },
});
