<template>
  <div class="auth-page">
    <div class="top-screen" ref="topScreenRef">
      <qu-search-area :model="screenForm" @search="restSearch" @reset="clearScreen(screenFormRef)">
        <template v-if="userType == 1">
          <el-form-item label="渠道商">
            <div class="screen-item">
              <el-select v-model="screenForm.agentId" filterable remote reserve-keyword placeholder="请输入关键词" clearable
                @change="fetchPropertys">
                <el-option :label="item.name" :value="item.id" v-for="item in agents" :key="item.id"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="物业" prop="propertyId">
            <div class="screen-item">
              <el-select v-model="screenForm.propertyId" filterable remote reserve-keyword placeholder="请输入关键词"
                clearable>
                <el-option :label="item.name" :value="item.id" v-for="item in propertys" :key="item.id"></el-option>
              </el-select>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="权限组名称">
          <div class="screen-item">
            <el-input v-model="screenForm.name" placeholder clearable></el-input>
          </div>
        </el-form-item>
      </qu-search-area>
    </div>
    <div class="auth-group">
      <el-skeleton :rows="10" v-if="!isLoaded" :throttle="500" />
      <qu-table :tableData="tableData" v-model:tableHeader="tableHeader" :height="tableHeight" :pageProps="pageProps"
        :rowButtons="rowButtons" @rowButtonClick="rowButtonCall" @pageChange="pageChange" @sortChange="sortChange"
        @fetchTableAttr="fetchTableAttr" v-loading="mainLoading" v-else :tableButtons="tableButtons" @buttonClick="buttonClick"></qu-table>
    </div>
    <div v-if="showgroupForm">
      <el-dialog :title="groupFormData.id ? '编辑权限组' : '新增权限组'" v-model="showgroupForm" width="400px">
        <el-form :model="groupFormData" label-width="100px" :rules="formRule" ref="addformRef">
          <el-form-item label="权限组名称" prop="name">
            <el-input v-model="groupFormData.name" placeholder></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="groupFormData.memo" placeholder></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type @click="showgroupForm = false">取消</el-button>
            <el-button type="primary" @click="appendGroup">确定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div v-if="showPeople">
      <el-dialog :title="'给“' + groupFormData.name + '”权限组配置人员'" width="600px" fullscreen v-model="showPeople"
        @close="clearPeopleScreen">
        <set-people :groupId="groupFormData.id" :showPeople="showPeople" :buttonId="currentButton.data.buttonId">
        </set-people>
      </el-dialog>
    </div>
  </div>
</template>
<script>
export default {
  name: "authManage",
};
</script>
<script setup>
import { nextTick, onMounted, reactive, ref, computed, watch } from "vue";
import { authorService } from "@/ApiService/authorService";
import { dropdownService } from "@/ApiService/dropdownService.js";
import templateHooks from "@/Hooks/templateHooks.js";
import setPeople from "@/Components/authManage/setPeopleCom.vue";

let mainLoading = ref(false),
  showgroupForm = ref(false),
  groupFormData = reactive({
    id: "",
    name: "",
    memo: "",
  }),
  formRule = reactive({
    name: [{ required: true, message: "权限组名称不能为空", trigger: "blur" }],
  });
const delTip = ref(false),
  tableHeight = ref(0),
  showPeople = ref(false);
const addformRef = ref(),
  topScreenRef = ref();

const isLoaded = ref(false);
const agents = ref([]);
const propertys = ref([]);
const userType = computed(() => {
  return $common.getCompany().enterpriseType;
});

const fetchAgents = () => {
  dropdownService.selectAllAgent().then((res) => {
    if (res.code == 0) {
      agents.value = res.data;
    } else {
      this.$message.error(res.err);
    }
  });
};
const fetchPropertys = () => {
  if (!screenForm.agentId) {
    propertys.value = [];
    screenForm.propertyId = "";
    return;
  }
  dropdownService
    .selectPropertyByAgentId({ agentId: screenForm.agentId })
    .then((res) => {
      if (res.code == 0) {
        propertys.value = res.data;
      } else {
        this.$message.error(res.err);
      }
    });
};
const fetchData = () => {
  if (mainLoading.value) {
    return;
  }
  mainLoading.value = true;
  const { page, rows, sord, sidx } = pageProps;
  return new Promise((resolve) => {
    authorService
      .queryAuthority({
        page,
        rows,
        sord,
        sidx,
        ...screenForm,
      })
      .then((res) => {
        resolve(true);
        mainLoading.value = false;
        if (res.code == 0) {
          tableData.value = res.data.rows;
          pageProps.records = res.data.records;
        } else {
          $message.error(res.err);
        }
      })
      .catch(() => {
        resolve(true);
        mainLoading.value = false;
      });
  });
};
const fetchTableAttr = (tableHead) => {
  $store.commit("fetchFields", { data: tableHead, name: $route.name });
};
const buttonClick = (button) => {
  buttonsClickFun.data[button.enName]();
};
const appendGroup = () => {
  addformRef.value.validate((valid) => {
    if (valid) {
      $messageBox
        .confirm("确定要进行提交吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then((rsp) => {
          console.log(rsp);
          if (groupFormData.id) {
            editGroup();
            return;
          }
          authorService.addAuthority(groupFormData).then((res) => {
            if (res.code == 0) {
              $message.success("添加成功");
              showgroupForm.value = false;
              fetchData();
            } else {
              $message.error(res.err);
            }
          });
        });
    }
  });
};
const editGroup = () => {
  authorService.updateAuthority(groupFormData).then((res) => {
    if (res.code == 0) {
      $message.success("修改成功");
      showgroupForm.value = false;
      fetchData();
    } else {
      $message.error(res.err);
    }
  });
};
const rowButtonCall = ({ row, $column }) => {
  for (let i in row) {
    groupFormData[i] = row[i];
  }
  currentButton.data = $column;
  buttonsClickFun.data[$column.enName]();
};
const clearPeopleScreen = () => { };
const {
  tableData,
  pageProps,
  tableButtons,
  rowButtons,
  tableHeader,
  selectItems,
  buttonsClickFun,
  currentButton,
  screenForm,
  screenFormRef,
  $store,
  $route,
  $router,
  $common,
  clearScreen,
  restSearch,
  pageChange,
  sortChange,
  $message,
  $messageBox,
} = templateHooks(fetchData);
const screenFormData = {
  agentId: "",
  propertyId: "",
  name: "",
};
for (let i in screenFormData) {
  screenForm[i] = screenFormData[i];
}
onMounted(() => {
  if (userType.value == 1) {
    console.log("身份：代理");
    fetchAgents();
  }
  fetchData().then((res) => {
    isLoaded.value = true;
  });

  buttonsClickFun.data = {
    add: () => {
      addformRef.value ? addformRef.value.resetFields() : "";
      for (let i in groupFormData) {
        groupFormData[i] = "";
      }
      showgroupForm.value = true;
    },
    edit: () => {
      showgroupForm.value = true;
    },
    delete: () => {
      console.log("delete");
      $messageBox
        .confirm("此操作将永久删除该数据，是否继续？？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          authorService.deleteAuthority(groupFormData.id).then((res) => {
            if (res.code == 0) {
              $message.success("删除成功");
              fetchData();
            } else {
              // $message.error(res.err);
              $messageBox.alert(res.err, "提示", {
                confirmButtonText: "确定",
              });
            }
          });
        });
    },
    setPeople: () => {
      console.log(currentButton);
      showPeople.value = true;
    },
    set: () => {
      $router.push({
        path: "./setPageAuth",
        query: { authorityId: groupFormData.id, title: groupFormData.name },
      });
    },
  };

});
watch(tableButtons, val => {
  if (val && val.length != 0) {
    nextTick(() => {
      const windowHeight = document.body.clientHeight
      console.log(topScreenRef.value.clientHeight);
      tableHeight.value = windowHeight - topScreenRef.value.clientHeight - 170
    })

  }
})
</script>
<style lang="scss">
.auth-page {
  padding: 0 10px;
  box-sizing: border-box;
}

.el-table__header-wrapper {
  .el-checkbox {
    display: none;
  }
}
</style>
