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) {
    let result = await this.dao.getPage(page, limit, type, keywords)
    for (let i = 0; i < result.rows.length; ++i) {
      if (result.rows[i].price) {
        result.rows[i].setDataValue("price", result.rows[i].price / 100)
      }
    }
    return result
  }

  async getAllDic (type = [1, 2]) {
    let query = {
      where: { product_type: { [this.db.Op.in]: type }, source_id: 10001 },
      attributes: ['id', 'product_type', 'product_name', 'price', 'product_property'],
      include: [{
        model: this.itemDao.model,
        attributes: [['product_id', 'id']],
        require: false,
        raw: true
      }],
    }
    this.dao.model.hasMany(this.itemDao.model, { foreignKey: 'parent_id' })
    let result = await this.dao.model.findAll(query)
    for (let i in result) {
      let res = []
      res = result[i].dataValues.productitems.map((data) => {
        return data.id
      })
      result[i].setDataValue("ids", res)
      result[i].setDataValue('price', result[i].price ? result[i].price / 100 : result[i].price)
      delete result[i].dataValues.productitems
      let resItem = await this.dao.model.findAll({
        where: {
          id: { [this.db.Op.in]: res }
        },
        attributes: ['id', 'product_name', 'price', 'product_property'],
        raw: true
      })

      for (let j = 0; j <= resItem.length; ++j) {
        if (resItem[j] && resItem[j].price && resItem[j].price > 0) {
          resItem[j].price = resItem[j].price / 100
        }
      }
      result[i].setDataValue('items', resItem)
    }
    return result
  }

  async getByIds (ids) {
    let result = await this.dao.getByIds(ids)
    for (let i = 0; i < result.length; ++i) {
      if (result[i].price) {
        result[i].setDataValue("price", result[i].price / 100)
      }
    }
    return result
  }

  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)
    for (let i in result) {
      if (result[i].price) {
        result[i].setDataValue("price", result[i].price / 100)
      }
    }
    let res = result.map((data) => {
      return data.id
    })
    let ans = {}
    ans.items = result
    ans.ids = res
    let pro = await this.dao.model.findOne({ where: { id: id } })
    pro.setDataValue("price", pro.price / 100)
    ans.pro = pro
    return ans
  }

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

  async maxItem (ids) {
    let res = await this.dao.getByIds(ids)
    let arr = []
    arr = res.map(data => {
      return data.product_property
    })
    arr = arr.sort()
    for (let i = 0; i < arr.length - 1; ++i) {
      if (arr[i] === arr[i + 1]) {
        return false
      }
    }
    return true
  }

  async createOrUpdate (params) {
    if (params.price) {
      params.price = Math.round(parseFloat(params.price) * 100)
    }
    if (params.id) {
      return await this.update(params)
    } else {
      return await this.create(params)
    }
  }

  async create (params) {
    let items
    if (params.product_type == 2) {
      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 == 2) {
      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
  }

  async apiList () {
    return [
      { key: "nameTwo_1", name: "姓名二要素-e签宝" },
      { key: "handsign_1", name: "手动签-e签宝" },
      { key: "autoSign_1", name: "静默签-e签宝" },
      { key: "bankThree_2", name: "银行卡三要素-兰铂旺" },
      { key: "bankFour_2", name: "银行卡四要素-兰铂旺" }
    ]
  }
  async apiMap () {
    let list = await this.apiList();
    let map = {};
    for (let item of list) {
      map[item.key] = item;
    }
    return map;
  }
}
module.exports = ProductService;