'use strict';

const utils = require('../../utils/functions');
const _ = require('../../utils/Underscore');

/**
 *
 *  商品列表通用方法
 *
 *
 *
 * 调用方法示例：
 let a = exports.api.goods.list({keyword:'6F2A44D7FAA04FC4A6355767A53E2218',pageNum:1,pageSize:20}) // 搜索商品
 let b = exports.api.goods.list({noPluCode:true,netPrice:''});   // 无码商品

 * @param params
 * @returns {
   status: 200,
   message: '',
   data: {
     items: [
       {
       id: 'A286C7DFD1B741B6BF108A523C96F91F',
       pluCode: '6935661772101',
       stkCode: '',
       name: '护手霜',
       spec: '60g',
       netPrice: 2.85,
       inventory: 20,
       vip: [
         {name: '银卡会员', price: 2.708, id: '56ygfvduigfdfd'},
         {name: '金卡会员', price: 2.451, id: '987564edffyyj'}
         ],
       categoryName: '零食类->2'
     }
     ],
     pageNum: 1,
     pageTotal: 1
   }
 }
 */

const list = function (params, callback) {
  console.time('testForEach');
  try {
    let shopId = nw.process.mainModule.exports.vue.business.shop.id, where = ` `;
    if (!params) {
      throw new Error('缺少参数：params')
    }
    if (!_.isObject(params)) {
      throw new Error('参数：params必须是对象');
    }
    let keyword = params.keyword, pageNum = params.pageNum || 1, pageSize = params.pageSize || 20;


    if (_.isNaN(pageNum)) {
      throw new Error('参数：pageNum 的值不允许为：NAN')
    }
    if (_.isNaN(pageSize)) {
      throw new Error('参数：pageSize 的值不允许为：NAN')
    }
    if (_.isUndefined(shopId) || _.isNaN(shopId)) {
      throw new Error('缺少参数：shopId')
    }

    if (!_.isUndefined(keyword)) {//有关键词
      if (_.isNaN(keyword - 1)) {//搜索条码
        where += `and (P_GOODS_BASE.NAME LIKE '%${keyword}%' OR P_GOODS_BASE.FULL_NAME LIKE '%${keyword}%' OR P_GOODS_BASE.SIMPLE_NAME LIKE '%${keyword}%')`;
      } else {
        if (keyword.toString().length > 7) {
          where += `and (P_GOODS.PLU_CODE = '${keyword}')`;
        } else if (keyword.toString().length < 5) {
          where += `and (P_GOODS_BASE.NAME LIKE '%${keyword}%' OR P_GOODS_BASE.FULL_NAME LIKE '%${keyword}%' OR P_GOODS_BASE.SIMPLE_NAME LIKE '%${keyword}%')`;
        } else {
          where += `and (P_GOODS.STK_CODE = '${keyword}')`;
        }
      }
    }
    if (params.costly) {
      where += ` AND P_GOODS_BASE.COSTLY='Y' `
    }

    if (params.noPluCode) {
      if (_.isNaN(parseFloat(params.netPrice))) {
        throw new Error('无码商品模式，请传入 netPrice')
      }
      let sql2 = `SELECT ID FROM P_GOODS WHERE PLU_CODE = '0000000000000'
                  AND SHOP_ID = '${shopId}'`
      nw.process.mainModule.exports.api.db.select(sql2,
        function (items) {
          // 无码商品直接输出
          _.isFunction(callback) && callback({
            code: 200,
            message: '',
            data: {
              items: [
                {
                  goodId: items[0].ID,
                  pluCode: '0000000000000',
                  stkCode: '',
                  name: '无码商品',
                  spec: '',
                  purPrice: parseFloat(params.netPrice),
                  netPrice: parseFloat(params.netPrice),
                  inventory: 0,
                  vip: [],
                  categoryName: '无',
                  isUseVip: false
                }
              ],
              pageNum: 1,
              pageTotal: 1
            }
          })
        });

      return
    } else {
      where += `and P_GOODS_BASE.NAME != '无码商品'`
    }

    let sql = `SELECT TEMP.id AS goodId,
       TEMP.plu_code AS pluCode,
       TEMP.stk_code AS stkCode,
       TEMP.name AS name,
       TEMP.spec AS sepc,
       TEMP.net_price AS netPrice,
       TEMP.pur_price AS purPrice,
       TEMP.QTY AS inventory,
       TEMP.uom AS uom,
       TEMP.uom AS uomName,
       TEMP.isUseVip AS isUseVip,
       '[' || GROUP_CONCAT(TEMP.vip, ',') || ']' AS vip,
       categoryName
  FROM (
SELECT P_GOODS.id,
               P_GOODS.net_price,
               P_GOODS.pur_price,
               P_GOODS.plu_code,
               P_GOODS.stk_code,
               P_GOODS_BASE.IS_USE_VIP AS isUseVip,
               P_GOODS_BASE.name,
               P_GOODS_BASE.SPEC,
               P_GOODS_BASE.QTY,
               '{"name":"' || B_MEMBER_GRADE.name || '","price":' ||
               CAST(ROUND(P_GOODS_VIP.DISC_RATE * P_GOODS.net_price, 3) AS CHAR) ||
               ',"id":"' || P_GOODS_VIP.GRADE_ID || '"}' AS vip,
               d.categoryName AS categoryName,
               P_UOM.name AS uom
          FROM P_GOODS_BASE
          LEFT JOIN P_GOODS ON P_GOODS.GOODS_BASE_ID = P_GOODS_BASE.ID
          LEFT JOIN P_GOODS_VIP ON P_GOODS_VIP.GOODS_BASE_ID = P_GOODS_BASE.ID
          LEFT JOIN B_MEMBER_GRADE ON P_GOODS_VIP.GRADE_ID = B_MEMBER_GRADE.GRADE_ID
          LEFT JOIN (SELECT P_CATEGORY.ID AS ID,
                           (CASE WHEN  P_CATEGORY_PARENT.NAME IS NULL  THEN P_CATEGORY.NAME ELSE P_CATEGORY_PARENT.NAME||'->'||P_CATEGORY.NAME END) AS CATEGORYNAME
                      FROM P_CATEGORY
                      LEFT JOIN P_CATEGORY P_CATEGORY_PARENT
                        ON P_CATEGORY.PARENT_ID = P_CATEGORY_PARENT.id) D ON P_GOODS_BASE.CATEGORY_ID = D.ID
          LEFT JOIN P_UOM ON P_UOM.ID = P_GOODS.UOM_ID
         WHERE P_GOODS.IS_DELETE != 'Y'
           AND P_GOODS_BASE.STATUS = 'Y'
           AND P_GOODS_BASE.SHOP_ID = '${shopId}' ${where}
) TEMP
 GROUP BY TEMP.ID`;
    nw.process.mainModule.exports.api.db.select(`SELECT count(*) as total FROM (${sql})`, function (count) {
      if (count[0]['total'] === 0) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: {
            items: [],
            pageNum: pageNum,
            pageTotal: count[0]['total']
          }
        })
      } else {
        nw.process.mainModule.exports.api.db.select(`${sql} limit ${(pageNum - 1) * pageSize},${(pageNum - 1) * pageSize + pageSize}`,
          function (items) {
            items.map(function (item) {
              item.vip = JSON.parse(item.vip);
              return item
            });
            _.isFunction(callback) && callback({
              code: 200,
              message: '',
              data: {
                items: items,
                pageNum: pageNum,
                pageTotal: count[0]['total']
              }
            })
          });
      }
    });

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};


