import { Build, Component, Event, h, Listen, Prop, State, } from "@stencil/core";
export class ModalPayCalculator {
  constructor() {
    this.colors = ["#3e95cd", "#8e5ea2", "#3cba9f", "#e8c3b9", "#c45850"];
    this.payModels = [];
    this.amount = 0;
    this.disableAmount = false;
    this.disableReferral = false;
    this.hasReferral = false;
    this.payables = [];
    this.totalPercentage = 0;
  }
  onChange(event) {
    var _a;
    if (event.target.name === "payModelId") {
      this.payModelId = (_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value;
      this.selectedPayModel = this.payModels.find((payModel) => payModel.id === this.payModelId);
      console.log(event, this.payModels, this.selectedPayModel);
    }
    else if (event.target.name === "received") {
      this.amount = event.target.value;
    }
    else if (event.target.name === "referral") {
      this.hasReferral = event.target.checked;
    }
    this.calculatePayables();
  }
  onSuccess(event) {
    var _a, _b, _c, _d, _e, _f;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint) === "findJob") {
      this.hasReferral = !!((_c = (_b = this.job) === null || _b === void 0 ? void 0 : _b.referral) === null || _c === void 0 ? void 0 : _c.id);
    }
    else if (((_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.endpoint) === "listPayModels") {
      this.payModels = ((_f = (_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.payModels)
        ? event.detail.data.payModels
        : [];
      if (this.payModelId) {
        this.selectedPayModel = this.payModels.find((payModel) => payModel.id === this.payModelId);
        console.log(this.selectedPayModel);
        this.calculatePayables();
      }
    }
  }
  onReset() {
    this.floodteamCloseModal.emit({});
  }
  onSubmit() {
    this.floodteamCloseModal.emit({});
  }
  formatUSD(amount) {
    const formatter = new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 2,
    });
    return formatter.format(amount ? amount : 0);
  }
  calculatePayables() {
    if (!this.selectedPayModel)
      return;
    let totalPercentage = 0;
    this.payables = this.selectedPayModel.payouts.map((payout, index) => {
      var _a;
      const percentage = this.hasReferral && ((_a = payout === null || payout === void 0 ? void 0 : payout.percentages) === null || _a === void 0 ? void 0 : _a.hasReferral)
        ? payout.percentages.hasReferral
        : payout.percentages.default;
      totalPercentage += percentage;
      return {
        percentage,
        role: payout === null || payout === void 0 ? void 0 : payout.role,
        amount: percentage * this.amount,
        color: this.mixColor(this.colors, index),
      };
    });
    this.totalPercentage = totalPercentage;
  }
  shadeColor(col, amt) {
    let usePound = false;
    if (col[0] === "#") {
      col = col.slice(1);
      usePound = true;
    }
    const num = parseInt(col, 16);
    let r = (num >> 16) + amt;
    if (r > 255) {
      r = 255;
    }
    else if (r < 0) {
      r = 0;
    }
    let b = ((num >> 8) & 0x00ff) + amt;
    if (b > 255) {
      b = 255;
    }
    else if (b < 0) {
      b = 0;
    }
    let g = (num & 0x0000ff) + amt;
    if (g > 255) {
      g = 255;
    }
    else if (g < 0) {
      g = 0;
    }
    return (usePound ? "#" : "") + (g | (b << 8) | (r << 16)).toString(16);
  }
  mixColor(colorPallet, index) {
    if (colorPallet[index]) {
      return colorPallet[index];
    }
    else {
      const goesInto = Math.floor(index / colorPallet.length);
      const darkenPercent = goesInto * 30;
      const colorIndex = index - goesInto * colorPallet.length;
      return this.shadeColor(colorPallet[colorIndex], darkenPercent);
    }
  }
  async fetchData() {
    this.fireenjinFetch.emit({
      endpoint: "findJob",
      params: {
        id: this.jobId,
        withPayments: true,
        withUsers: true,
        withSites: false,
        withPayModel: true,
        withPhotos: true,
        withPayables: false,
        withReadings: false,
      },
    });
  }
  componentDidLoad() {
    var _a;
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    if (((_a = this.payModels) === null || _a === void 0 ? void 0 : _a.length) && this.payModelId) {
      this.selectedPayModel = this.payModels[this.payModelId];
      setTimeout(() => {
        this.calculatePayables();
      }, 200);
    }
    if (this.jobId) {
      this.fetchData;
    }
  }
  render() {
    return (h("ion-content", { class: "ion-padding" },
      h("fireenjin-form", { submitButton: "Approve Payables", endpoint: "generatePayables" },
        h("ion-grid", null,
          h("ion-row", null,
            h("ion-col", { size: "12", sizeMd: "7" },
              h("ion-grid", null,
                h("ion-row", null,
                  h("ion-col", null,
                    h("fireenjin-input", { disabled: !!this.disableAmount, name: "received", label: "Amount Received", type: "tel", value: this.amount })),
                  h("ion-col", null,
                    h("fireenjin-select", { label: "Pay Model", name: "payModelId", endpoint: "listPayModels", resultsKey: "payModels", limit: 100, value: this.payModelId })),
                  h("ion-col", null,
                    h("ion-item", null,
                      h("ion-label", null, "Has Referral"),
                      h("ion-toggle", { name: "referral", disabled: this.disableReferral, checked: this.hasReferral }))),
                  h("ion-col", { class: "graph-col" },
                    h("fireenjin-graph", { type: "pie", datasets: [
                        {
                          backgroundColor: this.payables.map((payable) => payable.color),
                          data: this.payables.map((payable) => payable.amount),
                        },
                      ] }))))),
            h("ion-col", { size: "12", sizeMd: "5" },
              h("ion-list", null, this.payables.map((payable) => {
                var _a;
                return (h("ion-item", null,
                  h("ion-label", null,
                    h("h2", null, ((_a = payable === null || payable === void 0 ? void 0 : payable.role) === null || _a === void 0 ? void 0 : _a.name)
                      ? payable.role.name
                      : "No Role Name..."),
                    h("p", { style: {
                        color: payable.color,
                      } },
                      h("b", null, this.formatUSD(payable.amount)),
                      " @",
                      " ",
                      payable.percentage * 100,
                      " %")),
                  h("ion-badge", { color: "success" })));
              }))))))));
  }
  static get is() { return "modal-pay-calculator"; }
  static get originalStyleUrls() { return {
    "$": ["modal-pay-calculator.css"]
  }; }
  static get styleUrls() { return {
    "$": ["modal-pay-calculator.css"]
  }; }
  static get properties() { return {
    "job": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Job",
        "resolved": "{ __typename?: \"Job\"; address?: Address; afterhours?: boolean; amountBilled?: number; amountDeducted?: number; amountOwed?: number; amountPaid?: number; appointment?: Appointment; appointments?: Appointment[]; attributionToken?: Token; category?: number; cause?: string; claimNumber?: string; createdAt?: string; createdBy?: User; customer?: User; dateOfLoss?: string; efileCount?: number; efiles?: Efile[]; feed?: Feed[]; id?: string; invoices?: Invoice[]; isFranchise?: boolean; isInsured?: boolean; isSearchable?: boolean; lastNotifiedAt?: string; location?: Location; manager?: User; matterportModelId?: string; payModel?: PayModel; payables?: Payable[]; payments?: Payment[]; phone?: string; photos?: Photo[]; picture?: string; propertyAge?: number; ratings?: Rating[]; readings?: Reading[]; referral?: User; serviceStillNeeded?: string; services?: ScopeService[]; sites?: Site[]; status?: string; success?: User; tags?: string[]; title?: string; type?: string; updatedAt?: string; updatedBy?: User; userIds?: string[]; users?: User[]; weather?: Weather[]; weatherIds?: string[]; }",
        "references": {
          "Job": {
            "location": "import",
            "path": "../../../sdk"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "amount": {
      "type": "number",
      "mutable": false,
      "complexType": {
        "original": "number",
        "resolved": "number",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "amount",
      "reflect": false,
      "defaultValue": "0"
    },
    "disableAmount": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "disable-amount",
      "reflect": false,
      "defaultValue": "false"
    },
    "disableReferral": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "disable-referral",
      "reflect": false,
      "defaultValue": "false"
    },
    "hasReferral": {
      "type": "boolean",
      "mutable": true,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "has-referral",
      "reflect": false,
      "defaultValue": "false"
    },
    "jobId": {
      "type": "string",
      "mutable": false,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "job-id",
      "reflect": false
    },
    "payModelId": {
      "type": "string",
      "mutable": true,
      "complexType": {
        "original": "string",
        "resolved": "string",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "pay-model-id",
      "reflect": false
    }
  }; }
  static get states() { return {
    "payables": {},
    "selectedPayModel": {},
    "totalPercentage": {}
  }; }
  static get events() { return [{
      "method": "floodteamCloseModal",
      "name": "floodteamCloseModal",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }, {
      "method": "fireenjinFetch",
      "name": "fireenjinFetch",
      "bubbles": true,
      "cancelable": true,
      "composed": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "complexType": {
        "original": "any",
        "resolved": "any",
        "references": {}
      }
    }]; }
  static get listeners() { return [{
      "name": "ionChange",
      "method": "onChange",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinSuccess",
      "method": "onSuccess",
      "target": "body",
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinReset",
      "method": "onReset",
      "target": undefined,
      "capture": false,
      "passive": false
    }, {
      "name": "fireenjinSubmit",
      "method": "onSubmit",
      "target": undefined,
      "capture": false,
      "passive": false
    }]; }
}
