<template>
  <div style="padding: 20px">
    <el-input
      placeholder="请输入名称/代码"
      style="width: 340px"
      prefix-icon="el-icon-search"
      clearable
      v-model.trim="search"
      @change="onSearch"
    ></el-input>
    <el-button style="float: right" type="primary" @click="editOperation.show = true">新建操作项</el-button>
    <el-table style="margin-top: 20px" :data="operationList">
      <el-table-column label="操作项名称" prop="operationItemName" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="操作项code" prop="operationItemCode" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column label="页面code" prop="menuCode" :formatter="(row, col, val) => val || '--'"></el-table-column>
      <el-table-column :label="appType == 1 ? '好办版本' : '应用版本'" prop="version" :formatter="formatVersion"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" @click="onEdit(row)">编辑</el-button>
          <el-button type="text" @click="onDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="pager.total > 0"
      style="text-align: right"
      layout="total,sizes,prev,pager,next"
      background
      :total="pager.total"
      :page-sizes="pager.pageSizes"
      :page-size="pager.pageSize"
      :current-page="pager.currentPage"
      @size-change="onSizeChage"
      @current-change="onCurrentChange"
    ></el-pagination>
    <el-dialog :visible.sync="editOperation.show" :title="editOperation.operationItemId ? '编辑操作项' : '新建操作项'" width="590px" @closed="onEditOperationClose">
      <el-form :model="editOperation" :rules="editOperationRule" ref="editOperation" label-width="110px">
        <el-form-item label="节点" prop="menuId">
           <el-cascader v-model="editOperation.menuId" :options="menuList" :props="{ checkStrictly: true, label: 'menuName', value: 'menuId' }" style="width: 440px" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="节点code">
          <el-input :value="editOperation.menuCode" style="width:440px" disabled></el-input>
        </el-form-item>
        <el-form-item label="好办版本" prop="version" v-if="appType == 1">
          <el-select v-model="editOperation.version" style="width: 440px">
            <el-option v-for="el in haobanVersionList" :key="el.versionCode" :value="el.versionCode" :label="el.version"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用版本" prop="version" v-else>
          <el-select v-model="editOperation.version" style="width: 440px">
            <el-option v-for="el in appVersionList" :key="el.versionCode" :value="el.versionCode" :label="el.version"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="操作项名称" prop="operationItemName">
          <el-input
            type="text"
            style="width: 440px"
            maxlength="20"
            show-word-limit
            v-model.trim="editOperation.operationItemName"
          ></el-input>
        </el-form-item>
        <el-form-item label="操作项code" prop="operationItemCode">
          <el-input
            type="text"
            style="width: 440px"
            maxlength="200"
            show-word-limit
            v-model.trim="editOperation.operationItemCode"
          ></el-input>
        </el-form-item>
        <el-form-item label="请求URL">
          <el-input
            type="text"
            style="width: 440px"
            maxlength="200"
            show-word-limit
            v-model.trim="editOperation.operationItemUrl"
          ></el-input>
        </el-form-item>
        <el-form-item label="生成权限项">
          <el-switch :value="editOperation.authItemFlag == 1" @change="editOperation.authItemFlag = editOperation.authItemFlag == 1 ? 0 : 1"></el-switch>
        </el-form-item>
        <el-form-item label="权限适用">
          <el-radio-group v-model="editOperation.roleRange">
            <el-radio label="1">管理员权限集</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="editOperation.show = false">取消</el-button>
        <el-button type="primary" :loading="editOperation.loading" @click="onEditOperationSave">{{ editOperation.operationItemId ? '保存' : '新建' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/permission.js';

const { getOperationItemList, addOperationItem, editOperationItem, delOperationItem, getMenuList, haobanVersionList, appVersionList } = api;
// 搜索，翻页 done
// 新建、编辑操作项 done
// 删除操作项 done
export default {
  name: 'operation-table',
  props: {
    appType: [String, Number]
  },
  data() {
    return {
      // 节点列表
      menuList: [],
      // 平铺的节点列表
      flatMenuList: [],
      // 好办版本列表
      haobanVersionList: [],
      // 应用版本列表
      appVersionList: [],
      search: '',
      // 分页相关的数据
      pager: {
        total: 0,
        pageSizes: [20, 40, 60, 80],
        pageSize: 20,
        currentPage: 1
      },
      // 操作项列表
      operationList: [],
      // 新建、编辑操作项
      editOperation: {
        show: false,
        loading: false,
        operationItemId: '',
        menuId: [],
        menuCode: '',
        operationItemName: '',
        operationItemCode: '',
        operationItemUrl: '',
        authItemFlag: '', // 是否生产权限项1是0否
        roleRange: '1', // 1使用管理员
        version: '',
        appType: ''
      },
      editOperationRule: {
        menuId: [{ required: true, message: '请选择节点', trigger: 'change' }],
        version: [{ required: true, message: '请选择版本', trigger: 'change' }],
        operationItemName: [{ required: true, message: '操作项名称不能为空', trigger: 'blur' }],
        operationItemCode: [{ required: true, message: '操作项code不能为空', trigger: 'blur' }],
      }
    }
  },
  created() {
    // this.initData();
  },
  methods: {
    initData() {
      this.getOperationList();
      getMenuList({ appType: this.appType }).then(res => {
        this.menuList = this.flatDataToTree(res.result || []);
      })
      haobanVersionList().then(res => {
        this.haobanVersionList = res.result || [];
      })
      appVersionList().then(res => {
        this.appVersionList = res.result || [];
      })
    },
    // 获取操作项列表
    getOperationList() {
      const { currentPage, pageSize } = this.pager;
      const params = {
        search: this.search,
        pageNum: currentPage,
        pageSize,
        appType: this.appType
      }
      getOperationItemList(params).then(res => {
        const { totalCount, list } = res.result || {};
        this.pager.total = totalCount || 0;
        this.operationList = list || [];
      })
    },
    onSearch() {
      this.pager.currentPage = 1;
      this.getOperationList();
    },
    onSizeChage(pageSize) {
      this.pager.pageSize = pageSize;
      this.onSearch();
    },
    onCurrentChange(currentPage) {
      this.pager.currentPage = currentPage;
      this.getOperationList();
    },
    // 列表显示 格式化版本号信息
    formatVersion(row, col, val) {
      let result = '--';
      if (this.appType == 1) {
        this.haobanVersionList.some(callback);
      } else {
        this.appVersionList.some(callback);
      }
      function callback(el) {
        if (el.versionCode == val) {
          result = el.version;
        }
        return el.versionCode == val;
      }
      return result;
    },
    // 编辑操作项 打开弹窗
    onEdit(operationData) {
      const { operationItemId, menuId, menuCode, operationItemName, operationItemCode, operationItemUrl, authItemFlag, roleRange, version } = operationData;
      Object.assign(this.editOperation, {
        show: true,
        operationItemId,
        menuId: getFullId(this.flatMenuList, menuId),
        menuCode,
        operationItemName,
        operationItemCode,
        operationItemUrl,
        authItemFlag,
        roleRange: typeof roleRange == 'undefined' ? '1' : roleRange,
        version
      });
      function getFullId(menuList, menuId) {
        let result = [ menuId ];
        menuList.some(el => {
          if (el.menuId == menuId && el.parentId > 0) {
            result = getFullId(menuList, el.parentId).concat(result);
          }
          return el.menuId == menuId
        })
        return result;
      }
    },
    // 新建、编辑操作项 弹窗关闭
    onEditOperationClose() {
      Object.assign(this.editOperation, {
        operationItemId: '',
        menuId: '',
        menuCode: '',
        operationItemName: '',
        operationItemCode: '',
        operationItemUrl: '',
        authItemFlag: '',
        roleRange: '1',
        version: '',
        appType: ''
      })
      this.$nextTick(this.$refs.editOperation.clearValidate);
    },
    // 新建、编辑操作项 弹窗保存
    onEditOperationSave() {
      this.$refs.editOperation.validate(vali => {
        if (!vali) return;
        const { operationItemId, menuId, menuCode, operationItemName, operationItemCode, operationItemUrl, authItemFlag, roleRange, version, appType } = this.editOperation;
        const params = {
          menuId: Array.isArray(menuId) && menuId.length > 0 ? menuId[menuId.length - 1] : '',
          menuCode,
          operationItemName,
          operationItemCode,
          operationItemUrl,
          authItemFlag,
          roleRange,
          version
        }

        this.editOperation.loading = true;
        if (operationItemId) {
          params.operationItemId = operationItemId;
          editOperationItem(params).then(succ.bind(this, '保存成功！')).finally(() => this.editOperation.loading = false);
        } else {
          params.appType = appType;
          addOperationItem(params).then(succ.bind(this, '新建成功！')).finally(() => this.editOperation.loading = false);
        }
        function succ(msg) {
          this.$message.success(msg);
          this.getOperationList();
        }
      })
    },
    // 删除操作项
    onDel(operationData) {
      const { operationItemId, operationItemName } = operationData;
      this.$confirm(`确定删除【 ${operationItemName} 】吗？`, '提示', { type: 'warning' }).then(() => {
        delOperationItem({ operationItemId }).then(res => {
          this.$message.success('删除成功！');
          if (this.pager.currentPage > 1 && this.operationList.length == 1) {
            this.pager.currentPage--;
          }
          this.getOperationList();
        })
      })
    },
    flatDataToTree(data) {
      return data.filter(el => {
        // 返回当前节点下的子节点
        const children = data.filter(item => item.parentId == el.menuId);
        if (children.length > 0) {
          el.children = children; // 如果存在子级，则给父级添加一个children属性，并赋值
        }
        return el.parentId == 0;
      })
    },
  }
}
</script>
