const system = require("../../../system");
const ServiceBase = require("../../sve.base")
const settings = require("../../../../config/settings")
class MerchantService extends ServiceBase {
  constructor() {
    super("merchant", ServiceBase.getDaoName(MerchantService));
    this.merchantaccountDao = system.getObject("db.merchant.merchantaccountDao");

    this.merchanttitleDao = system.getObject("db.merchant.merchanttitleDao");

    this.merchantaddressDao = system.getObject("db.merchant.merchantaddressDao");

    this.merchantrechargeDao = system.getObject("db.merchant.merchantrechargeDao");
  }
  //查询商户
  async apiGetMerchant(params) {
    try {
       return await this.getById(params.id, params.options);
    } catch (error) {
      console.log(error)
      return system.getResult(null, "接口异常");
    }
  }

  async apiGetMerchantMap(params) {
    try {
      var map = await this.dao.findMapByIds(params.ids, params.attrs);
      return system.getResultSuccess(map);
    } catch (error) {
      console.log(error)
      return system.getResult(null, "接口异常");
    }
  }

  async apiAddMerchant(merchant) {
    try {
      merchant.orderPrice = merchant.orderPrice || 0;
      merchant.ucname = "";
      merchant.ucid = "";
      merchant.appSecret = await this.getUidInfo(32);

      return await this.addMerchant(merchant);
    } catch (error) {
      console.log(error)
      return system.getResult(null, "接口异常");
    }
  }

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

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

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

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

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

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

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

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

  async secretById(params) {
    var merchant = await this.dao.getById(params.id, "id, appSecret")
    return system.getResultSuccess(merchant);
  }

  async nameList() {
    var nameList = await this.dao.nameList();
    return system.getResultSuccess(nameList);
  }
  
  async infoPage(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    if (params.merchantId) {
      where.id = params.merchantId;
    }

    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd, true);

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

    var attributes = ["id", "name", "taxType", "contactName", "contactMobile", "contactEmail",
      "invoiceValid", "mustPay", "orderPrice", "ownerName", "ownerMobile", "status", "created_at"
    ];

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

  async addMerchant(merchant) {
    var name = this.trim(merchant.name);
    if (!name) {
      return system.getResult(null, "请填写商户名称");
    }

    var isExist = await this.dao.findOne({
      name: name
    });
    if (isExist) {
      return system.getResult(null, "商户名称【" + name + "】已存在");
    }

    var title = merchant.title;
    var address = merchant.address;

    title.isDefault = true;
    address.isDefault = true;
    merchant.status = "00";

    var self = this;
    merchant = await self.db.transaction(async function (t) {
      // 创建商户
      merchant = await self.dao.create(merchant, t);

      // 商户id赋值
      title.merchant_id = merchant.id;
      address.merchant_id = merchant.id;

      // 创建账户
      var account = await self.merchantaccountDao.create({
        merchant_id: merchant.id,
        channel_id: "1",
        banlance: 0
      }, t);

      // 创建抬头
      title = await self.merchanttitleDao.create(title, t);

      // 创建收件地址
      address = await self.merchantaddressDao.create(address, t);

      merchant.accountList = [account];
      merchant.titleList = [title];
      merchant.addressList = [merchant.addressList];
      return merchant;
    });

    return system.getResultSuccess();
  }

  async updMerchant(params) {
    var id = this.trim(params.id);

    var merchant = await this.dao.findById(id);
    if (!merchant) {
      return system.getResult(null, "商户不存在");
    }

    var name = this.trim(params.name);
    if (!name) {
      return system.getResult(null, "请填写商户名称");
    }

    var isExist = await this.dao.findOne({
      name: name
    });
    if (isExist && isExist.id != id) {
      return system.getResult(null, "商户名称【" + name + "】已存在");
    }

    merchant.name = name;
    merchant.taxType = this.trim(params.taxType);
    merchant.contactName = this.trim(params.contactName);
    merchant.contactMobile = this.trim(params.contactMobile);
    merchant.contactEmail = this.trim(params.contactEmail);
    merchant.invoiceValid = params.invoiceValid ? true : false;
    merchant.mustPay = params.mustPay ? true : false;
    merchant.ownerName = this.trim(params.ownerName);
    merchant.ownerMobile = this.trim(params.ownerMobile);
    merchant.ownerId = this.trim(params.ownerId);
    merchant.ownerPath = this.trim(params.ownerPath);

    await merchant.save();
    return system.getResultSuccess();
  }