/**
 * 新增/修改包装单位
 * @param params
 * {
  "businessId": "7467d3b1137a4ce0be8dc8edd1667257",
  "createTime": "2017-12-02 10:24:12",
  "id": "8488d3b1137a4ce0be8dc9dvd1667257",
  "name": "箱"
}
 * @param type
 */
const addUom = function (params, callback) {
  return addOrUpdateUom(params, 'add', callback)
}
const updateUom = function (params, callback) {
  return addOrUpdateUom(params, 'update', callback)
}
const addOrUpdateUom = function (params, type, callback) {
  let sqls = []
  try {
    if (!_.isArray(params)) {
      params = [params]
    }

    for (let i = 0; i < params.length; i++) {

      if (!_.isObject(params[i])) {
        throw new Error('参数：params必须是对象');
      }

      if (!params[i].name) {
        throw new Error('缺少包装单位的名称');
      }

      if (!params[i].id) {
        // 因为包装单位只能在线上添加，所以在这里必须有ID（线上生成的）
        throw new Error('缺少包装单位的ID');
      }
      if (!params[i].id && !params[i].createTime) {
        // 因为包装单位只能在线上添加，所以在添加时间以线上的为准
        throw new Error('缺少包装单位的createTime');
      }

      if (params[i].createTime) {
        params[i].createTime = new Date(params[i].createTime).format('yyyy-MM-dd hh:mm:ss');
      }
      if (params[i].modifyTime) {
        params[i].modifyTime = new Date(params[i].modifyTime).format('yyyy-MM-dd hh:mm:ss');
      }
      if (type === 'add') {
        sqls.push(utils.getInsertSql('P_UOM', params[i]))
      } else {
        sqls.push(utils.getUpdateSql('P_UOM', params[i], {id: params[i].id}))
      }
    }
    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }

    });

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};


const deleteUom = function (params, callback) {
  try {
    let sqls = []
    if (!_.isArray(params)) {
      params = [params]
    }
    params.map((item) => {
      sqls.push(`DELETE FROM P_UOM where  ID = '${item.id}' and BUSINESS_ID = '${nw.process.mainModule.exports.vue.business.base.id}'`)
    });
    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }
    });

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }

};

/**
 * 新增或修改分类信息
 * @param params
 * @returns {*}
 */

const addCategory = function (params, callback) {
  return addOrUpdateCategory(params, 'add', callback)
}
const updateCategory = function (params, callback) {
  return addOrUpdateCategory(params, 'update', callback)
}
const addOrUpdateCategory = function (params, type, callback) {
  let sqls = [];
  try {
    if (!_.isArray(params)) {
      params = [params]
    }

    for (let i = 0; i < params.length; i++) {

      if (!_.isObject(params[i])) {
        throw new Error('参数：params必须是对象');
      }
      if (!params[i].id) {//修改
        throw new Error('缺少分类的ID');
      }
      if (!params[i].shopId) {
        throw new Error('缺少分类的shopId');
      }
      if (!params[i].name) {
        throw new Error('缺少分类的名称');
      }
      if (!params[i].sortNo) {
        params[i].sortNo = 100
      }
      if (!params[i].isEnable) {
        throw new Error('缺少分类的是否启用标示');
      }
      if (params[i].shopId !== nw.process.mainModule.exports.vue.business.shop.id) {
        throw new Error('该分类的店铺ID与当前门店不一致');
      }
      if (!params[i].id && !params[i].createTime) {
        // 添加时间以线上的为准
        throw new Error('缺少createTime');
      }
      params[i].createTime = new Date(params[i].createTime).format('yyyy-MM-dd hh:mm:ss');

      if (type == 'add') {
        sqls.push(utils.getInsertSql('P_CATEGORY', params[i]))
      } else {
        sqls.push(utils.getUpdateSql('P_CATEGORY', params[i], {id: params[i].id}))
      }
    }
    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '分类同步成功',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }

    })

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};

const deleteCategory = function (params, callback) {
  try {
    let sqls = []
    if (!_.isArray(params)) {
      params = [params]
    }
    params.map((item) => {
      sqls.push(`DELETE FROM P_CATEGORY where  ID = '${item.id}' and SHOP_ID = '${nw.process.mainModule.exports.vue.business.shop.id}'`)
    });
    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }

    });
  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};


/**
 * 新增商品
 * @param params
 * @returns {*}
 */

