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(params);
    } 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) || {};
    loginUser.isManager = loginUser.deliver.admin_id == loginUser.id;

    this.setAuth(loginUser);

    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) {
      if(params.password) {
        user.password = await this.getEncryptStr(params.password);
      }
      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(deliver);
  }

  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(params) {
    params.isEnabled = 1;
    var list = await this.dao.getList(params);
    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 = {};
    if (params.id) {
      where.id = this.trim(params.id);
    }
    if (params.name) {
      where.name = this.trim(params.name);
    }
    if (params.saas_id) {
      where.saas_id = this.trim(params.saas_id);
    }
    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 deliver = await this.dao.findById(params.deliver_id);
    params.admin_id = deliver.admin_id;
    let sql = "SELECT * FROM d_deliver_user WHERE deliver_id = :deliver_id AND id <> :admin_id ";
    let list = await this.customQuery(sql, params);

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

  async deliverUserAll(params) {
    let sql = "SELECT * FROM d_deliver_user WHERE deliver_id = :deliver_id ";
    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;
  }

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

    let deliver_id = params.deliver_id;
    if (!deliver_id) {
      return system.getResultSuccess({ count: 0, rows: [], msg: "deliver_id is empty" });
    }

    let where = {
      deliver_id: deliver_id
    };

    
    if(params.org_id) {
      let org = await this.deliverorgDao.findById(params.org_id);
      if(!org) {
        return system.getResultSuccess({ count: 0, rows: [], msg: "deliver_id is empty" });
      }

      where.org_path = {
        [this.db.Op.like]: org.path + "%"
      };
    }

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

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

  async deliverUserInfo(params) {
    let id = params.id;
    let user = await this.deliveruserDao.findById(id);
    let deliver = await this.findById(user.deliver_id);
    
    return system.getResult({
      user: user,
      deliver: deliver,
    });
  }

  async deliverSynUpdate(params) {
    let user = await this.deliveruserDao.findById(params.user_id);
    let deliver = await this.findById(user.deliver_id);

    if(!user.nt_user_id) {
      user.nt_user_id = params.nt_user_id;
      await user.save();
    }
    if(!deliver.nt_company_id) {
      deliver.nt_company_id = params.nt_company_id;
      await deliver.save();
    }
    return system.getResultSuccess();
  }

  setAuth(row) {
    if (row.isManager) {
      row.auth = [1, 2, 3, 4];
      row.authNames = "管理员";
      return;
    }
    let auth = row.auth;
    if (!auth || auth.length < 4) {
      row.auth = [];
      row.authNames = "";
      return;
    }
    let gsb = Number(row.auth[0] || 0);
    let cwb = Number(row.auth[1] || 0);
    let swb = Number(row.auth[2] || 0);
    let pjb = Number(row.auth[3] || 0);
    let authArr = [];

    let authNames = [];
    if (gsb) {
      authArr.push(1);
      authNames.push("工商宝");
    }
    if (cwb) {
      authArr.push(2);
      authNames.push("财务宝");
    }
    if (swb) {
      authArr.push(3);
      authNames.push("税务宝");
    }
    if (pjb) {
      authArr.push(4);
      authNames.push("票据宝");
    }
    row.auth = authArr;
    row.authNames = authNames.join("、");
  }

  async setOrg(rows) {
    if (!rows || rows.length == 0) {
      return;
    }

    let orgIds = [];
    for (let row of rows) {
      orgIds.push(row.org_id);
    }

    let orgMap = await this.deliverorgDao.findMapByIds(orgIds);
    for (let row of rows) {
      row.org = orgMap[row.org_id] || {};
    }
  }
  async deliverUserById(params) {
    let id = params.id;
    let user = await this.deliveruserDao.getById(id) || {};
    user.password = "";
    this.setAuth(user);
    return system.getResultSuccess(user);
  }
  async deliverUserSave(params) {
    let deliver_id = params.deliver_id;
    if (!deliver_id) {
      return system.getResult(null, "交付商不存在");
    }

    let id = params.id;
    let real_name = this.trim(params.real_name);
    let ucname = this.trim(params.ucname);
    let org_id = params.org_id;
    let isAdmin = Number(params.isAdmin || 0);
    let authArr = [];
    if (params.auth) {
      for (let authCode of params.auth) {
        if (authCode) {
          authArr.push(Number(authCode));
        }
      }
    }

    let deliver = await this.dao.findById(deliver_id);
    if (!deliver) {
      return system.getResult(null, "交付商不存在");
    }

    let org = await this.deliverorgDao.findById(org_id);
    if (!org) {
      return system.getResult(null, "组织机构不存在");
    }
    let user;
    if (id) {
      user = await this.deliveruserDao.findById(id);
    } else {
      user = await this.deliveruserDao.findOne({ ucname: ucname });
      if (user) {
        return system.getResult(null, `账号【${ucname}】已存在`)
      }
      user = {};
    }

    user.real_name = real_name;
    user.org_id = org_id;
    user.org_path = org.path;
    user.isAdmin = isAdmin ? true : false;
    let auth = [];
    for (let i = 1; i <= 4; i++) {
      if (authArr.indexOf(i) == -1) {
        auth.push("0");
      } else {
        auth.push("1");
      }
    }
    user.auth = auth.join("");

    if (user.id) {
      await user.save();
    } else {
      user.saas_id = deliver.saas_id;
      user.deliver_id = deliver.id;
      user.ucname = params.ucname;
      user.password = await this.getEncryptStr(params.password);
      user = await this.deliveruserDao.model.create(user);
    }

    return system.getResultSuccess(user);
  }

  async orgTree(params) {
    try {
      let deliver_id = params.deliver_id;
      if (!deliver_id) {
        return system.getResult(null, "交付商不存在");
      }

      var all = await this.deliverorgDao.byDeliverId(params.deliver_id, '') || [];
      for (let row of all) {
        this.handleDate(row, ["created_at"], null, -8);
      }
      var pmap = {};
      for (let item of all) {
        item.label = item.name;
        var list = pmap[item.parent_id] || [];
        list.push(item);
        pmap[item.parent_id] = list;
      }
      for (let item of all) {
        item.children = pmap[item.id] || [];
      }
      return system.getResult(pmap[0]);
    } catch (error) {
      return system.getResult(-1, `系统错误 错误信息 ${error}`);
    }
  }

  async orgById(params) {
    let org = await this.deliverorgDao.getById(params.id) || "";
    return system.getResultSuccess(org);
  }

  async allOrg(params) {
    let deliver_id = params.deliver_id;
    if (!deliver_id) {
      return system.getResultSuccess([]);
    }
    var all = await this.deliverorgDao.byDeliverId(params.deliver_id, '') || [];
    for (let row of all) {
      this.handleDate(row, ["created_at"], null, -8);
    }
    return system.getResultSuccess(all);
  }

  async orgSave(params) {
    let id = params.id;
    let pid = params.parent_id;
    let name = params.name;
    let deliver_id = params.deliver_id;
    if (!pid) {
      return system.getResult(null, "请选择上级部门");
    }

    let parent = await this.deliverorgDao.findById(pid);
    if (!parent) {
      return system.getResult(null, "上级部门不存在");
    }
    if (!name) {
      return system.getResult(null, "请填写部门名称");
    }
    if (!deliver_id) {
      return system.getResult(null, "交付商不存在");
    }

    let org;
    if (id) {
      org = await this.deliverorgDao.findById(id);
    } else {
      org = {};
    }
    org.deliver_id = deliver_id;
    org.name = name;
    org.parent_id = pid;
    org.path = parent.path + name + ".";
    org.type = '';
    org.del_flag = 0;
    org.group_type = 0;
    if (org.id) {
      org = await org.save();
    } else {
      org.saas_id = this.trim(params.saas_id);
      org = await this.deliverorgDao.model.create(org);
    }
    return system.getResultSuccess(org);
  }
}

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