import { h, Build, } from "@stencil/core";
import { menuController, modalController, popoverController, toastController, } from "@ionic/core";
import state from "../../../store";
import getJobFromCache from "../../../helpers/getJobFromCache";
import isAdmin from "../../../helpers/auth/isAdmin";
export class AppJob {
  constructor() {
    this.userRoleMap = {};
    this.jobId = undefined;
    this.showingEfileHistory = [];
    this.efiles = undefined;
    this.isUploading = false;
    this.efileLoading = false;
    this.isSending = false;
    this.template = undefined;
    this.dots = undefined;
    this.activityFeed = [];
    this.isSiteModalOpen = false;
    this.isEndOfFeed = false;
    this.payModels = [];
    this.feedLimit = 10;
    this.siteId = undefined;
    this.currentSlide = 0;
    this.showControls = null;
    this.sidebarContentEl = undefined;
    this.isUploadingPhoto = false;
    this.activityFeedEl = undefined;
    this.selectedReadingDate = undefined;
    this.readingsView = "readings";
    this.selectedImage = undefined;
    this.preparingEfiles = [];
    this.efileTemplateId = [];
  }
  async onSlideChange(event) {
    this.currentSlide =
      (await event.target.getActiveIndex()) + 1;
  }
  async onSuccess(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2;
    if (event.detail.endpoint === "upload") {
      this.isUploadingPhoto = false;
    }
    else if (event.detail.endpoint === "addEfile") {
      this.isUploading = false;
    }
    else if (event.detail.endpoint === "editJob") {
      this.modalEl.dismiss();
    }
    else if (event.detail.endpoint === "addUserToJob") {
      this.modalEl.dismiss();
    }
    else if (event.detail.endpoint === "addEfile") {
      this.isUploading = false;
    }
    else if (event.detail.endpoint === "deleteDot") {
      this.modalEl.dismiss();
      this.fetchDots();
    }
    else if (["sendTemplateEmail", "editJob", "addUserToJob"].includes((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.endpoint)) {
      if ((_b = this.modalEl) === null || _b === void 0 ? void 0 : _b.dismiss)
        this.modalEl.dismiss();
    }
    else if (event.detail.endpoint === "addNote") {
      const paginationEl = this.activityFeedEl.querySelector("fireenjin-pagination");
      if (paginationEl) {
        setTimeout(() => {
          paginationEl.getResults();
        }, 2000);
      }
    }
    else if (event.detail.endpoint === "findJob" &&
      ((_e = (_d = (_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.job) === null || _e === void 0 ? void 0 : _e.id) === this.jobId) {
      this.userRoleMap = {};
      if ((_g = (_f = state === null || state === void 0 ? void 0 : state.job) === null || _f === void 0 ? void 0 : _f.customer) === null || _g === void 0 ? void 0 : _g.id)
        this.userRoleMap[(_h = state.job) === null || _h === void 0 ? void 0 : _h.customer.id] = "customer";
      if ((_k = (_j = state === null || state === void 0 ? void 0 : state.job) === null || _j === void 0 ? void 0 : _j.cosigner) === null || _k === void 0 ? void 0 : _k.id)
        this.userRoleMap[(_l = state.job) === null || _l === void 0 ? void 0 : _l.cosigner.id] = "cosigner";
      if ((_o = (_m = state === null || state === void 0 ? void 0 : state.job) === null || _m === void 0 ? void 0 : _m.manager) === null || _o === void 0 ? void 0 : _o.id)
        this.userRoleMap[(_p = state.job) === null || _p === void 0 ? void 0 : _p.manager.id] = "manager";
      if ((_r = (_q = state === null || state === void 0 ? void 0 : state.job) === null || _q === void 0 ? void 0 : _q.referral) === null || _r === void 0 ? void 0 : _r.id)
        this.userRoleMap[state.job.referral.id] = "referral";
      if ((_t = (_s = state === null || state === void 0 ? void 0 : state.job) === null || _s === void 0 ? void 0 : _s.success) === null || _t === void 0 ? void 0 : _t.id)
        this.userRoleMap[state.job.success.id] = "success";
      this.userRoleMap = { ...this.userRoleMap };
      const efiles = [];
      for (const efile of ((_u = state === null || state === void 0 ? void 0 : state.job) === null || _u === void 0 ? void 0 : _u.efiles) || []) {
        const existingFileIndex = efiles.findIndex((file) => { var _a, _b; return ((_a = file === null || file === void 0 ? void 0 : file.template) === null || _a === void 0 ? void 0 : _a.id) === ((_b = efile === null || efile === void 0 ? void 0 : efile.template) === null || _b === void 0 ? void 0 : _b.id); });
        if (existingFileIndex >= 0) {
          efiles[existingFileIndex].history.push(efile);
        }
        else {
          efiles.push({ ...efile, history: [] });
        }
      }
      this.efiles = efiles;
      setTimeout(() => {
        var _a, _b, _c;
        this.selectedReadingDate = ((_b = (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.readings) === null || _b === void 0 ? void 0 : _b.length)
          ? (_c = state.job) === null || _c === void 0 ? void 0 : _c.readings[0].name
          : null;
        this.readingsGraphData();
      }, 1000);
    }
    else if (((_v = event === null || event === void 0 ? void 0 : event.detail) === null || _v === void 0 ? void 0 : _v.endpoint) === "generatePdf") {
      const toast = await toastController.create({
        message: "File has been added to Efile.",
        duration: 3000,
      });
      toast.present();
      this.efileLoading = false;
    }
    else if (((_w = event === null || event === void 0 ? void 0 : event.detail) === null || _w === void 0 ? void 0 : _w.endpoint) === "listPayModels") {
      this.payModels = ((_z = (_y = (_x = event === null || event === void 0 ? void 0 : event.detail) === null || _x === void 0 ? void 0 : _x.data) === null || _y === void 0 ? void 0 : _y.listPayModels) === null || _z === void 0 ? void 0 : _z.payModels) || [];
    }
    else if (((_0 = event === null || event === void 0 ? void 0 : event.detail) === null || _0 === void 0 ? void 0 : _0.endpoint) === "listDots") {
      this.dots = ((_2 = (_1 = event === null || event === void 0 ? void 0 : event.detail) === null || _1 === void 0 ? void 0 : _1.data) === null || _2 === void 0 ? void 0 : _2.dots) || [];
    }
  }
  async onSlideTap(_event) {
    this.openSiteEditModal();
  }
  onCloseModa() {
    this.isSiteModalOpen = false;
  }
  async openReadingModal(event) {
    var _a, _b, _c, _d, _e, _f;
    if (!["addReading", "addDot"].includes((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.name))
      return;
    const modalEl = await modalController.create({
      component: "modal-take-readings",
      componentProps: {
        jobId: (_b = state === null || state === void 0 ? void 0 : state.job) === null || _b === void 0 ? void 0 : _b.id,
        zip: (_d = (_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.address) === null || _d === void 0 ? void 0 : _d.zip,
        dotForm: ((_e = event === null || event === void 0 ? void 0 : event.detail) === null || _e === void 0 ? void 0 : _e.name) === "addDot",
        closeOnFinish: ((_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.name) === "addDot",
      },
    });
    await modalEl.present();
  }
  onOpenSiteEditModal(event) {
    this.openSiteEditModal(event.detail.site, {
      selectedTab: event.detail.selectedTab,
    });
  }
  onSelect(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    if (((_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.name) === "readingId" && !((_b = this.modalEl) === null || _b === void 0 ? void 0 : _b.isConnected)) {
      if ((_c = event === null || event === void 0 ? void 0 : event.detail) === null || _c === void 0 ? void 0 : _c.reading) {
        console.log((_e = (_d = event === null || event === void 0 ? void 0 : event.detail) === null || _d === void 0 ? void 0 : _d.reading) === null || _e === void 0 ? void 0 : _e.name);
        this.selectedReadingDate = (_g = (_f = event === null || event === void 0 ? void 0 : event.detail) === null || _f === void 0 ? void 0 : _f.reading) === null || _g === void 0 ? void 0 : _g.name;
      }
      else {
        this.openReadingModal();
      }
      this.popoverEl.dismiss();
    }
    else if (((_h = event === null || event === void 0 ? void 0 : event.detail) === null || _h === void 0 ? void 0 : _h.name) === "user" && ((_k = (_j = event === null || event === void 0 ? void 0 : event.detail) === null || _j === void 0 ? void 0 : _j.user) === null || _k === void 0 ? void 0 : _k.id)) {
      this.sendEmail(event, (_m = (_l = event === null || event === void 0 ? void 0 : event.detail) === null || _l === void 0 ? void 0 : _l.user) === null || _m === void 0 ? void 0 : _m.id);
      this.popoverEl.dismiss();
    }
  }
  onChange(event) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j;
    console.log(event);
    if (((_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.name) === "readingsView") {
      this.readingsView = event.target.value;
      this.readingsGraphData();
    }
    if ((_d = (_c = (_b = event === null || event === void 0 ? void 0 : event.target) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.includes) === null || _d === void 0 ? void 0 : _d.call(_c, "efile-")) {
      const efileUrl = (_f = (_e = event === null || event === void 0 ? void 0 : event.target) === null || _e === void 0 ? void 0 : _e.value) === null || _f === void 0 ? void 0 : _f.url;
      const efileTemplateId = (_j = (_h = (_g = event === null || event === void 0 ? void 0 : event.target) === null || _g === void 0 ? void 0 : _g.value) === null || _h === void 0 ? void 0 : _h.template) === null || _j === void 0 ? void 0 : _j.id;
      this.efileTemplateId = this.efileTemplateId.includes(efileTemplateId)
        ? this.efileTemplateId.filter((id) => efileTemplateId !== id)
        : [...new Set([...this.efileTemplateId, efileTemplateId])];
      this.preparingEfiles = this.preparingEfiles.includes(efileUrl)
        ? this.preparingEfiles.filter((url) => efileUrl !== url)
        : [...new Set([...this.preparingEfiles, efileUrl])];
    }
  }
  async removeEfileFromJob(efile) {
    if (confirm(`Are you sure you want to remove this file from the job?`)) {
      this.fireenjinSubmit.emit({
        endpoint: "deleteEfile",
        id: efile.id,
      });
    }
    if (this.efileListEl)
      this.efileListEl.closeSlidingItems();
  }
  async openMatterportModal() {
    var _a, _b;
    this.modalEl = await modalController.create({
      component: "modal-matterport",
      cssClass: "modal-matterport",
      backdropDismiss: false,
      componentProps: {
        jobId: (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.id,
        modelId: (_b = state === null || state === void 0 ? void 0 : state.job) === null || _b === void 0 ? void 0 : _b.matterportModelId,
      },
    });
    this.modalEl.present();
  }
  async openSiteEditModal(site, options) {
    var _a, _b, _c;
    state.site = site;
    if (this.isSiteModalOpen)
      return;
    this.modalEl = await modalController.create({
      component: "modal-site-edit",
      cssClass: "modal-site-edit",
      backdropDismiss: false,
      componentProps: {
        site,
        jobId: (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.id,
        siteId: ((_b = state === null || state === void 0 ? void 0 : state.site) === null || _b === void 0 ? void 0 : _b.id) || null,
        sites: (options === null || options === void 0 ? void 0 : options.sites) || ((_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.sites) || [],
        dots: this.dots,
        currentSlide: (options === null || options === void 0 ? void 0 : options.currentSlide) ? options.currentSlide : null,
        viewGallery: typeof (options === null || options === void 0 ? void 0 : options.viewGallery) === "boolean"
          ? !!(options === null || options === void 0 ? void 0 : options.viewGallery)
          : true,
        showProgress: !!(options === null || options === void 0 ? void 0 : options.showProgress),
        selectedTab: (options === null || options === void 0 ? void 0 : options.selectedTab) ? options.selectedTab : null,
        photo: (options === null || options === void 0 ? void 0 : options.photo) ? options.photo : null,
        photoUploading: !!(options === null || options === void 0 ? void 0 : options.photoUploading),
      },
    });
    this.modalEl.present();
    this.isSiteModalOpen = true;
    console.log(site === null || site === void 0 ? void 0 : site.name, site === null || site === void 0 ? void 0 : site.id);
  }
  async openReadingSelect(event) {
    var _a, _b;
    this.popoverEl = await popoverController.create({
      component: "popover-reading-select",
      componentProps: {
        readings: ((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.readings)
          ? Object.values((_b = state.job) === null || _b === void 0 ? void 0 : _b.readings)
          : [],
      },
      event,
    });
    return this.popoverEl.present();
  }
  // async removeUserFromJob( user: User) {
  //   if (
  //     confirm(
  //       `Are you sure you want to remove ${
  //         user?.firstName ? user.firstName : "this user"
  //       } from the job?`
  //     )
  //   )
  //     this.fireenjinSubmit.emit({
  //       endpoint: "removeUserFromJob",
  //       data: {
  //         jobId: state?.job?.id,
  //         userId: user.id,
  //       },
  //     });
  //   if (this.userListEl) this.userListEl.closeSlidingItems();
  // }
  async openaddReadingPopover(event) {
    this.popoverEl = await popoverController.create({
      event,
      cssClass: "popover-add-reading",
      component: "popover-add-reading",
      componentProps: {
        job: state.job,
      },
    });
    this.popoverEl.present();
  }
  async openUserSelect(event) {
    var _a;
    this.popoverEl = await popoverController.create({
      event,
      cssClass: "popover-user-select",
      component: "popover-user-select",
      componentProps: {
        jobId: this.jobId,
        users: ((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.users) || [],
      },
    });
    this.popoverEl.present();
  }
  async openUserSearch() {
    this.modalEl = await modalController.create({
      cssClass: "modal-search-users",
      component: "modal-search-users",
      componentProps: {
        job: state.job,
      },
    });
    this.modalEl.present();
  }
  readingsGraphData() {
    var _a, _b, _c;
    const graphData = [];
    if (this.readingsView === "temperature") {
      graphData.push({
        data: (((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.readings) ? (_b = state.job) === null || _b === void 0 ? void 0 : _b.readings.reverse() : []).map((reading) => { var _a; return ((_a = reading === null || reading === void 0 ? void 0 : reading.weather) === null || _a === void 0 ? void 0 : _a.temperature) ? reading.weather.temperature : 0; }),
      });
    }
    const dotReadings = {};
    for (const reading of ((_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.readings) || []) {
      for (const site of (reading === null || reading === void 0 ? void 0 : reading.sites) || []) {
        for (const dot of (site === null || site === void 0 ? void 0 : site.dots) || []) {
          if (!dotReadings[dot === null || dot === void 0 ? void 0 : dot.id])
            dotReadings[dot === null || dot === void 0 ? void 0 : dot.id] = [];
          dotReadings[dot === null || dot === void 0 ? void 0 : dot.id].push(dot === null || dot === void 0 ? void 0 : dot.moistureContent);
        }
      }
    }
    for (const [dotId, readings] of Object.entries(dotReadings)) {
      if (!dotId || !(readings === null || readings === void 0 ? void 0 : readings.length))
        continue;
      graphData.push({
        data: readings.map((reading) => (reading === null || reading === void 0 ? void 0 : reading[this.readingsView]) || 0),
      });
    }
    return graphData;
  }
  async openFileUpload(event) {
    console.log(event);
  }
  async openMenu() {
    menuController.open();
  }
  async openJobEdit(step) {
    this.modalEl = await modalController.create({
      component: "modal-job-edit",
      cssClass: "modal-edit-job",
      backdropDismiss: false,
      componentProps: {
        step,
        job: state.job,
        payModels: this.payModels,
      },
    });
    this.modalEl.present();
  }
  async openSendEfileModal(event) {
    var _a;
    event.preventDefault();
    event.stopPropagation();
    this.modalEl = await modalController.create({
      component: "modal-send-email",
      cssClass: "modal-send-email",
      backdropDismiss: false,
      componentProps: {
        templateId: "0xtJNtGRrT3GIosbN7iP",
        job: state.job,
        ccs: this.efileTemplateId.includes("LuqgyLwV2uMNJ362bH8l") &&
          this.efileTemplateId.includes("beLtN4HFStll5UgL9NaZ")
          ? ["claims@thefloodteam.com"]
          : [],
        templateFilter: (template) => { var _a, _b; return !(template === null || template === void 0 ? void 0 : template.partial) && ((_b = (_a = template === null || template === void 0 ? void 0 : template.tags) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, "job")); },
        attachments: this.preparingEfiles,
        payload: this.efileTemplateId,
        users: ((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.users) || [],
      },
    });
    this.modalEl.present();
  }
  async openEsignModal(event, templateId, userSignId, efileId) {
    event.preventDefault();
    event.stopPropagation();
    this.modalEl = await modalController.create({
      component: "modal-esign",
      cssClass: "modal-esign",
      backdropDismiss: false,
      componentProps: {
        jobId: this.jobId,
        job: state.job,
        templateId,
        userSignId,
        efileId,
      },
    });
    this.modalEl.present();
  }
  async fetchJob() {
    if (!this.jobId)
      return;
    this.fireenjinFetch.emit({
      endpoint: "findJob",
      cacheKey: "jobs",
      params: {
        id: this.jobId,
        withPayments: false,
        withUsers: true,
        withSites: true,
        withPayModel: true,
        withPhotos: true,
        withEfiles: true,
        withPayables: false,
        withReadings: true,
      },
    });
  }
  async fetchPayModels() {
    this.fireenjinFetch.emit({
      endpoint: "listPayModels",
      params: {
        data: {
          limit: 10,
        },
      },
    });
  }
  async fetchDots() {
    this.fireenjinFetch.emit({
      endpoint: "listDots",
    });
  }
  async generatePdf(templateId, filename = null) {
    var _a, _b;
    this.efileLoading = true;
    this.fireenjinSubmit.emit({
      endpoint: "generatePdf",
      data: {
        filename,
        jobId: this.jobId,
        templateId,
        invoiceType: ((_b = (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.serviceTypes) === null || _b === void 0 ? void 0 : _b[0]) || "water",
      },
    });
  }
  formatUSD(amount) {
    const formatter = new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: "USD",
      minimumFractionDigits: 2,
    });
    return formatter.format(amount ? amount : 0);
  }
  send(event, template) {
    event.preventDefault();
    event.stopPropagation();
    this.template = template;
    this.isSending = true;
    this.openUserSelect(event);
  }
  async sendEmail(event, userId) {
    var _a, _b, _c, _d, _e;
    event.preventDefault();
    event.stopPropagation();
    if (!((_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid))
      return;
    const data = {
      templateId: "ltEEAQ9Q1J7Jkn6wIIEH",
      userIds: [userId],
      ccs: [],
      data: {
        app: {
          url: Build.isBrowser ? window.location.origin : ".",
        },
        template: {
          id: ((_b = this.template) === null || _b === void 0 ? void 0 : _b.id) || null,
          description: ((_c = this.template) === null || _c === void 0 ? void 0 : _c.description) || null,
          subject: ((_d = this.template) === null || _d === void 0 ? void 0 : _d.description) || null,
          tags: ((_e = this.template) === null || _e === void 0 ? void 0 : _e.tags) || [],
        },
        job: JSON.parse(JSON.stringify(state.job)),
        userId,
      },
    };
    console.log(data, "email input");
    this.fireenjinSubmit.emit({
      endpoint: "sendTemplateEmail",
      data,
    });
  }
  getData() {
    this.fireenjinTrigger.emit({
      name: "subscribe",
      payload: {
        collection: "jobs",
        id: this.jobId,
        callback: () => {
          this.fetchJob();
          this.getActivityFeed();
        },
      },
    });
    this.fetchJob();
    this.fetchPayModels();
    this.fetchDots();
  }
  async componentWillLoad() {
    state.job = await getJobFromCache(this.jobId);
  }
  getActivityFeed() {
    var _a;
    console.log(state);
    state.feedFetchData = {
      myFeed: (_a = state === null || state === void 0 ? void 0 : state.session) === null || _a === void 0 ? void 0 : _a.uid,
      jobId: this.jobId,
    };
  }
  cleanNotionId(str) {
    return (str || "").replace(/-/g, "");
  }
  componentDidLoad() {
    if (!(Build === null || Build === void 0 ? void 0 : Build.isBrowser))
      return;
    this.getData();
  }
  disconnectedCallback() {
    this.fireenjinTrigger.emit({
      name: "unsubscribe",
      payload: {
        collection: "jobs",
        id: this.jobId,
      },
    });
  }
  render() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11;
    const contractEfileLookup = {};
    (((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.efiles) || []).map((efile) => {
      var _a;
      return (contractEfileLookup[(_a = efile === null || efile === void 0 ? void 0 : efile.template) === null || _a === void 0 ? void 0 : _a.id] = efile);
    });
    const roleUserLookup = {};
    (((_b = state === null || state === void 0 ? void 0 : state.job) === null || _b === void 0 ? void 0 : _b.users) || []).map((user) => {
      return (roleUserLookup[this.userRoleMap[user === null || user === void 0 ? void 0 : user.id]] = user);
    });
    return [
      h("ion-content", null, h("ion-grid", { style: {
          display: "block",
          maxWidth: "1200px",
          margin: "0 auto",
        } }, h("ion-row", null, h("ion-col", null, h("floodteam-title-bar", null, ((_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.title) || "???"))), h("ion-row", null, h("ion-col", { class: "ion-align-self-center" }, h("flooteam-chip-bar", null, h("ion-chip", null, h("ion-icon", { name: "calendar-outline", class: "ft-icon-style" }), h("ion-label", { class: "ion-text-capitalize" }, (_d = state === null || state === void 0 ? void 0 : state.job) === null || _d === void 0 ? void 0 : _d.createdAt)), h("floodteam-select-job-service-types", { jobId: this.jobId, value: ((_e = state === null || state === void 0 ? void 0 : state.job) === null || _e === void 0 ? void 0 : _e.serviceTypes) || [] }), h("floodteam-select-status", { jobId: this.jobId, value: (_f = state === null || state === void 0 ? void 0 : state.job) === null || _f === void 0 ? void 0 : _f.status }), ((_g = state === null || state === void 0 ? void 0 : state.job) === null || _g === void 0 ? void 0 : _g.status) === "lost" && (h("floodteam-select-lost-reason", { jobId: this.jobId, value: (_h = state === null || state === void 0 ? void 0 : state.job) === null || _h === void 0 ? void 0 : _h.lostReason })), h("floodteam-select-location", { jobId: this.jobId, value: (_k = (_j = state === null || state === void 0 ? void 0 : state.job) === null || _j === void 0 ? void 0 : _j.location) === null || _k === void 0 ? void 0 : _k.id }), h("ion-router-link", { href: `geo:${(_m = (_l = state === null || state === void 0 ? void 0 : state.job) === null || _l === void 0 ? void 0 : _l.address) === null || _m === void 0 ? void 0 : _m.full}` }, h("ion-chip", null, h("ion-icon", { class: "ft-icon-style", name: "map" }), h("ion-label", null, "Map"))), h("ion-router-link", { href: `/jobs/${this.jobId}/scope` }, h("ion-chip", null, h("ion-icon", { class: "ft-icon-style", name: "list" }), h("ion-label", null, "View Scope"))), ((_o = state === null || state === void 0 ? void 0 : state.job) === null || _o === void 0 ? void 0 : _o.matterportModelId) && (h("ion-router-link", { href: "#", onClick: () => this.openMatterportModal() }, h("ion-chip", null, h("ion-icon", { class: "ft-icon-style", name: "cube" }), h("ion-label", null, "Matterport Model")))), isAdmin() && (h("ion-chip", { onClick: () => this.openJobEdit("payment") }, h("ion-icon", { class: "ft-icon-style", name: "logo-usd" }), h("ion-label", null, "Owed ", this.formatUSD(((_p = state === null || state === void 0 ? void 0 : state.job) === null || _p === void 0 ? void 0 : _p.amountOwed) || 0)))), h("ion-router-link", { href: `/pay/${this.jobId}` }, h("ion-chip", null, h("ion-icon", { class: "ft-icon-style", name: "cash" }), h("ion-label", null, "Epay"))), h("ion-chip", { onClick: () => this.openJobEdit("cause") }, h("ion-icon", { class: "ft-icon-style", name: "water" }), h("ion-label", null, `Cat ${((_q = state === null || state === void 0 ? void 0 : state.job) === null || _q === void 0 ? void 0 : _q.category) || 0} - ${((_r = state === null || state === void 0 ? void 0 : state.job) === null || _r === void 0 ? void 0 : _r.cause) || "Unknown"}`)), isAdmin() && ((_s = state === null || state === void 0 ? void 0 : state.job) === null || _s === void 0 ? void 0 : _s.notionId) && (h("ion-router-link", { href: `https://notion.so/madnesslabs/${this.cleanNotionId(state.job.notionId)}`, target: "_system" }, h("ion-chip", null, h("ion-icon", { class: "ft-icon-style", name: "book" }), h("ion-label", null, "Open Notion"))))))), h("ion-row", { class: "ion-no-padding ion-no-margin" }, h("ion-col", { size: "12", sizeMd: "4", class: "ion-no-padding ion-no-margin" }, h("floodteam-title-bar", { icon: "cube", heading: 4, disableUnderline: true }, h("ion-text", null, "Sites"), h("ion-button", { fill: "outline", href: "#", slot: "end", size: "small", onClick: () => this.openSiteEditModal() }, "Add")), h("ion-card", { class: "site-card" }, h("ion-list", { lines: "full", style: {
          paddingBottom: ((_u = (_t = state === null || state === void 0 ? void 0 : state.job) === null || _t === void 0 ? void 0 : _t.sites) === null || _u === void 0 ? void 0 : _u.length) ? "0px" : "8px",
          paddingTop: ((_w = (_v = state === null || state === void 0 ? void 0 : state.job) === null || _v === void 0 ? void 0 : _v.sites) === null || _w === void 0 ? void 0 : _w.length) ? "0px" : "8px",
        } }, ((_y = (_x = state === null || state === void 0 ? void 0 : state.job) === null || _x === void 0 ? void 0 : _x.sites) === null || _y === void 0 ? void 0 : _y.length) ? ((_z = state === null || state === void 0 ? void 0 : state.job) === null || _z === void 0 ? void 0 : _z.sites.map((site) => (h("floodteam-item-site", { onClick: (event) => {
          event.preventDefault();
          event.stopPropagation();
          this.openSiteEditModal(site);
        }, site: site })))) : (h("floodteam-fallback", { message: "No Sites Added...", icon: "cube" }))))), h("ion-col", { size: "12", sizeMd: "8" }, h("floodteam-title-bar", { heading: 4, disableUnderline: true, icon: "water" }, h("ion-text", null, "Moisture Map"), h("ion-button", { fill: "outline", href: "#", slot: "end", size: "small", onClick: (event) => this.openaddReadingPopover(event) }, "Add")), h("floodteam-moisture-map", null)), h("ion-col", { size: "12", sizeMd: "6" }, h("floodteam-title-bar", { heading: 4, disableUnderline: true, icon: "people" }, h("ion-text", null, "Users"), h("ion-button", { fill: "outline", href: "#", slot: "end", size: "small", onClick: () => this.openUserSearch() }, "Add")), h("ion-card", null, h("ion-list", { ref: (el) => (this.userListEl = el) }, ((_1 = (_0 = state === null || state === void 0 ? void 0 : state.job) === null || _0 === void 0 ? void 0 : _0.users) === null || _1 === void 0 ? void 0 : _1.length) ? ((_2 = state.job) === null || _2 === void 0 ? void 0 : _2.users.map((user) => {
        var _a;
        return (h("floodteam-item-user", { role: this.userRoleMap[user === null || user === void 0 ? void 0 : user.id] || null, user: user, jobId: (_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.id }));
      })) : (h("floodteam-fallback", { icon: "people", message: "No Users Added..." }))))), h("ion-col", { size: "12", sizeMd: "6" }, h("floodteam-title-bar", { heading: 4, icon: "file-tray-full", disableUnderline: true }, h("ion-text", null, "Efiles"), h("ion-button", { fill: "outline", href: "#", slot: "end", size: "small", onClick: () => {
          (this.isUploading = true),
            this.fireenjinTrigger.emit({
              name: "upload",
              multiple: true,
              payload: {
                jobId: this.jobId,
              },
            });
        } }, "Add")), h("ion-card", null, h("ion-accordion-group", null, h("ion-accordion", null, h("ion-item", { slot: "header" }, h("ion-icon", { name: "file-tray-full", slot: "start" }), h("ion-label", null, "Inbox"), ((_3 = this.preparingEfiles) === null || _3 === void 0 ? void 0 : _3.length) ? (h("ion-button", { onClick: (event) => this.openSendEfileModal(event), slot: "end", fill: "solid", color: "primary", size: "small" }, h("ion-label", null, "Send "), h("ion-text", { slot: "end" }, "\u00A0", ((_4 = this.preparingEfiles) === null || _4 === void 0 ? void 0 : _4.length) || 0))) : (h("ion-text", { color: ((_6 = (_5 = state === null || state === void 0 ? void 0 : state.job) === null || _5 === void 0 ? void 0 : _5.efiles) === null || _6 === void 0 ? void 0 : _6.length) > 0
          ? "primary"
          : "medium", slot: "end" }, ((_8 = (_7 = state === null || state === void 0 ? void 0 : state.job) === null || _7 === void 0 ? void 0 : _7.efiles) === null || _8 === void 0 ? void 0 : _8.length) || 0))), h("ion-list", { class: {
          "is-loading": this.efileLoading,
        }, slot: "content", ref: (el) => (this.efileListEl = el) }, h("fireenjin-chip-bar", null, h("ion-chip", { onClick: () => this.generatePdf("CcLLkmgyUfeQvQVEWnLp", "Photos Pdf") }, h("ion-icon", { class: "ft-icon-style", name: "document-text-outline" }), h("ion-label", null, "Photo PDF")), h("ion-chip", { onClick: () => this.generatePdf("QMzg5GspcjqouWNxArbh", "Readings PDF") }, h("ion-icon", { class: "ft-icon-style", name: "document-text-outline" }), h("ion-label", null, "Readings PDF")), h("ion-chip", { onClick: () => this.generatePdf("beLtN4HFStll5UgL9NaZ", "Invoice PDF") }, h("ion-icon", { class: "ft-icon-style", name: "document-text-outline" }), h("ion-label", null, "Invoice PDF"))), ((_9 = this.efiles) === null || _9 === void 0 ? void 0 : _9.length) ? (this.efiles
        .sort((a, b) => ((a === null || a === void 0 ? void 0 : a.name) > (b === null || b === void 0 ? void 0 : b.name) ? 1 : -1))
        .map((efile) => {
        var _a, _b;
        return [
          h("ion-item-sliding", null, h("ion-item", { detail: true, target: "_blank", href: efile === null || efile === void 0 ? void 0 : efile.url }, h("ion-checkbox", { slot: "start", name: `efile-${efile === null || efile === void 0 ? void 0 : efile.id}`, value: efile }), h("ion-label", { class: "ion-text-wrap" }, h("p", null, efile === null || efile === void 0 ? void 0 : efile.name)), ((_a = efile === null || efile === void 0 ? void 0 : efile.history) === null || _a === void 0 ? void 0 : _a.length) ? (h("ion-button", { size: "large", color: "primary", fill: "clear", slot: "end", onClick: (event) => {
              var _a;
              event.preventDefault();
              event.stopPropagation();
              if ((_a = this.showingEfileHistory) === null || _a === void 0 ? void 0 : _a.includes(efile.id)) {
                this.showingEfileHistory =
                  this.showingEfileHistory.filter((efileId) => efileId !== (efile === null || efile === void 0 ? void 0 : efile.id));
              }
              else {
                this.showingEfileHistory = [
                  ...this.showingEfileHistory,
                  efile.id,
                ];
              }
            } }, h("ion-icon", { name: "time", slot: "icon-only" }))) : ("")), h("ion-item-options", null, h("ion-item-option", { color: "danger", onClick: () => this.removeEfileFromJob(efile) }, h("ion-icon", { slot: "end", name: "close-circle" }), "Remove"))),
          !!((_b = efile === null || efile === void 0 ? void 0 : efile.history) === null || _b === void 0 ? void 0 : _b.length) && (h("ion-list", { style: {
              display: this.showingEfileHistory.includes(efile.id)
                ? "block"
                : "none",
            } }, ((efile === null || efile === void 0 ? void 0 : efile.history) || []).map((oldEfile) => (h("ion-item-sliding", null, h("ion-item", { detail: true, target: "_blank", href: oldEfile.url }, h("ion-checkbox", { slot: "start", name: `efile-${oldEfile.id}`, value: oldEfile.url }), h("ion-label", { class: "ion-text-wrap" }, h("p", null, oldEfile.name))), h("ion-item-options", null, h("ion-item-option", { color: "danger", onClick: () => this.removeEfileFromJob(oldEfile) }, h("ion-icon", { slot: "end", name: "close-circle" }), "Remove"))))))),
        ];
      })) : (h("floodteam-fallback", { icon: "file-tray-full", message: "No Files Uploaded..." })))), h("ion-accordion", null, h("ion-item", { slot: "header" }, h("ion-icon", { slot: "start", name: "create" }), h("ion-label", null, "Contracts")), h("ion-list", { slot: "content" }, (state.templates || [])
        .filter((template) => {
        var _a, _b, _c, _d, _e;
        return (template === null || template === void 0 ? void 0 : template.type) === "contract" &&
          (((_b = (_a = template === null || template === void 0 ? void 0 : template.tags) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, "job")) ||
            ((_e = (_d = (_c = state === null || state === void 0 ? void 0 : state.job) === null || _c === void 0 ? void 0 : _c.serviceTypes) === null || _d === void 0 ? void 0 : _d.some) === null || _e === void 0 ? void 0 : _e.call(_d, (serviceType) => { var _a, _b; return (_b = (_a = template === null || template === void 0 ? void 0 : template.tags) === null || _a === void 0 ? void 0 : _a.includes) === null || _b === void 0 ? void 0 : _b.call(_a, serviceType); })));
      })
        .map((contract) => {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        const efile = contractEfileLookup[contract === null || contract === void 0 ? void 0 : contract.id] || null;
        const contractSignatureLookup = {};
        for (const tag of (contract === null || contract === void 0 ? void 0 : contract.tags) || []) {
          if (tag.includes("sign:")) {
            if (!(contractSignatureLookup === null || contractSignatureLookup === void 0 ? void 0 : contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id]))
              contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id] = [];
            let signed = false;
            let noUser = false;
            const role = tag.replace("sign:", "");
            const user = roleUserLookup[role];
            if (!user) {
              noUser = true;
            }
            for (const signature of (efile === null || efile === void 0 ? void 0 : efile.signatures) || []) {
              if ((((_a = signature === null || signature === void 0 ? void 0 : signature.createdBy) === null || _a === void 0 ? void 0 : _a.id) &&
                ((_b = signature === null || signature === void 0 ? void 0 : signature.createdBy) === null || _b === void 0 ? void 0 : _b.id) === (user === null || user === void 0 ? void 0 : user.id)) ||
                ((user === null || user === void 0 ? void 0 : user.id) &&
                  ((_g = (_f = (_e = (_d = (_c = signature === null || signature === void 0 ? void 0 : signature.createdBy) === null || _c === void 0 ? void 0 : _c._key) === null || _d === void 0 ? void 0 : _d.path) === null || _e === void 0 ? void 0 : _e.segments) === null || _f === void 0 ? void 0 : _f.pop) === null || _g === void 0 ? void 0 : _g.call(_f)) ===
                    (user === null || user === void 0 ? void 0 : user.id)))
                signed = true;
            }
            contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id].push({
              role,
              user,
              signed,
              noUser,
            });
          }
        }
        return (h("ion-item", { detail: true }, (efile === null || efile === void 0 ? void 0 : efile.id) &&
          !((_h = contractSignatureLookup === null || contractSignatureLookup === void 0 ? void 0 : contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id]) === null || _h === void 0 ? void 0 : _h.length) && (h("ion-icon", { style: { marginRight: "10px" }, name: "checkmark-circle", color: "primary", slot: "start" })), h("ion-label", { class: "ion-text-wrap" }, h("p", null, (contract === null || contract === void 0 ? void 0 : contract.subject)
          ? contract.subject
          : "No Name..."), ((_j = contractSignatureLookup === null || contractSignatureLookup === void 0 ? void 0 : contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id]) === null || _j === void 0 ? void 0 : _j.length) && (h("fireenjin-chip-bar", null, ((contractSignatureLookup === null || contractSignatureLookup === void 0 ? void 0 : contractSignatureLookup[contract === null || contract === void 0 ? void 0 : contract.id]) ||
          []).map((signer) => {
          var _a, _b;
          return (h("ion-chip", { disabled: (signer === null || signer === void 0 ? void 0 : signer.noUser) || (signer === null || signer === void 0 ? void 0 : signer.signed), onClick: (event) => {
              var _a;
              return this.openEsignModal(event, contract === null || contract === void 0 ? void 0 : contract.id, (_a = signer === null || signer === void 0 ? void 0 : signer.user) === null || _a === void 0 ? void 0 : _a.id, efile === null || efile === void 0 ? void 0 : efile.id);
            } }, h("ion-icon", { name: (signer === null || signer === void 0 ? void 0 : signer.signed)
              ? "checkmark-circle"
              : "create", color: (signer === null || signer === void 0 ? void 0 : signer.signed)
              ? "success"
              : "danger" }), h("ion-label", null, signer === null || signer === void 0 ? void 0 :
            signer.role, " -", " ", ((_a = signer === null || signer === void 0 ? void 0 : signer.user) === null || _a === void 0 ? void 0 : _a.firstName) || "", " ", ((_b = signer === null || signer === void 0 ? void 0 : signer.user) === null || _b === void 0 ? void 0 : _b.lastName) || "")));
        })))), h("ion-button", { slot: "end", color: "primary", fill: "clear", size: "small", onClick: (event) => this.send(event, contract) }, h("ion-icon", { slot: "start", name: "mail" }), "Send")));
      }))))))))),
      h("floodteam-navigation-footer", null, h("floodteam-title-bar", { back: "/jobs", disableUnderline: true }, h("ion-breadcrumbs", null, h("ion-breadcrumb", { href: "/jobs" }, h("ion-icon", { class: "ft-icon-style", slot: "start", name: "water" }), "Jobs"), h("ion-breadcrumb", { href: "#", onClick: () => {
          var _a;
          return this.fireenjinTrigger.emit({
            name: "pin",
            payload: {
              icon: "water",
              href: `/jobs/${this.jobId}`,
              name: ((_a = state === null || state === void 0 ? void 0 : state.job) === null || _a === void 0 ? void 0 : _a.title) || "New Job",
            },
          });
        } }, h("ion-icon", { color: ((_10 = ((state === null || state === void 0 ? void 0 : state.pins) || [])
          .map((pin) => pin === null || pin === void 0 ? void 0 : pin.href)) === null || _10 === void 0 ? void 0 : _10.includes(`/jobs/${this.jobId}`))
          ? "primary"
          : null, slot: "start", name: "pin" }), ((_11 = state === null || state === void 0 ? void 0 : state.job) === null || _11 === void 0 ? void 0 : _11.title) || "???")), h("ion-buttons", { slot: "end" }, h("ion-button", { color: "primary", fill: "solid", onClick: () => this.openJobEdit() }, "Edit")))),
    ];
  }
  static get is() { return "app-job"; }
  static get originalStyleUrls() {
    return {
      "$": ["app-job.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["app-job.css"]
    };
  }
  static get properties() {
    return {
      "jobId": {
        "type": "string",
        "mutable": false,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "job-id",
        "reflect": false
      }
    };
  }
  static get states() {
    return {
      "showingEfileHistory": {},
      "efiles": {},
      "isUploading": {},
      "efileLoading": {},
      "isSending": {},
      "template": {},
      "dots": {},
      "activityFeed": {},
      "isSiteModalOpen": {},
      "isEndOfFeed": {},
      "payModels": {},
      "feedLimit": {},
      "siteId": {},
      "currentSlide": {},
      "showControls": {},
      "sidebarContentEl": {},
      "isUploadingPhoto": {},
      "activityFeedEl": {},
      "selectedReadingDate": {},
      "readingsView": {},
      "selectedImage": {},
      "preparingEfiles": {},
      "efileTemplateId": {}
    };
  }
  static get events() {
    return [{
        "method": "fireenjinFetch",
        "name": "fireenjinFetch",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "FireEnjinFetchEvent",
          "resolved": "FireEnjinFetchEvent",
          "references": {
            "FireEnjinFetchEvent": {
              "location": "import",
              "path": "@fireenjin/sdk"
            }
          }
        }
      }, {
        "method": "fireenjinTrigger",
        "name": "fireenjinTrigger",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "FireEnjinTriggerInput",
          "resolved": "FireEnjinTriggerInput<any>",
          "references": {
            "FireEnjinTriggerInput": {
              "location": "import",
              "path": "@fireenjin/sdk"
            }
          }
        }
      }, {
        "method": "fireenjinSubmit",
        "name": "fireenjinSubmit",
        "bubbles": true,
        "cancelable": true,
        "composed": true,
        "docs": {
          "tags": [],
          "text": ""
        },
        "complexType": {
          "original": "FireEnjinSubmitInput",
          "resolved": "FireEnjinSubmitInput<any, any>",
          "references": {
            "FireEnjinSubmitInput": {
              "location": "import",
              "path": "@fireenjin/sdk"
            }
          }
        }
      }];
  }
  static get elementRef() { return "jobPageEl"; }
  static get listeners() {
    return [{
        "name": "ionSlideDidChange",
        "method": "onSlideChange",
        "target": "body",
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinSuccess",
        "method": "onSuccess",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "ionSlideTap",
        "method": "onSlideTap",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "floodteamCloseModal",
        "method": "onCloseModa",
        "target": "body",
        "capture": false,
        "passive": false
      }, {
        "name": "fireenjinTrigger",
        "method": "openReadingModal",
        "target": "document",
        "capture": false,
        "passive": false
      }, {
        "name": "floodteamOpenSiteEditModal",
        "method": "onOpenSiteEditModal",
        "target": "body",
        "capture": false,
        "passive": false
      }, {
        "name": "floodteamSelect",
        "method": "onSelect",
        "target": "body",
        "capture": false,
        "passive": false
      }, {
        "name": "ionChange",
        "method": "onChange",
        "target": undefined,
        "capture": false,
        "passive": false
      }, {
        "name": "ionRouteDidChange",
        "method": "getData",
        "target": undefined,
        "capture": false,
        "passive": false
      }];
  }
}
