var page_function = {
  components: {
    "data-table": httpVueLoader("components/layout/data_table.vue"),
  },
  data() {
    return {
      VarMenuPage: "admin_users",
      VarMenu: "area",
      VarPageContainerCss: "height:calc(100vh - 65px);",
      selectedItem: 1,
      list: [],

      easy_table: {
        pageIndex: 1,
        pageSize: 10,
        cellStyleOption: {
          headerCellClass: ({ column, rowIndex }) => {
            return "bg-primary text-white custom-table-header";
          },
        },
        data: [],
      },
      //彈窗用資料
      dialog_option_role_id: [],
      dialog: {
        show: false, // 新增/編輯使用者版面顯示
        isNew: true, // 是否為新增
        showEditBtn: false, // 編輯使用者按鈕
        showDeleteBtn: false, // 刪除使用者按鈕
        editUserDisable: false, // 編輯那些資料不能更新設定

        user_id: null, // 員工代號
        name: null, // 使用者名稱
        password: null, // 使用者密碼
        check_password: null, // 使用者二次確認輸入密碼
        role_id: null, //權限
        enabled: "1", //停用狀態 0:停用 1:啟用
        priv_no: 0,
      },

      //列印彈窗控制
      dialog_print: {
        show: false, //是否顯示
        user_id: "", // 員工代號
        user_name: "", // 員工名稱
      },
    };
  },
  computed: {
    tableColumns() {
      let arr = [
        {
          field: "user_id",
          key: "a",
          title: "員工代號",
          align: "center",
          width: 150,
        },
        {
          field: "role_name",
          key: "b",
          title: "權限別",
          align: "center",
          width: 150,
        },
        {
          field: "user_name",
          key: "c",
          title: "員工名稱",
          align: "center",
          width: 150,
        },
        {
          field: "enabled_str",
          key: "d",
          title: "停用狀態",
          align: "center",
          width: 150,
        },
        {
          field: "updated_at",
          key: "e",
          title: "最後更新日期",
          align: "center",
          width: 150,
        },
        {
          field: "updated_by",
          key: "f",
          title: "更新人員",
          align: "center",
          width: 150,
        },
        {
          field: "",
          key: "p",
          title: "-",
          width: 250,
          renderBodyCell: ({ row, column, rowIndex }, h) => {
            let dom = [];
            if (row.edit_ctrl) {
              dom = [
                h("q-btn", {
                  class: "glossy",
                  style: "margin:0px 10px; min-height: 2em;",
                  attrs: {
                    label: "修改",
                    color: "blue",
                  },
                  on: {
                    click: () => {
                      this.open_dialog(row);
                    },
                  },
                }),
                h("q-btn", {
                  class: "glossy",
                  style: "margin:0px 10px; min-height: 2em;",
                  attrs: {
                    label: "刪除",
                    color: "red",
                  },
                  on: {
                    click: () => {
                      this.deleteUser(row);
                    },
                  },
                }),
              ];
            }
            return dom;
          },
        },
      ];
      return arr;
    },
    // table data
    tableData() {
      const { pageIndex, pageSize } = this.easy_table;
      return this.easy_table.data.slice(
        (pageIndex - 1) * pageSize,
        pageIndex * pageSize
      );
    },
    totalCount() {
      return this.easy_table.data.length;
    },

    message_alart() {
      return [
        { label: "未輸入帳號", value: this.$t("page.admin_users.message.id") },
        {
          label: "未輸入密碼",
          value: this.$t("page.admin_users.message.password"),
        },
        {
          label: "未輸入確認密碼",
          value: this.$t("page.admin_users.message.checkPassword"),
        },
        {
          label: "兩個密碼不一致，請輸入正確",
          value: this.$t("page.admin_users.message.password_dc"),
        },
        {
          label: "未輸入姓名",
          value: this.$t("page.admin_users.message.name"),
        },
        {
          label: "電話號碼格式不正確",
          value: this.$t("page.admin_users.message.telephone"),
        },
        {
          label: "手機號碼格式不正確",
          value: this.$t("page.admin_users.message.cellphone"),
        },
        {
          label: "電子郵件格式不正確",
          value: this.$t("page.admin_users.message.email"),
        },
        {
          label: "未可查看案場角色",
          value: this.$t("page.admin_users.message.roleStationSpec"),
        },
        {
          label: "新增成功",
          value: this.$t("page.admin_users.message.success"),
        },
        {
          label: "新增失敗",
          value: this.$t("page.admin_users.message.success_error"),
        },
        {
          label: "刪除成功",
          value: this.$t("page.admin_users.message.delete"),
        },
        {
          label: "刪除失敗",
          value: this.$t("page.admin_users.message.delete_error"),
        },
        {
          label: "更新成功",
          value: this.$t("page.admin_users.message.update"),
        },
        {
          label: "更新失敗",
          value: this.$t("page.admin_users.message.update_error"),
        },
        { label: "提醒", value: this.$t("page.admin_users.message.alart") },
        {
          label: "確定刪除此使用者？",
          value: this.$t("page.admin_users.message.delete_user"),
        },
      ];
    },
  },

  watch: {},

  mounted() {
    this.$set(this.WebSetup, "caption", "使用者管理");
    this.MenuSetup.opened = false;
    this.VarMenuIsOverlay = true;
    this.loadData();
    this.load_option();
  },

  methods: {
    //載入選項
    load_option() {
      let that = this;
      var params = {
        Action: "setting_optios",
        Datas: {},
      };
      return that.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          var resData = res.data.data;
          resData.forEach((el) => {
            that.dialog_option_role_id.push({
              label: el.role_name,
              value: el.role_id,
            });
          });
          that.tableData = resData;
        } else {
          that.FnNotify(res.data.message, "error");
        }
      });
    },
    //載入資料
    loadData() {
      let that = this;
      that.$q.loading.show();
      var params = {
        Action: "Users",
        Datas: {},
      };
      return that.FnWebAPIGet(params).then((res) => {
        if (res.data.result) {
          var resData = res.data.data;
          that.easy_table.data = resData;
          that.$q.loading.hide();
        } else {
          that.FnNotify(res.data.message, "error");
          that.$q.loading.hide();
        }
      });
    },
    // page number change
    pageNumberChange(pageIndex) {
      this.easy_table.pageIndex = pageIndex;
    },
    // page size change
    pageSizeChange(pageSize) {
      this.easy_table.pageIndex = 1;
      this.easy_table.pageSize = pageSize;
    },
    //開啟新增、修改視窗
    async open_dialog(edit_data) {
      var that = this;
      that.$q.loading.show();
      //edit_data 為空則為修改
      if (edit_data != undefined) {
        that.dialog.isNew = false;
        let param = {
          Action: "Users",
          Datas: {
            user_id: edit_data.user_id,
          },
        };
        await that
          .FnWebAPIGet(param)
          .then(function (res) {
            if (res.data.result) {
              var resData = res.data.data;
              that.dialog.user_id = resData.user_id;
              that.dialog.name = resData.user_name;
              that.dialog.role_id = resData.role_id;
              that.dialog.enabled = resData.enabled;
            } else {
              that.FnNotify(`獲取資料失敗 : ${res.data.message}`, "error");
            }
          })
          .catch(async function (err) {});
      }
      that.dialog.show = true;
      that.$q.loading.hide();
    },
    //關閉新增、修改視窗
    close_dialog() {
      var that = this;
      that.$data.dialog = that.$options.data().dialog;
    },
    //	儲存新增使用者資訊
    async save_user() {
      let that = this;

      that.$q.loading.show();
      try {
        //	員工代號確認(區分更新與新增)
        if (
          (that.dialog.isNew && that.dialog["user_id"] == null) ||
          that.dialog["user_id"] == ""
        ) {
          throw "未輸入員工代號";
        }
        //密碼驗證 (區分更新與新增)
        //新增
        if (that.dialog.isNew) {
          //	密碼確認
          if (
            that.dialog["password"] == null ||
            that.dialog["password"] == ""
          ) {
            throw "未輸入新密碼";
          }
          //	第二次密碼確認 (若為更新則此項有填入在驗證)
          if (
            that.dialog["check_password"] == null ||
            that.dialog["check_password"] == ""
          ) {
            throw "未輸入再次輸入新密碼";
          }
          //	密碼與第二次輸入密碼是否一致 (若為更新則此項有填入在驗證)
          if (that.dialog["password"] != that.dialog["check_password"]) {
            that.dialog["check_password"] = null;
            throw "密碼與再次輸入密碼不一致";
          }
        }
        //更新
        else {
          //	密碼確認
          if (
            that.dialog["password"] != null &&
            that.dialog["password"] != ""
          ) {
            //	第二次密碼確認 (若為更新則密碼有填入在驗證)
            if (
              that.dialog["check_password"] == null ||
              that.dialog["check_password"] == ""
            ) {
              throw "未輸入再次輸入新密碼";
            }
            //	密碼與第二次輸入密碼是否一致 (若為更新則密碼有填入在驗證)
            if (that.dialog["password"] != that.dialog["check_password"]) {
              that.dialog["check_password"] = null;
              throw "密碼與再次輸入密碼不一致";
            }
          }
        }
        //	姓名確認
        if (that.dialog["name"] == null || that.dialog["name"] == "") {
          throw "未輸入姓名";
        }
        //	權限確認
        if (that.dialog["role_id"] == null || that.dialog["role_id"] == "") {
          throw "未選擇權限";
        }
        let action = that.dialog.isNew ? "AddUserInfo" : "UpdateUserInfo";
        var params = {
          Action: action,
          Datas: {
            user_id: that.dialog.user_id,
            name: that.dialog.name,
            password: that.dialog.password,
            check_password: that.dialog.check_password,
            role_id: that.dialog.role_id,
            enabled: that.dialog.enabled,
          },
        };
        await that
          .FnWebAPIPost(params)
          .then(function (res) {
            if (res.data.result) {
              that.FnNotify(`成功`, "success");
              that.loadData();
              that.close_dialog();
            } else {
              that.FnNotify(`失敗: ${res.data.message}`, "error");
              that.$q.loading.hide();
            }
          })
          .catch(async function (err) {
            that.FnNotify("系統異常", "error");
            that.$q.loading.hide();
          });
      } catch (e) {
        that.FnNotify(e, "warning");
        that.$q.loading.hide();
        return;
      }
    },

    //	刪除
    async deleteUser(row_data) {
      let that = this;

      if (
        await that.FnConfirm("確定刪除此使用者？", "確認刪除資料將不存在！")
      ) {
        var params = {
          Action: "DeleteUserInfo",
          Datas: {
            userID: row_data.user_id,
          },
        };

        that.$q.loading.show();
        await that
          .FnWebAPIPost(params)
          .then(function (res) {
            if (res.data.result) {
              that.FnNotify(`刪除成功`, "success");
              that.loadData();
            } else {
              that.FnNotify(`刪除失敗 : ${res.data.message}`, "error");
              that.$q.loading.hide();
            }
          })
          .catch(async function (err) {
            that.$q.loading.hide();
            that.FnNotify(`系統異常`, "error");
          });
      }
    },
    //開啟人員QRcode畫面
    open_user_qrcode(row_data) {
      var that = this;
      that.$q.loading.show();
      that.dialog_print.user_id = row_data.user_id;
      that.dialog_print.user_name = row_data.user_name;

      //產生qrcode
      var qr_data = {
        user_id: row_data.user_id,
      };

      var qr_data_str = JSON.stringify(qr_data);
      qr_data_str = qr_data_str.replaceAll('"', "#");
      new QRCode(this.$refs.qr_code, {
        text: qr_data_str,
        width: 128,
        height: 128,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });

      that.dialog_print.show = true;
      that.$q.loading.hide();
    },

    //關閉列印視窗
    close_dialog_print() {
      var that = this;
      //清除彈窗內資料
      that.$data.dialog_print = that.$options.data().dialog_print;
      //清除qrcode
      this.$refs.qr_code.innerText = "";
    },

    //QRcode列印
    print_qrcode() {
      var that = this;
      this.close_dialog_print();
    },
  },
};