const addGood = function (params, callback) {
  let sqls = [];
  try {
    if (!_.isObject(params)) {
      throw new Error('参数：params必须是对象');
    }

    if (!params.baseGood) {
      throw new Error('缺少基础商品信息');
    }
    if (!params.syncGoods) {
      throw new Error('缺少商品包装信息');
    }
    if (params.baseGood.shopId !== nw.process.mainModule.exports.vue.business.shop.id) {
      throw new Error('该商品的店铺ID与当前门店不一致');
    }

    if (params.baseGood.createTime) {
      params.baseGood.createTime = new Date(params.baseGood.createTime).format('yyyy-MM-dd hh:mm:ss')
    }
    if (params.baseGood.modifyTime) {
      params.baseGood.modifyTime = new Date(params.baseGood.modifyTime).format('yyyy-MM-dd hh:mm:ss')
    }

    nw.process.mainModule.exports.api.db.select(`SELECT count(*) as total FROM P_GOODS_BASE where ID = ? and SHOP_ID = ?`, [params.baseGood.id, nw.process.mainModule.exports.vue.business.shop.id], function (hasBaseGoodId) {

      if (hasBaseGoodId[0].total > 0) {
        sqls.push(utils.getUpdateSql('P_GOODS_BASE', params.baseGood, {id: params.baseGood.id}))
      } else {
        sqls.push(utils.getInsertSql('P_GOODS_BASE', params.baseGood))
      }
      sqls.push(`DELETE  FROM P_GOODS WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
      for (var i = 0; i < params.syncGoods.length; i++) {
        if (params.syncGoods[i].createTime) {
          params.syncGoods[i].createTime = new Date(params.syncGoods[i].createTime).format('yyyy-MM-dd hh:mm:ss')
        }
        if (params.syncGoods[i].modifyTime) {
          params.syncGoods[i].modifyTime = new Date(params.syncGoods[i].modifyTime).format('yyyy-MM-dd hh:mm:ss')
        }
        sqls.push(utils.getInsertSql('P_GOODS', params.syncGoods[i]))
      }
      sqls.push(`DELETE  FROM P_GOODS_VIP WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
      if (params.goodsVip) {
        for (var i = 0; i < params.goodsVip.length; i++) {
          let vip = params.goodsVip[i];
          delete vip.syncVersion
          if (vip.createTime) {
            vip.createTime = new Date(vip.createTime).format('yyyy-MM-dd hh:mm:ss')
          }
          sqls.push(utils.getInsertSql('P_GOODS_VIP', vip))
        }
      }
      sqls.push(`DELETE  FROM P_GOODS_IMG WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
      if (params.goodsImg) {
        let goodsImg = {
          "id": params.goodsImg.id,
          "goodsBaseId": params.goodsImg.goodsBaseId,
          "imgUrl": params.goodsImg.imgUrl,
          "sortNo": params.goodsImg.sortNo,
          "createTime": new Date(params.goodsImg.createTime).format('yyyy-MM-dd hh:mm:ss'),
        };
        sqls.push(utils.getInsertSql('P_GOODS_IMG', goodsImg))
      }
      nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
        if (!err) {
          _.isFunction(callback) && callback({
            code: 200,
            message: '',
            data: params
          })
        } else {
          _.isFunction(callback) && callback({
            code: 500,
            message: err.message,
            data: params
          })
        }
      });
    });

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};

/**
 * 修改商品
 * @param params
 * @returns {*}
 */

const updateGood = function (params, callback) {

  let sqls = [];
  try {
    if (!_.isObject(params)) {
      throw new Error('参数：params必须是对象');
    }
    if (!params.baseGood) {
      throw new Error('缺少基础商品信息');
    }
    if (!params.syncGoods) {
      throw new Error('缺少商品包装信息');
    }

    if (params.baseGood.shopId !== nw.process.mainModule.exports.vue.business.shop.id) {
      throw new Error('该商品的店铺ID与当前门店不一致');
    }
    console.warn(params.baseGood)

    if (params.baseGood.createTime) {
      params.baseGood.createTime = new Date(params.baseGood.createTime).format('yyyy-MM-dd hh:mm:ss')
    }
    if (params.baseGood.modifyTime) {
      params.baseGood.modifyTime = new Date(params.baseGood.modifyTime).format('yyyy-MM-dd hh:mm:ss')
    }
    params.baseGood.goodsType = 'SINGLE';
    sqls.push(`DELETE  FROM P_GOODS_BASE WHERE ID = '${params.baseGood.id}'`);
    sqls.push(utils.getInsertSql('P_GOODS_BASE', params.baseGood))

    sqls.push(`DELETE  FROM P_GOODS WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
    for (let i = 0; i < params.syncGoods.length; i++) {
      if (params.syncGoods[i].createTime) {
        params.syncGoods[i].createTime = new Date(params.syncGoods[i].createTime).format('yyyy-MM-dd hh:mm:ss')
      }
      if (params.syncGoods[i].modifyTime) {
        params.syncGoods[i].modifyTime = new Date(params.syncGoods[i].modifyTime).format('yyyy-MM-dd hh:mm:ss')
      }
      params.syncGoods[i].shopId = params.baseGood.shopId;

      sqls.push(utils.getInsertSql('P_GOODS', params.syncGoods[i]))
    }
    sqls.push(`DELETE  FROM P_GOODS_VIP WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
    if (params.goodsVip) {
      for (var i = 0; i < params.goodsVip.length; i++) {
        let vip = params.goodsVip[i];
        if (vip.createTime) {
          vip.createTime = new Date(vip.createTime).format('yyyy-MM-dd hh:mm:ss')
        }
        delete vip.syncVersion
        sqls.push(utils.getInsertSql('P_GOODS_VIP', vip))
      }
    }

    sqls.push(`DELETE  FROM P_GOODS_IMG WHERE GOODS_BASE_ID = '${params.baseGood.id}'`);
    if (params.goodsImg) {
      let goodsVipData = {
        "id": params.goodsImg.id,
        "goodsBaseId": params.goodsImg.goodsBaseId,
        "imgUrl": params.goodsImg.imgUrl,
        "sortNo": params.goodsImg.sortNo,
        "createTime": new Date(params.goodsImg.createTime).format('yyyy-MM-dd hh:mm:ss'),
      };
      sqls.push(utils.getInsertSql('P_GOODS_IMG', goodsVipData))
    }


    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }
    });

  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }
};


/**
 * 删除商品
 * @param params
 * @returns {*}
 */

const deleteGood = function (params, callback) {
  try {
    let sqls = []
    // 设置接收变量的数组
    let arr = []
    if (!_.isArray(params.goodsBaseID)) {
      arr = [params.goodsBaseID]
    } else {
      arr = params.goodsBaseID
    }
    arr.map((item) => {
      sqls.push(`update p_goods  set  IS_DELETE = 'Y', MODIFY_TIME = datetime('now','localtime') where GOODS_BASE_ID = '${item}' `)
      sqls.push(`update p_goods_base  set  MODIFY_TIME = datetime('now','localtime') where ID = '${item}' `)
    });
    nw.process.mainModule.exports.api.db.exec(sqls, function (err) {
      if (!err) {
        _.isFunction(callback) && callback({
          code: 200,
          message: '',
          data: params
        })
      } else {
        _.isFunction(callback) && callback({
          code: 500,
          message: err.message,
          data: params
        })
      }
    });
  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }

};


/**
 * @description 获取商品分类
 * @param { String }isEnable: 是否启用（启用(Y)/禁用(N)）–如果为空，都查询
 *        { String }parentId: 商品类别父类ID --如果为空，都查询
 * @return
 */
const getCategoryList = function (params, callback) {
  try {
    let $where = '';
    params = params || {};
    if (params) {
      if (params.parentId) {
        $where += ` AND PARENT_ID= '${params.parentId}'`
      } else {
        $where += ` AND PARENT_ID =''`

      }

      $where += ` AND IS_ENABLE= '${params.isEnable || 'Y'}'`

    }

    let sql = `WITH locs(DISC_RATE,ID,IS_ENABLE,IS_ONLINE,NAME,PARENT_ID,SHOP_ID,SORT_NO)
          AS
          (
          SELECT DISC_RATE,ID,IS_ENABLE,IS_ONLINE,NAME,PARENT_ID,SHOP_ID,SORT_NO from  P_CATEGORY where SHOP_ID=? and IS_ONLINE = 'N' ${$where}
          UNION ALL
          SELECT A.id,A.PARENT_ID,A.name FROM P_CATEGORY A,locs B ON A.PARENT_ID = B.ID
          -- b.pid=a.id 向上递归
          )
          select DISC_RATE AS discRate,
      ID AS id,
      IS_ENABLE AS isEnable,
      IS_ONLINE AS isOnline,
      NAME AS name,
      PARENT_ID AS parentId,
      SHOP_ID AS shopId,
      SORT_NO AS sortNo from locs  order by SORT_NO`;


    nw.process.mainModule.exports.api.db.select(sql, [nw.process.mainModule.exports.vue.business.shop.id], function (items) {
      let arr = [];
      items.map((item) => {
        if (item.parentId === null) {
          item.listBacks = [];
          arr.push(item)
        } else {
          arr[arr.length].listBacks.push(item)
        }

      });
      _.isFunction(callback) && callback({
        code: 200,
        message: '',
        data: arr
      })
    });


  } catch (e) {
    console.error(e)
    _.isFunction(callback) && callback({
      code: 500,
      message: e.message,
      data: null
    })
  }

};

module.exports = {
  list,
  addCategory,
  updateCategory,
  deleteCategory,
  addGood,
  updateGood,
  deleteGood,
  getCategoryList,
  addUom,
  updateUom,
  deleteUom
};
