<template>
  <div style="padding:10px">
    <q-card inline class="fit shadow-6">
      <q-card-main style="height:80%">
        <q-table
          ref="table"
          color="primary"
          :data="serverData"
          :columns="columns"
          separator="cell"
          selection="multiple"
          :selected.sync="selected"
          row-key="id"
          :pagination.sync="serverPagination"
          @request="request"
          :loading="loading"
          :rows-per-page-label="$t('Rows per page')"
          :rows-per-page-options="[5,10,20,30,40,50,60,200,500]"
          :no-data-label="$t('No data')"
        >
          <template slot="top-left" slot-scope="props">
            <q-input v-model="filter.name" type="text" prefix="名称：" />&nbsp;&nbsp;
            <q-btn push dense color="primary" icon="search" @click="search">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
           <!-- <q-btn push dense color="primary" icon="add" @click="addSaveDept">{{$t('Add')}}</q-btn>&nbsp;&nbsp;-->
             <q-btn push dense color="primary" icon="swap horiz" @click="findwxDeptinfo">同步微信部门</q-btn> 
          </template>
          <template slot="top-right" slot-scope="props">
            <q-btn
              flat
              round
              dense
              :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'"
              @click="props.toggleFullscreen"
            />
          </template>
          <template slot="top-selection" slot-scope="props">
            <!-- <q-btn color="negative" flat round delete icon="delete" @click="delUsers" /> -->
            <q-btn icon="create" color="positive" label="启用" @click="updateDeptsStatuslist (1)" />&nbsp;&nbsp;
            <q-btn icon="create" color="negative" label="停用" @click="updateDeptsStatuslist (0)" />
          </template>
          <q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:200px">
            <!-- <q-btn
              small
              icon="toc"
              push
              glossy
              dense
              color="primary"
              label="下属部门"
              @click="selectDeptListByPid(props.value)"
            />
            <q-btn
              small
              round
              push
              glossy
              dense
              icon="edit"
              color="primary"
              @click="editDept(props.value,1)"
            ></q-btn>
            <q-btn
              small
              round
              push
              glossy
              dense
              icon="delete"
              color="red"
              @click="delDept(props.value)"
            ></q-btn> -->
            <q-btn-dropdown color="secondary" label="操作" no-wrap>
                <q-list link>
                  <q-item v-close-overlay @click.native="selectDeptListByPid(props.value)">
                    <q-item-main>
                      <q-item-tile sublabel>下属部门</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay @click.native="editDept(props.value,1)" >
                    <q-item-main>
                      <q-item-tile sublabel>修改</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay @click.native="delDept(props.value)" >
                    <q-item-main>
                      <q-item-tile sublabel >删除</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay>
                    <q-item-main>
                    <q-item-tile sublabel>关闭弹窗</q-item-tile>
                    </q-item-main>
                  </q-item>
                </q-list>
            </q-btn-dropdown>
          </q-td>
        </q-table>
      </q-card-main>
    </q-card>
    <!-- 新增修改页面 -->
    <q-modal v-model="editModal" maximized>
      <q-modal-layout>
        <q-toolbar slot="header">
          <q-btn flat round dense @click="editModal = false" icon="reply" />
          <q-toolbar-title v-if="subtype=='edit'">{{$t('Edit')}}</q-toolbar-title>
          <q-toolbar-title v-if="subtype=='add'">{{$t('Add')}}</q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
          <q-toolbar-title></q-toolbar-title>
          <q-btn round color="red"  @click="saveUpdateDept" v-if="subtype=='edit'">{{$t('Save')}}</q-btn>
          <q-btn round color="red"  @click="saveDept" v-if="subtype=='add'">{{$t('Add')}}</q-btn>
          <q-btn round @click="editModal = false">{{$t('Cancel')}}</q-btn>
        </q-toolbar>

        <div class="layout-padding">
          <q-field :count="20" class="liststype">
            <q-input v-model="tempDept.name" float-label="名称" />
          </q-field>
          <q-field class="liststype">
            <q-select v-model="tempDept.status" :options="yeornoOptions" float-label="启用" />
          </q-field>
        </div>
      </q-modal-layout>
    </q-modal>
    <!-- 所属部门 -->
    <q-modal v-model="menuModal" maximized>
      <q-modal-layout>
        <q-toolbar slot="header">
          <q-btn
            flat
            round
            dense
            @click="menuModal = false,addDept='0',filter.name='',pid='1'"
            icon="reply"
          />
          <q-toolbar-title>下级部门</q-toolbar-title>
        </q-toolbar>
        <q-toolbar slot="footer">
          <q-toolbar-title></q-toolbar-title>
          <q-btn round color="red" @click="menuModal = false,addDept='0',filter.name='',pid='1'">关闭</q-btn>
        </q-toolbar>
        <q-table
          ref="table"
          color="primary"
          :data="nextserverData"
          :columns="next_columns"
          selection="multiple"
          :selected.sync="selected"
          row-key="id"
          :pagination.sync="nextserverPagination"
          @request="next_request"
          :loading="loading"
          :rows-per-page-label="$t('Rows per page')"
          :no-data-label="$t('No data')"
        >
          <template slot="top-left" slot-scope="nextprops">
            <q-input v-model="filter.nextname" type="text" prefix="名称：" />&nbsp;&nbsp;
            <q-btn push dense color="primary" icon="search" @click="nextsearch">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
            <q-btn push dense color="primary" icon="add" @click="nextaddDept">{{$t('Add')}}</q-btn>&nbsp;&nbsp;
            <!-- <q-btn push dense color="primary" icon="swap horiz" @click="synchronousAvatar">同步微信头像</q-btn> -->
          </template>
          <template slot="top-selection" slot-scope="props">
            <!-- <q-btn color="negative" flat round delete icon="delete" @click="delUsers" /> -->
            <q-btn icon="create" color="positive" label="启用" @click="updateDeptsStatuslist (1)" />&nbsp;&nbsp;
            <q-btn icon="create" color="negative" label="停用" @click="updateDeptsStatuslist (0)" />
          </template>
          <q-td slot="body-cell-id" slot-scope="nextprops" :props="nextprops" style="width:200px">
            <!-- <q-btn
              small
              round
              push
              glossy
              dense
              icon="edit"
              color="primary"
              @click="editDept(nextprops.value,2)"
            ></q-btn>
            <q-btn
              small
              round
              push
              glossy
              dense
              icon="delete"
              color="red"
              @click="delDept(nextprops.value)"
            ></q-btn> -->
            <q-btn-dropdown color="secondary" label="操作" no-wrap>
                <q-list link>
                  <q-item v-close-overlay @click.native="editDept(nextprops.value,2)" >
                    <q-item-main>
                      <q-item-tile sublabel>修改</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay @click.native="delDept(nextprops.value)" >
                    <q-item-main>
                      <q-item-tile sublabel >删除</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay>
                    <q-item-main>
                    <q-item-tile sublabel>关闭弹窗</q-item-tile>
                    </q-item-main>
                  </q-item>
                </q-list>
            </q-btn-dropdown>
          </q-td>
        </q-table>
      </q-modal-layout>
    </q-modal>
  </div>
