<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryParams.roleName" placeholder="模糊检索" clearable style="width: 220px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['agri:seller:role:add']">创建角色</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="roleList">
        <el-table-column label="角色名称" align="center" prop="roleName" min-width="120" :show-overflow-tooltip="true" />
        <el-table-column label="角色描述" align="center" prop="roleDesc" min-width="160" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.roleDesc || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="绑定员工" align="center" prop="bindCount" width="90">
          <template slot-scope="scope">
            <span>{{ scope.row.bindCount != null ? scope.row.bindCount : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center"  fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:seller:role:edit']">修改角色</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:seller:role:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 创建/修改角色弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" maxlength="30" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="form.roleDesc" type="textarea" :rows="2" placeholder="选填" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="功能权限" prop="menuIds">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menu"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerRole,
  sellerRoleMenuTree,
  getSellerRole,
  addSellerRole,
  updateSellerRole,
  delSellerRole
} from "@/api/agri/seller/role"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"

export default {
  name: "AgriSellerRole",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 列表加载遮罩
      loading: true,
      // 是否显示检索区
      showSearch: true,
      // 列表总条数
      total: 0,
      // 角色列表数据
      roleList: [],
      // 弹窗标题
      title: "",
      // 是否显示弹窗
      open: false,
      // 菜单树数据
      menuOptions: [],
      menuExpand: false,
      menuNodeAll: false,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 列表检索参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined
      },
      // 创建/编辑表单
      form: {},
      // 表单校验规则
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ]
      }
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    /** 初始化：加载店铺上下文后拉列表 */
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    /** 加载商家端当前店铺上下文，写入 X-Shop-Id 缓存 */
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true
      listSellerRole(this.queryParams).then(response => {
        this.roleList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置检索 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 加载商家端可分配菜单树 */
    loadMenuTree() {
      return sellerRoleMenuTree().then(response => {
        this.menuOptions = response.data || []
      })
    },
    /** 获取权限树选中节点（含半选父节点） */
    getMenuAllCheckedKeys() {
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    /** 展开/折叠权限树 */
    handleCheckedTreeExpand(value) {
      const treeList = this.menuOptions
      for (let i = 0; i < treeList.length; i++) {
        this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value
      }
    },
    /** 全选/全不选权限树 */
    handleCheckedTreeNodeAll(value) {
      this.$refs.menu.setCheckedNodes(value ? this.menuOptions : [])
    },
    /** 父子联动开关 */
    handleCheckedTreeConnect(value) {
      this.form.menuCheckStrictly = !!value
    },
    /** 重置表单 */
    reset() {
      if (this.$refs.menu) {
        this.$refs.menu.setCheckedKeys([])
      }
      this.menuExpand = false
      this.menuNodeAll = false
      this.form = {
        roleId: undefined,
        roleName: undefined,
        roleDesc: undefined,
        status: "0",
        menuCheckStrictly: true
      }
      this.resetForm("form")
    },
    /** 打开创建角色弹窗 */
    handleAdd() {
      this.reset()
      this.loadMenuTree().then(() => {
        this.open = true
        this.title = "创建角色"
      })
    },
    /** 打开修改角色弹窗并回显 */
    handleUpdate(row) {
      this.reset()
      Promise.all([
        this.loadMenuTree(),
        getSellerRole(row.roleId)
      ]).then(responses => {
        const data = (responses[1].data) || {}
        this.form = {
          roleId: data.roleId,
          roleName: data.roleName,
          roleDesc: data.roleDesc,
          status: data.status != null ? data.status : "0",
          menuCheckStrictly: true
        }
        this.open = true
        this.title = "修改角色"
        this.$nextTick(() => {
          if (this.$refs.menu && data.menuIds && data.menuIds.length) {
            this.$refs.menu.setCheckedKeys(data.menuIds)
          }
        })
      })
    },
    /** 关闭弹窗 */
    cancel() {
      this.open = false
      this.reset()
    },
    /** 提交创建或修改 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const menuIds = this.getMenuAllCheckedKeys()
        if (!menuIds || !menuIds.length) {
          this.$modal.msgWarning("请至少选择一项功能权限")
          return
        }
        const payload = {
          roleName: this.form.roleName,
          roleDesc: this.form.roleDesc,
          status: this.form.status,
          menuIds: menuIds
        }
        if (this.form.roleId != null) {
          payload.roleId = this.form.roleId
          updateSellerRole(payload).then(() => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.getList()
          })
        } else {
          addSellerRole(payload).then(() => {
            this.$modal.msgSuccess("创建成功")
            this.open = false
            this.getList()
          })
        }
      })
    },
    /** 删除角色 */
    handleDelete(row) {
      const tip = row.bindCount > 0
        ? '角色「' + row.roleName + '」已绑定 ' + row.bindCount + ' 名员工，删除可能失败。是否继续？'
        : '是否确认删除角色「' + row.roleName + '」？'
      this.$modal.confirm(tip).then(() => {
        return delSellerRole(row.roleId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 0;
}
.tree-border {
  margin-top: 8px;
  border: 1px solid #e5e6e7;
  border-radius: 4px;
  padding: 8px;
  max-height: 360px;
  overflow: auto;
}
</style>
