const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")

class DeliverService extends ServiceBase {
  constructor() {
    super("deliver", ServiceBase.getDaoName(DeliverService));
    this.deliveruserDao = system.getObject("db.deliver.deliveruserDao");
    this.deliverorgDao = system.getObject("db.deliver.deliverorgDao");
  }

  async apiAll(params) {
    try {
      return await this.allList();
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiPage(params) {
    try {
      return await this.page(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiSave(params) {
    try {
      return await this.save(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiInfo(params) {
    try {
      return await this.info(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, "接口异常");
    }
  }

  async apiDeleteByIds(params) {
    var ids = params.ids;
    if (!ids || ids.length == 0) {
      return system.getResult(null, "传入参数错误：ids=" + JSON.stringify(ids));
    }
    try {
      for (var id of ids) {
        try {
          await this.delById(id);
        } catch (error) {
          console.log(error);
        }
      }
      return system.getResultSuccess(1);
    } catch (error) {
      return system.getResult(null, "接口异常");
    }
  }

  // -----------------------以此间隔，上面为API，下面为service---------------------------------

  async info(params) {
    let id = params.id;
    let item = await this.dao.getById(id);
    this.handleDate(item, ["created_at"], null, -8);
    let user = await this.deliveruserDao.getById(item.admin_id);
    if (user) {
      user.password = "";
      item.real_name = user.real_name || "";
      item.ucname = user.ucname || "";
      item.user = user;
    }
    return system.getResultSuccess(item);
  }

  async login(params) {
    let ucname = this.trim(params.ucname);
    let password = this.trim(params.password);

    let loginUser = await this.deliveruserDao.findByUcname(ucname);
    if (!loginUser) {
      return system.getResult(null, "用户名或密码错误");
    }

    let pwd = await this.getEncryptStr(password);
    if (pwd != loginUser.password) {
      return system.getResult(null, "用户名或密码错误");
    }

    loginUser.password = "";
    loginUser.deliver = await this.dao.getById(loginUser.deliver_id);
    return system.getResultSuccess(loginUser);
  }

  async save(params) {
    let id = params.id;
    let deliver;
    let user;
    if (id) {
      deliver = await this.dao.findById(id);
      if(deliver.admin_id) {
        user = await this.deliveruserDao.findById(deliver.admin_id);
      }
    } else {
      deliver = {};
    }

    if (!user) {
      let exists = await this.deliveruserDao.findOne({ucname: params.ucname});
      if(exists) {
        return system.getResult(null, `用户名[${params.ucname}]重复`);
      }
    }

    deliver.name = this.trim(params.name);
    deliver.businessmenDivide = 0;
    deliver.invoiceDivide = 0;
    deliver.isEnabled = params.isEnabled == 1 ? true : 0;
    deliver.remark = this.trim(params.remark);
    deliver.saas_id = this.trim(params.saas_id);

    if (id) {
      deliver = await deliver.save();
    } else {
      deliver = await this.dao.create(deliver);
    }
    user = user || {};
    user.real_name = params.real_name;
    user.auth = '1111';
    if (user.id) {
      user = await user.save();
    } else {
      user.saas_id = deliver.saas_id;
      user.isAdmin = true;
      user.deliver_id = deliver.id;
      user.ucname = params.ucname;
      user.password = await this.getEncryptStr(params.password);
      user = await this.deliveruserDao.model.create(user);
    }
    deliver.admin_id = user.id;
    await deliver.save();

    if(user.org_id) {
      let org = await this.deliverorgDao.findById(user.org_id);
      org.name = deliver.name;
      org.path = deliver.name + ".";
      await org.save();
 
      user.org_path = org.path;
      await user.save();
    } else {
      let org = {
        deliver_id: deliver.id,
        name: deliver.name,
        parent_id: 0,
        path: deliver.name + ".",
        type: '',
        del_flag: 0,
        group_type: 0
      };

      org = await this.deliverorgDao.model.create(org);
      user.org_id = org.id;
      user.org_path = org.path;
      await user.save();
    }
    return system.getResultSuccess();
  }

  async updPassword(params) {
    let user = await this.deliveruserDao.findById(params.admin_id);
    if (!user) {
      return system.getResult(null, '交付商管理员账户不存在');
    }
    user.password = await this.getEncryptStr(params.password);
    await user.save();

    return system.getResultSuccess();
  }

  async allList() {
    var list = await this.dao.getList(1);
    return system.getResultSuccess(list);
  }

  async delById(id) {
    if (!id) {
      return system.getResult(null, "删除失败");
    }
    await this.dao.delById(id);
    return system.getResultSuccess(1);
  }

  async page(params) {
    let currentPage = Number(params.currentPage || 1);
    let pageSize = Number(params.pageSize || 10);

    let where = {};

    let orderby = [
      ["id", 'desc']
    ];

    let page = await this.getPageList(currentPage, pageSize, where, orderby, null);
    if (page && page.rows) {
      for (var row of page.rows) {
        this.handleDate(row, ["created_at"], null, -8);
      }
      await this.setUser(page.rows);
    }
    return system.getResultSuccess(page);
  }

  async enable(params) {
    let deliver = await this.findById(params.id);
    deliver.isEnabled = params.isEnabled == 0 ? false : true;
    await deliver.save();
    return system.getResultSuccess();
  }

  async setUser(rows) {
    if (!rows || rows.length == 0) {
      return;
    }
    let ids = [];
    for (let item of rows) {
      if (item.admin_id) {
        ids.push(item.admin_id);
      }
    }
    let map = await this.deliveruserDao.findMapByIds(ids);
    for (let item of rows) {
      let user = map[item.admin_id] || {};
      user.password = "";
      item.real_name = user.real_name || "";
      item.ucname = user.ucname || "";
      item.user = user;
    }
  }

  async deliverUsers(params) {
    let sql = "SELECT * FROM d_deliver_user WHERE deliver_id = :deliver_id AND isAdmin = 0";
    let list = await this.customQuery(sql, params);

    if (list) {
      for (let item of list) {
        item.realName = item.real_name;
      }
    }
    return system.getResultSuccess(list);
  }

  async deliverUserMap(params) {
    if (!params.ids || params.ids.length == 0) {
      return;
    }

    let sql = "SELECT * FROM d_deliver_user WHERE id IN (:ids)";

    let list = await this.customQuery(sql, {ids: params.ids});

    let result = {};
    if (!list || list.length == 0) {
      return result;
    }

    for (let item of list) {
      result[item.id] = item;
    }
    return result;
  }
}

module.exports = DeliverService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });