var system = require("../../../system")
const settings = require("../../../../config/settings")
const CtlBase = require("../../ctlms.base");
const md5 = require("MD5");
const uuidv4 = require('uuid/v4');
const logCtl = system.getObject("web.common.oplogCtl");


class UserCtl extends CtlBase {
  constructor() {
    super();
    this.userSve = system.getObject("service.uc.userSve");
    this.redisClient = system.getObject("util.redisClient");
    this.captchaSve = system.getObject("service.common.captchaSve");
    this.deliverSve = system.getObject("service.common.deliverSve");

    this.redisClientTax = system.getObject("util.redisClientTax");
  }

  async login(pobj, pobj2, req, res) {
    var loginName = this.trim(pobj.loginName);
    var password = this.trim(pobj.password);
    // var captchaKey = this.trim(pobj.captchaKey);
    // var captchaCode = this.trim(pobj.captchaCode);

    try {
      // var vrs = await this.captchaSve.valid({
      //   key: captchaKey,
      //   code: captchaCode,
      // });
      // if (vrs.status !== 0) {
      //   return vrs;
      // }

      var loginUser = await this.deliverSve.login({
        ucname: loginName,
        password: password,
      });
      if (loginUser.status != 0) {
        return loginUser;
      }

      loginUser = loginUser.data;
      var loginKey = await this.setLogin(loginUser);
      let ntapi = settings.ntapi();
      let loginUrl = settings.protocalPrefix + req.headers['host'] + "/#/logins";
      console.log(loginUrl, "---------------loginUrl--------------");
      let loginBaseUrl = system.base64_encode(loginUrl);
      let test = system.base64_decode(loginBaseUrl);
      console.log(test);

      let rs = {
        key: loginKey.xggadminsid,
        // taxLoginUrl: ntapi.taxLoginUrl + `?username=${loginUser.ucname}&cookieId=${loginKey.subsid}&target=tax&baseurl=${loginBaseUrl}`,
        // finLoginUrl: ntapi.taxLoginUrl + `?username=${loginUser.ucname}&cookieId=${loginKey.subsid}&baseurl=${loginBaseUrl}`,
        loginname: loginUser.ucname,
        auth: loginUser.auth,
        isManager: loginUser.isManager,
        menus: {gtArr: this.getOrderMenu(loginUser), pjArr: this.getInvoiceMenu(loginUser)},
        loginUrl: loginUrl,
      };

      return system.getResultSuccess(rs);
    } catch (error) {
      console.log(error);
      return system.getResultFail(500, "接口异常：" + error.message);
    }
  }

  async ngaLogin(params, pobj2, req, res) {
    // 登录用户
    let loginUser = req.loginUser;

    // 登录地址加密
    let ntapi = settings.ntapi();
    let loginUrl = settings.protocalPrefix + req.headers['host'] + "/#/logins";
    console.log(loginUrl, "---------------loginUrl--------------");
    let loginBaseUrl = system.base64_encode(loginUrl);
    let url;

    // 登录用户key
    let subsid = "sub_" + req.sid.replace("jfs_", "");
    await this.redisClientTax.setWithEx(subsid, (loginUser.nt_user_id || "").toString(), 60 * 60 * 5);

    if (params.type == "tax") {
      url = ntapi.taxLoginUrl + `?username=${loginUser.ucname}&cookieId=${subsid}&target=tax&baseurl=${loginBaseUrl}`;
    } else {
      url = ntapi.finLoginUrl + `?username=${loginUser.ucname}&cookieId=${subsid}&baseurl=${loginBaseUrl}`;
    }
    return system.getResult(url);
  }

  async setLogin(user) {
    user.loginsid = "jfs_" + uuidv4();
    await this.redisClient.setWithEx(user.loginsid, JSON.stringify(user), 60 * 60 * 5);
    return {
      xggadminsid: user.loginsid
    };
  }

  async getMenu(qobj, pobj, req) {
    // return system.getResultSuccess(req.loginUser.menus);
    let loginUser = req.loginUser;
    if (!loginUser) {
      return system.getResultSuccess({gtArr: [], pjArr: []})
    }

    let gtArr = this.getOrderMenu(loginUser);
    let pjArr = this.getInvoiceMenu(loginUser);
    return system.getResultSuccess({gtArr: gtArr, pjArr: pjArr});
  }

