const ServiceBase = require("../../sve.base");
const system = require('../../../system')
class ProductService extends ServiceBase {
  constructor() {
    super("product", ServiceBase.getDaoName(ProductService));
    this.itemDao = system.getObject("db.product.productitemDao");
  }

  async getPage (page, limit, type, keywords) {
    return await this.dao.getPage(page, limit, type, keywords)
  }

  async getAllDic (type) {
    return await this.dao.getAllDic(type)
  }

  async getByIds (ids) {
    return await this.dao.getByIds(ids)
  }

  async getItems (id) {
    const querys = {
      where: { parent_id: id },
      attributes: ['product_id'],
      raw: true
    };
    let ids = await this.itemDao.getAll(querys)
    let arr = []
    for (let i of ids) {
      arr.push(i.product_id)
    }
    let result = await this.dao.getByIds(arr)
    return result
  }

  async checkSitem(ids) {
    let res = await this.dao.getByIds(ids, [0])
    let arr = []
    for (let i of res) {
      arr.push(i.id)
    }
    if (JSON.stringify(ids) == JSON.stringify(arr)) {
      return true
    } else {
      return false
    }
  }

  async createOrUpdate (params) {
    if (params.id) {
      return await this.update(params)
    } else {
      return await this.create(params)
    }
  }

  async create (params) {
    let items
    if (params.product_type == 1) {
      items = JSON.parse(JSON.stringify(params.items))
      delete params.items
    }
    params.source_id = params.source_id || 10001
    let result = await this.dao.create(params)
    let itemArr = []
    if (items) {
      for (let i of items) {
        itemArr.push({ parent_id: result.id, product_id: i })
      }
      let itemResult = await this.itemDao.createMany(itemArr)
    }
    return result
  }

  async update (params) {
    let items
    if (params.product_type == 1) {
      items = JSON.parse(JSON.stringify(params.items))
      delete params.items
    }
    params.source_id = params.source_id || 10001
    let result = await this.dao.update(params)
    let itemArr = []
    if (items) {
      for (let i of items) {
        itemArr.push({ parent_id: result.id, product_id: i })
      }
      await this.itemDao.delete({ parent_id: params.id })
      let itemResult = await this.itemDao.createMany(itemArr)
    }
    return result
  }
}
module.exports = ProductService;