  async auditMerchant(params) {
    var id = this.trim(params.id);

    var merchant = await this.dao.findById(id);
    if (!merchant) {
      return system.getResult(null, "商户不存在");
    }

    merchant.status = "10";
    merchant.ucname = params.ucname;
    merchant.ucid = params.ucid;

    await merchant.save();
    return system.getResultSuccess(merchant);
  }

  async getById(id, options) {
    options = options || {};
    var merchant = await this.dao.getById(id);
    if (merchant) {
      await this.dao.setRowCodeName(merchant, "status");
      await this.dao.setRowCodeName(merchant, "taxType");
      this.handleDate(merchant, ["created_at", "updated_at"], null, -8);

      if(options.title) {
        merchant.titleList = await this.merchanttitleDao.listByMerchantId(id);
      }

      if(options.address) {
        merchant.addressList =  await this.merchantaddressDao.listByMerchantId(id);
      }
    }
    return system.getResultSuccess(merchant);
  }

  
  /**
   * 查询商户信息 queryMerchant
   * @param {*} params 查询条件{appid:XXX}
   */
  async queryMerchant(id, options) {
    //此处id没有获取到
    let include=[];
    if(options.title){
      include.push({
        association:this.dao.model.hasMany(this.merchanttitleDao.model,{
          foreignKey:'merchant_id',targetKey:'id'
        }),
        required:false,
        attributes:['titleNo','taxNo','invoiceAddr','invoiceMobile','accountName','accountPublic']
      });
    }
    if(options.address){
      include.push({
        association:this.dao.model.hasMany(this.merchantaddressDao.model,{
          foreignKey:'merchant_id',targetKey:'id'
        }),
        required:false,
        attributes:['addressNo','mailAddr','mailTo','mailMobile']
      });
    };
    let opt = {
      where: {
        id: id||"11064624194480427"
      },
      include,
      attributes: [
        `name`,
        `taxType`,
        `contactName`,
        `contactEmail`,
        `contactMobile`,
        `invoiceValid`,
        `mustPay`,
        `status`,
        `ownerName`,
        `ownerMobile`,
        `created_at`
      ],
      raw: false
    };
    try {
      var item = await this.dao.model.findOne(opt);
      if (item) {
        return system.getResultSuccess(item);
      }else{
        return system.getResult(null, "没有查询到相关数据");
      }
    } catch (error) {
      return system.getResult(null, "没有查询到相关数据");
    }
  }

  async pageByCondition(params) {
    var currentPage = Number(params.currentPage || 0);
    var pageSize = Number(params.pageSize || 10);

    var where = {};

    if (params.name) {
      where.name = {
        [this.db.Op.like]: "%" + params.name + "%"
      };
    }

    if (params.merchantId) {
      where.id = params.merchantId;
    }

    if (params.owner_name) {
      where.owner_name = {
        [this.db.Op.like]: "%" + params.owner_name + "%"
      };
    }
    this.addWhereTime(where, 'created_at', params.createdBegin, params.createdEnd, true);

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

    var attributes = ["id", "name", "taxType", "contactName", "contactMobile", "contactEmail",
      "taxNo", "invoiceAddr", "invoiceMobile", "accountName", "accountPublic",
      "mailAddr", "mailTo", "mailMobile", "status",
      "ownerName", "ownerMobile", "created_at"
    ];

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

  //操作平台--------------------------start
  async createUser(userName, mobile, password) {
    var param = {
      app_id: req.app.id,
      userName: userName,
      mobile: mobile,
      password: password || settings.defaultPassWord
    }
    var registerUrl = settings.paasUrl() + "api/auth/accessAuth/register";
  }
  //操作平台--------------------------end
}
module.exports = MerchantService;
// var task=new UserService();
// task.getUserStatisticGroupByApp().then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });