<template>
  <div :style="pageStyle">
    <q-card>
      <q-card-title class="card-title">{{ $t("menu.alarm_dispatch")+" "+$t('page.alarm_dispatch.form_content') }}</q-card-title>
      <q-card-main>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.form_id') }}</div>
        </div>
        <div>{{ this.dispatchSn || 'NULL' }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.phase') }}</div>
        </div>
        <div>{{ this.$t("sys.phase."+phase) }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.seq') }}</div>
        </div>
        <div>{{ this.formData.seq }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.stn') }}</div>
        </div>
        <div>{{ this.formData.stn }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.al_start_time') }}</div>
        </div>
        <div>{{ moment(this.formData.al_start_time).format("YYYY/MM/DD HH:mm:ss") }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.al_message') }}</div>
        </div>
        <div>{{ this.formData.Message }}</div>
        <div class="q-if-label q-if-label-above">
          <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.owner_user_name') }}</div>
        </div>
        <div>{{ this.ownerUserName || 'NULL' }}</div>
        <q-select
          v-if="action!='view' && phase=='draft'"
          v-model="assignUserId"
          :stack-label="$t('page.alarm_dispatch.assign_user_name')"
          :options="assignUserOptions"
        ></q-select>
        <q-input
          v-else
          v-model="assignUserName"
          :stack-label="$t('page.alarm_dispatch.assign_user_name')"
          readonly
        ></q-input>
        <q-input
          v-model="comment"
          type="textarea"
          :stack-label="$t('page.alarm_dispatch.comment')"
          :readonly="action=='view'"
          rows="3"
        ></q-input>
      </q-card-main>
      <q-card-title class="card-title">{{ $t('page.alarm_dispatch.reply_content') }}</q-card-title>
      <q-card-main
        v-show="phase!='draft'"
        style="max-height: 300px; overflow-y: auto;"
      >
        <q-input
          v-show="action!='add'"
          v-model="reply"
          type="textarea"
          :stack-label="$t('page.alarm_dispatch.reply')"
          :readonly="action=='view'"
          rows="3"
        ></q-input>
        <!-- 上傳多張圖片 -->
        <div v-show="action=='edit'">
          <div class="q-if-label q-if-label-above">
            <div class="q-if-label-inner ellipsis">{{ $t('page.alarm_dispatch.upload_image') }}</div>
          </div>
          <input
            type="file"
            multiple
            accept="image/*"
            ref="fileInput"
            @change="handerFiles"
          />
          <hr>
        </div>
        <div style="border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; background-color: rgbrgb(249, 249, 249);">
          <img
            v-for="(itm,idx) in imageFileList"
            :key="idx"
            :src="itm"
            class="hover-effect"
            :style="'cursor: pointer;width:'+($root.VarIsDesktop?'25%':'50%')"
            @click="openImageModel(itm,idx)"
          >
        </div>
      </q-card-main>
      <q-card-actions align="center">
        <q-btn
          color="primary"
          :label="$t('sys.edit')"
          @click="action='edit'"
          style="width:80px;"
          v-show="action=='view' && phase=='execute' && (loginUserIsAssign || logingUserIsManager)"
        ></q-btn>
        <q-btn
          color="primary"
          :label="$t('page.alarm_dispatch.dispatch')"
          @click="dispatchForm"
          style="width:80px;"
          v-show="action=='add'"
        ></q-btn>
        <q-btn
          color="primary"
          :label="$t('sys.save')"
          @click="saveForm"
          style="width:80px;"
          v-show="action=='edit'"
        ></q-btn>
        <q-btn
          color="primary"
          :label="$t('page.alarm_dispatch.re_dispatch')"
          @click="reDispatchForm"
          style="width:80px;"
          v-if=" phase=='complete' && logingUserIsManager && action=='view'"
        ></q-btn>
        <q-btn
          v-if="(phase=='execute' && (logingUserIsManager || loginUserIsAssign)) && action=='view'"
          color="orange"
          :label="$t('sys.phase.complete')"
          @click="completeForm"
          style="width:80px;"
        ></q-btn>
        <q-btn
          v-if=" phase=='complete' && logingUserIsManager && action=='view'"
          color="orange"
          :label="$t('sys.phase.end')"
          @click="endForm"
          style="width:80px;"
        ></q-btn>
        <q-btn
          v-if="(phase=='execute' || phase=='complete' || phase=='end') && logingUserIsManager && action=='view'"
          color="red"
          :label="$t('sys.void')"
          @click="voidForm"
          style="width:80px;"
        ></q-btn>
        <!-- 沒有 draft -->
        <!-- <q-btn
          v-if="phase=='draft' && action=='view' && logingUserIsManager"
          color="red"
          :label="$t('sys.delete')"
          @click="delForm"
          style="width:80px;"
        ></q-btn>
      -->
        <q-btn
          color="secondary"
          :label="$t('sys.close')"
          @click="closeForm"
          style="width:80px;"
        ></q-btn>
      </q-card-actions>
    </q-card>
    <q-modal
      v-model="isOpenImageModal"
      minimized
    >
      <q-card>
        <q-card-main :style="{'max-height': ($root.VarLayoutScreenHeight*0.6) +'px','overflow-y': 'auto'}">
          <img
            :src="imageOpenFile"
            style="max-width: 90vw;"
          >
        </q-card-main>
        <q-card-actions align="center">
          <q-btn
            color="red"
            v-show="phase=='execute' && action=='edit' && (logingUserIsManager || loginUserIsAssign)"
            :label="$t('sys.delete')"
            style="width:80px;"
            @click="delImage"
          ></q-btn>
          <q-btn
            color="secondary"
            :label="$t('sys.close')"
            @click="isOpenImageModal=false"
            style="width:80px;"
          ></q-btn>
        </q-card-actions>
      </q-card>
    </q-modal>
  </div>
</template>

<script>
module.exports = {
  name: "alarm-dispatch-form",
  props: {
    "title": {
      "type": "String",
    },
    "page-style": { // 放在頁面 template / div 的 style
      "type": "String",
      "default": "",
    },
    "action": { // 新增或者修改用途
      "type": "String",
      "default": "add", // add, update, view
    },
    "form-id": { // 派工編號
      "type": "String",
      "default": "",
    },
    "is-modal-open": {
      "type": "Boolean",
      "default": false,
    },
    "alarm-dispatch-props": { // 表單資料(phase=add)
      "type": "Object",
      "default": {},
    },
    "is-only-form": { // 只是表單(alarm_dispatch_form.php)
      "type": "Boolean",
      "default": false,
    },
  },
  data () {
    return {
      dispatchSn: "",
      comment: "",
      assignUserList: [], // 抓取可作業人員清單,最後整理成下拉選單(assignUserOptions)
      assignUserId: "", // 作業人員
      assignUserName: "", // 作業人員姓名
      ownerUserId: "", // 派指人員
      ownerUserName: "", // 派指人員姓名
      reply: "", // 回覆
      phase: "draft", // 階段
      imageRowList: [], // 圖片記錄清單
      imageFileList: [], // 圖片內容清單
      isOpenImageModal: false, // 是否開啟圖片視窗
      imageOpenFile: "", // 開啟視窗的圖片
      imageOpenRow: null, // 開啟視窗的圖片記錄
      uploadFileList: [], // 上傳的檔案
      formData: {},
    }
  },
  computed: {
    isDesktop () { // 是否為桌面平台
      return this.$root.VarIsDesktop;
    },
    isMobile () { // 是否為手機平台
      return this.$root.VarIsMobile;
    },
    isTablet () { // 是否為平板平台
      return this.$root.VarIsTablet;
    },
    isMenuOpen () { // 是否開啟選單
      return this.$root.VarIsMenuOpen;
    },
    screenIsVertical () { // 螢幕是否直立
      return this.$root.VarScreenIsVertical;
    },
    layoutScreenHeight () { // 螢幕的高
      return this.$root.VarLayoutScreenHeight;
    },
    layoutContainerHeight () { // 螢幕的寬
      return this.$root.VarLayoutContainerHeight;
    },
    assignUserOptions () { // 作業人員下拉選單
      return this.$root.FnGetOptions(this.assignUserList, "user_name", "user_id");
    },
    logingUserIsManager () { // 是否為管理者
      return this.$root.FnChkLoginRole('admin');
    },
    loginUserIsOwner () { // 目前登入者是否為指派人員
      return this.$root.LoginSetup.uid == this.ownerUserId;
    },
    loginUserIsAssign () { // 目前登入者是否為作業人員
      return this.$root.LoginSetup.uid == this.assignUserId;
    },
  },
  watch: {
    // 需指定 is-modal-open 才能驅動 <alarm-dispatch-form action="view" :is-modal-open="isModalOpen" @modal-close="modalClose"></alarm-dispatch-form>
    isModalOpen (nv) {
      if (nv) { // 每次開啟視窗時
        this.initForm();
      }
    },
  },
  mounted () {
    this.getAssignUserList(); // 只會蒐尋一次
    if (this.isOnlyForm) {
      this.initForm();
    }
  },
  methods: {
    async initForm () {
      this.dispatchSn = "";
      this.comment = "";
      this.ownerUserId = "";
      this.ownerUserName = "";
      this.assignUserId = "";
      this.assignUserName = "";
      this.comment = "";
      this.imageRowList = [];
      this.imageFileList = [];
      this.imageOpenFile = "";
      this.imageOpenRow = null;
      this.uploadFileList = [];
      this.$refs.fileInput.value = null;
      if (this.action == "add") {
        this.formData = this.alarmDispatchProps;
        this.ownerUserId = this.$root.LoginSetup.uid;
        this.ownerUserName = this.$root.LoginSetup.user_name;
      } else if (this.action == "update" || this.action == "view") {
        this.dispatchSn = this.formId;
        this.getForm().then((res) => {
          this.assignUserId = this.formData.assign_user_id;
          this.assignUserName = this.formData.assign_user_name;
          this.ownerUserId = this.formData.owner_user_id;
          this.ownerUserName = this.formData.owner_user_name;
          this.comment = this.formData.comment;
          this.phase = this.formData.phase;
          this.reply = this.formData.reply;
          this.getImageRowList();
        })
      }
    },
    async delForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_del_form"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn };
      var params = {
        Action: 'Delete',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$emit('data-modified');
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      })
    },
    async voidForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_void_form"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn };
      var params = {
        Action: 'Void',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$emit('data-modified');
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        this.$emit('modal-close');
      })
    },
    async completeForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_complete_form"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn };
      var params = {
        Action: 'complete',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$emit('data-modified');
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        this.$emit('modal-close');
      })
    },
    async reDispatchForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_re_dispatch"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn };
      var params = {
        Action: 'ReDispatch',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$emit('data-modified');
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        this.$emit('modal-close');
      })
    },
    async endForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_end_form"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn };
      var params = {
        Action: 'End',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$emit('data-modified');
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        this.$emit('modal-close');
      })
    },
    async dispatchForm () {
      if (this.assignUserId == "") {
        this.$root.FnNotify(this.$t("page.alarm_dispatch.message.please_assign"), "warning")
        return;
      }
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_dispatch"))) {
        return;
      }
      var datas = { "owner_user_id": this.ownerUserId, "assign_user_id": this.assignUserId, "comment": this.comment, "stn": this.formData.stn, "seq": this.formData.seq, "al_start_time": this.formData.al_start_time };
      var params = {
        Action: 'AlarmDispatch',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(res.data.data, "info");
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        this.$emit('modal-close');
      })
    },
    async saveForm () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("page.alarm_dispatch.message.confirm_save_form"))) {
        return;
      }
      var datas = { "dispatch_sn": this.dispatchSn, "reply": this.reply };
      var params = {
        Action: 'Save',
        Datas: datas,
        Files: { "upload_files": this.uploadFileList },
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.$refs.fileInput.value = null;
          this.getImageRowList();
          this.$emit('data-modified'); // 通知父層資料已修改, 會造成 action = 'view'
          // 但 isOnlyForm = true 時,需要主動設定
          if (this.isOnlyForm) {
            this.action = "view";
          }
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      }).finally(() => {
        // this.$emit('modal-close');
      })
    },
    closeForm () {
      this.$emit('modal-close');
    },
    getForm () {
      var params = {
        Action: 'AlarmDispatchForm',
        Datas: { "dispatch_sn": this.dispatchSn },
        menu_page: "alarm_dispatch",
      };
      return this.$root.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          this.formData = res.data.data;
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      });
    },
    getAssignUserList () {
      var params = {
        Action: 'AssignUserList',
        Datas: {},
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          this.assignUserList = res.data.data;
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      });
    },
    getImageRowList () {
      var params = {
        Action: 'ImageRowList',
        Datas: { "dispatch_sn": this.dispatchSn },
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          this.imageRowList = res.data.data;
          this.imageFileList = [];
          _.each(this.imageRowList, (row, idx) => {
            this.$root.FnWebAPIImage({ Action: 'Image', Datas: { "id": row["id"] }, "menu_page": "alarm_dispatch" }, this.$data, "imageFileList", idx);
          });
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      });
    },
    openImageModel (src, idx) {
      this.imageOpenFile = src;
      this.imageOpenRow = this.imageRowList[idx];
      this.isOpenImageModal = true;
    },
    handerFiles (event) {
      this.uploadFileList = event.target.files;
    },
    async delImage () {
      if (!await this.$root.FnConfirm(this.$t("sys.message.confirm"), this.$t("sys.message.are_sure_to_execute"))) {
        return;
      }
      if (this.imageOpenRow == null) {
        return;
      }
      var datas = { "id": this.imageOpenRow.id, "sys_file": this.imageOpenRow.sys_file };
      var params = {
        Action: 'DeleteImage',
        Datas: datas,
        menu_page: "alarm_dispatch",
      };
      this.$root.FnWebAPIPost(params).then((res) => {
        if (res.data.result) {
          this.$root.FnNotify(this.$t("sys.message.execute_success"), "info");
          this.isOpenImageModal = false;
          this.getImageRowList();
        } else {
          this.$root.FnNotify(res.data.message, "error");
        }
      }).catch(function (err) {
        console.log(err);
      })
    },
  }
}
</script>

<style scoped>
.card-title {
  background-color: #334048;
  color: #fff;
  text-align: center;
}

.hover-effect:hover {
  border: 1px solid rgb(43, 0, 255);
  transform: scale(1.1);
  transition: all 0.4s ease;
}
</style>