  getOrderMenu(loginUser) {
    if (!loginUser) {
      return [];
    }
    if (loginUser.isManager) {
      return [
        {
          "name": "数据概览",
          "icon": "iconfont icon-gth-gsshujugailan",
          "team": [
            {
              "name": "业务数据汇总",
              "path": "/home"
            }
          ]
        },
        {
          "name": "订单中心",
          "icon": "iconfont icon-gth-gsdingdanzhongxin",
          "team": [
            {"name": "全部订单", "path": "/trading/ordersAll"},
            {"name": "我的业务订单", "path": "/trading/glyorderInformation"},
            {"name": "工商注册", "path": "/trading/glyRegister"},
            {"name": "刻章办理", "path": "/trading/glyHandle"},
            {"name": "银行开户", "path": "/trading/glyBank"},
            {"name": "税务报道", "path": "/trading/glyReport"},
            {"name": "代理记账", "path": "/trading/glyAccount"},
          ]
        },
        {
          "name": "个体户中心",
          "icon": "iconfont icon-gth-gsgetihuzhongxin",
          "team": [
            {
              "name": "个体户管理",
              "path": "/trading/userInformation"
            },
          ]
        },
      ];
    } else {
      return [
        {
          "name": "数据概览",
          "icon": "iconfont icon-gth-gsshujugailan",
          "team": [
            {
              "name": "业务数据汇总",
              "path": "/home"
            }
          ]
        },
        {
          "name": "订单中心",
          "icon": "iconfont icon-gth-gsdingdanzhongxin",
          "team": [
            {"name": "我的业务订单", "path": "/trading/glyorderInformation"},
            {"name": "工商注册", "path": "/trading/glyRegister"},
            {"name": "刻章办理", "path": "/trading/glyHandle"},
            {"name": "银行开户", "path": "/trading/glyBank"},
            {"name": "税务报道", "path": "/trading/glyReport"},
            {"name": "代理记账", "path": "/trading/glyAccount"},

          ]
        },
        {
          "name": "个体户中心",
          "icon": "iconfont icon-gth-gsgetihuzhongxin",
          "team": [
            {
              "name": "个体户",
              "path": "/trading/userAll"
            }
          ]
        }
      ];
    }
  }

  getInvoiceMenu(loginUser) {
    if (!loginUser) {
      return [];
    }
    if (loginUser.isManager) {
      return [
        {
          name: "数据概览",
          icon: "iconfont icon-gth-gsshujugailan",
          team: [{name: "业务数据汇总", path: "/home"}]
        },
        {
          name: "发票中心",
          icon: "iconfont icon-gth-gsfapiaozhongxin",
          team: [
            {name: "发票申请", path: "/trading/invoiceApplyFor"},
            {name: "发票办理", path: "/trading/invoiceManagement"},
            {name: "我的发票业务", path: "/trading/invoiceApplyMy"},
          ]
        }
      ];
    }else{
      return [
        {
          name: "数据概览",
          icon: "iconfont icon-gth-gsshujugailan",
          team: [{name: "业务数据汇总", path: "/home"}]
        },
        {
          name: "发票中心",
          icon: "iconfont icon-gth-gsfapiaozhongxin",
          team: [
            {name: "发票办理", path: "/trading/invoiceManagement"},
            {name: "我的发票业务", path: "/trading/invoiceApplyMy"},
          ]
        }
      ];
    }
    
  }

  /**
   *   添加
   * @param {*} params
   */
  async addUser(params, pobj2, req) {
    try {
      var user = {
        saas_id: params.saas_id,
        org_id: Number(params.org_id || 0),
        ucname: this.trim(params.ucname),
        password: this.trim(params.password),
        uctype: '3',
        uctypeId: this.trim(params.deliverId),
        mobile: this.trim(params.mobile),
        realName: this.trim(params.realName),
        roles: params.roles || [],
      };
      if (!user.ucname) {
        return system.getResult(null, "请填写用户名");
      }
      if (!user.password) {
        return system.getResult(null, "请填写密码");
      }
      if (!user.mobile) {
        return system.getResult(null, "请填写手机号");
      }
      if (!user.realName) {
        return system.getResult(null, "请填写姓名");
      }

      if (user.uctype != 1) {
        user.org_id = null;
        user.roles = [];
      }
      return await this.userSve.addUser(user);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   *   更新
   * @param {*} params
   */
  async updUser(params, pobj2, req) {
    var user = {
      id: Number(params.id || 0),
      saas_id: params.saas_id,
      org_id: Number(params.org_id || 0),
      uctype: '3',
      uctypeId: this.trim(params.deliverId),
      mobile: this.trim(params.mobile),
      realName: this.trim(params.realName),
      roles: params.roles || [],
    };

    if (!user.id) {
      return system.getResult(null, "用户不存在");
    }

    if (!user.mobile) {
      return system.getResult(null, "请填写手机号");
    }

    if (!user.realName) {
      return system.getResult(null, "请填写姓名");
    }

    if (user.uctype != 1) {
      user.org_id = null;
      user.roles = [];
    }

    try {
      return await this.userSve.updUser(user);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async currentUser(qobj, pobj, req) {
    return system.getResultSuccess(req.loginUser);
  }

  /**
   * 启用禁用
   * @param {*} params
   * @param {*} pobj2
   * @param {*} req
   */
  async enabled(params, pobj2, req) {
    try {
      params.id = Number(params.id || 0);
      params.enabled = Number(params.enabled || 0);
      return await this.userSve.enabled(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async delUser(params, pobj2, req) {
    try {
      return await this.userSve.delUser(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   *   查询明细
   * @param {*} params
   */
  async queryById(params, pobj2, req) {
    try {
      return await this.userSve.queryById(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async updPassword(params, pobj2, req) {
    params.password = this.trim(params.password);
    if (!params.password) {
      return system.getResult(null, `请填写密码`);
    }

    try {
      return await this.userSve.updPassword(params);
    } catch (error) {
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  /**
   * 根据pid查出子目录
   * @param {*} params
   */
  async page(params, pobj2, req) {
    try {
      params.uctypeId = params.deliver_id;
      return await this.userSve.page(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }

  async salesmanList(params, pobj2, req) {
    try {
      if (!params.deliver_id) {
        return system.getResultSuccess([]);
      }
      return await this.userSve.salesmanList(params);
    } catch (error) {
      console.log(error);
      return system.getResult(null, `系统错误 错误信息 ${error}`);
    }
  }
}

module.exports = UserCtl;