import Vue from 'vue'

export default function getAttributeList (payload = {}) {
  return new Promise(async (resolve, reject) => {
    const isSpec = payload.attribute_type === 0
    const actions = [
      {
        title: '添加',
        action: 'goAttributeDetail',
        actionOption: {
          type: payload.attribute_type,
          id: payload.attribute_category_id,
          name: Vue.stack.getStack().list.attribute.find(i => i.name === 'attribute-list').title,
        },
        props: {
          type: 'primary',
        },
      },
    ]

    // 表格项
    const columns = {
      name: {
        title: `${isSpec ? '规格' : '参数'}名称`,
        key: 'name',
        align: 'center',
      },
      attribute_category_name: {
        title: '商品属性',
        key: 'attribute_category_name',
        align: 'center',
      },
      input_list: {
        title: '可选值',
        key: 'input_list',
        align: 'center',
      },
      sort: {
        title: '排序',
        key: 'sort',
        align: 'center',
      },
    }

    const columnsExtra = {
      nodeType: 'action',
      payload: {
        title: '操作',
        list: [
          {
            title: '编辑',
            action: 'goAttributeDetail',
            props: {
              type: 'primary',
              loading: false,
            },
          },
          {
            title: '删除',
            action: 'deleteAttributeDetail',
          },
        ],
      },
    }

    const isOption = !payload.attribute_type && payload.attribute_type !== 0
    const requestBody = !isOption
      ? payload
      : {
        attribute_category_id: payload.attribute_category_id,
        per_page: 1000,
      }
    try {
      const { data, extra, meta } = await Vue.http.get('/product/attribute/item', {
        params: requestBody,
      })

      if (isOption) return resolve(data)
      const response = {
        filters: [],
        actions,
        data,
        columns: extra.columns
          .map(key => columns[key])
          .filter(Boolean)
          .concat(columnsExtra),
        page: meta.pagination,
        title: isSpec ? '规格列表' : '参数列表',
      }
      resolve(response)
    } catch (e) {
      reject(e)
    }
  })
}