</template>

<script>
import {
  getDeptPagedList,
  delDept,
  updateDeptStatus,
  saveDept,
  editDept,
  updateDeptsStatus,
  loadDept,
  countByExample,
  searchAccount,
  findwxDeptinfo,
  updateRedis
} from "@/service/department/dept";
export default {
  name: "user",
  data() {
    return {
      serverData: [],
      nextserverData: [],
      menuModal: false,
      nextEditModal: false,
      tempFunction: {
        id: 0,
        name: "",
        moduleId: 0,
        module: "",
        code: "",
        description: ""
      },
      menuList: [],
      roleList: [],
      menuSelected: 0,
      addtype: "0",
      roleSelected: [],
      menuModal: false,
      roleModal: false,
      pid: "1",
      serverPagination: {
        page: 1,
        rowsNumber: 0, // specifying this determines pagination is server-side
        rowsPerPage: 10 // current rows per page being displayed
      },
      nextserverPagination: {
        page: 1,
        rowsNumber: 0, // specifying this determines pagination is server-side
        rowsPerPage: 100 // current rows per page being displayed
      },
      selectOptions: [
        {
          label: "启用",
          value: "1"
        },
        {
          label: "停用",
          value: "0"
        }
      ],
      yeornoOptions: [
        {
          label: "是",
          value: "1"
        },
        {
          label: "否",
          value: "0"
        }
      ],
      sexOptions: [
        {
          label: "男",
          value: "1"
        },
        {
          label: "女",
          value: "2"
        }
      ],
      columns: [
        {
          name: "name",
          required: true,
          label: "名称",
          align: "left",
          field: "name",
         sortable: false
        },
        {
          name: "num",
          label: "下属部门数量",
          field: "num",
         sortable: false,
          align: "center"
        },
        {
          name: "statusname",
          label: "启停",
          field: "statusname",
         sortable: false,
          align: "center"
        },
        {
          name: "id",
          required: true,
          label: this.$t("ID"),
          align: "center",
          field: "id"
        }
      ],
      //   子部门菜单
      next_columns: [
        {
          name: "name",
          required: true,
          label: "名称",
          align: "left",
          field: "name",
         sortable: false
        },
        {
          name: "statusname",
          label: "启停",
          field: "statusname",
         sortable: false,
          align: "center"
        },
        {
          name: "id",
          required: true,
          label: this.$t("ID"),
          align: "center",
          field: "id"
        }
      ],
      filter: {
        name: "",
        pid: ""
      },
      selected: [],
      loading: false,
      editModal: false,
      subtype: "add",
      tempDept: {
        id: "",
        name: "",
        nextname: "",
        pid: "",
        status: "",
        synchronous: ""
      }
    };
  },
  methods: {
    async request(props) {
      this.loading = true;
      this.serverPagination = props.pagination;
      let table = this.$refs.table,
        { page, rowsPerPage, sortBy, descending } = props.pagination;
      let query = {
        pageNum: page,
        pageSize: rowsPerPage,
        sortBy: sortBy,
        descending: descending,
        name: this.filter.name,
        pid: this.pid
        // account: this.filter.account,
        // phoneNumber: this.filter.phoneNumber
      };

      let dataRes = await getDeptPagedList(query);
      let data = dataRes.data.data;
      this.serverPagination.rowsNumber = data.total;
      this.serverData = data.list;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    async delDept(id) {
      let count = await countByExample({ id: id });
      if (count.data.data > 0) {
        this.$q.notify({
          type: "negative",
          message: this.$t("Dept delete"),
          position: "bottom-right"
        });
        return;
      } else {
        try {
          await this.$q.dialog({
            title: "删除操作",
            message: this.$t("Comfirm do it"),
            position: "right",
            ok: {
              push: true,
              label: "确认"
            },
            cancel: {
              push: true,
              color: "negative",
              label: "取消"
            }
          });
          await delDept({ id: id });
          this.$q.notify({
            type: "positive",
            message: this.$t("Successfully deleted"),
            position: "bottom-right"
          });
          this.search();
        } catch (e) {}
      }
    },
    /**
     * 批量更新状态
     */
    async updateDeptsStatuslist(type) {
      try {
        await this.$q.dialog({
          title: this.$t("Batch do it"),
          message: this.$t("Comfirm do it"),
          ok: {
            push: true,
            label: "提交"
          },
          cancel: {
            push: true,
            color: "negative",
            label: "取消"
          }
        });
        let idlist = this.selected.map(s => {
          return s.id;
        });
        await updateDeptsStatus(idlist.join(","), type);
        this.$q.notify({
          type: "positive",
          message: this.$t("Successfully"),
          position: "bottom-right"
        });
        this.selected = [];
        this.search();
        this.nextsearch();
      } catch (e) {}
    },
    /**用户修改 */
    editDept(id, type) {
      this.subtype = "edit";
      let editDept = this.serverData.filter(s => {
        return s.id === id;
      });
      if (type == "2") {
        editDept = this.nextserverData.filter(s => {
          return s.id === id;
        });
      }

      if (editDept && editDept.length > 0) {
        this.tempDept = JSON.parse(JSON.stringify(editDept[0]));
      } else {
        return true;
      }
      this.editModal = true;
      
    },
    async saveUpdateDept() {
      await editDept(this.tempDept);
      this.$q.notify({
        type: "positive",
        message: this.$t("Saved successfully"),
        position: "bottom-right"
      });
      this.editModal = false;
      if (this.addtype == "0") {
        this.search();
      } else if (this.addtype == "1") {
        this.nextsearch();
      }
    },
    search() {
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    },
    /**
     * 更新用户
     */
    async saveDept() {
 if (this.tempDept.name=="" || this.tempDept.name==null) {
          this.$q.notify({
          message:"请填写部门名称",
          type: "negative",
          icon: "error_outline",
          timeout: 3000,
          position: "center"
        });
        return false;
      }

      let count = await searchAccount({ name: this.tempDept.name });
      if (count.data.data > 0) {
         this.$q.notify({
          type: "negative",
          message: this.$t("部门名称已存在"),
          position: "center"
        });
        return;
      } else {
        this.tempDept.pid = this.pid;
               
         let count =await saveDept(this.tempDept);
  
        this.$q.notify({
          type: "positive",
          message: this.$t("保存成功"),
          position: "center"
        });
        this.editModal = false;
        if (this.addtype == "0") {
          this.pid = "1";
          this.search();
        } else if (this.addtype == "1") {
          this.nextsearch();
        }
      }
    },
    search() {
    	this.updateRedis_use();
      this.request({
        pagination: this.serverPagination,
        filter: this.filter
      });
    },
    /**同步微信头像 */
    async findwxDeptinfo() {
      await findwxDeptinfo();
      this.$q.notify({
        type: "positive",
        message: this.$t("Successfully synchronization"),
        position: "bottom-right"
      });
    },
    /**新增 */
    addSaveDept() {
      this.pid = "1";
      this.tempDept = {};
      this.tempDept.status="1";
      this.subtype = "add";
      this.editModal = true;
    },
    // 下级部门方法
    //   查询子部门
    async next_request(props) {
      this.loading = true;
      this.nextserverPagination = props.pagination;
      let table = this.$refs.table,
        { page, rowsPerPage, sortBy, descending } = props.pagination;
      let query = {
        pageIndex: page,
        pageSize: rowsPerPage,
        sortBy: sortBy,
        descending: descending,
        pid: this.pid,
        name: this.filter.nextname
      };
      let dataRes_next = await getDeptPagedList(query);
      let data_next = dataRes_next.data.data;
      this.nextserverPagination.rowsNumber = data_next.total;
      this.nextserverData = data_next.list;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },
    selectDeptListByPid(pid) {
      this.pid=pid;
      this.addDept = "1";
      this.next_request({
        pagination: this.nextserverPagination,
        filter: this.filter
      });
      this.menuModal = true;
    },
    nextsearch() {
      this.next_request({
        pagination: this.nextserverPagination,
        filter: this.filter
      });
    },
    nextaddDept() {
      this.tempDept = {};
      this.tempDept.pid = this.pid;
      this.tempDept.status="1";
      this.subtype = "add";
      this.addtype = "1";
      this.editModal = true;
    },
    		//调用审批接口，更新缓存
			async updateRedis_use(){
			 		let menuListRes = await updateRedis();
			}
  },

  mounted() {
    this.request({
      pagination: this.serverPagination,
      filter: this.filter
    });
  }
};
</script>
<style scoped>
.liststype {
  width: 98%;
  /* padding-left: 4%; */
  /* float: left; */
}
</style>
