<template>
  <div class="app-container post-page">
    <div class="page-container post-page-min" v-if="pageType == 1">
      <div class="page-form-title-box">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" >
        <el-form-item label="" prop="searchValue">
          <el-input
            v-model="queryParams.searchValue"
            placeholder="身份名称/身份编码"
            clearable
            size="small"
          />
        </el-form-item>
        <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
        <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
          <p class="page-submit-common-style-button"
             style="float: right;"
             @click="handleAdd"
             v-hasPermiRouter="['system:post:add']"
          >新增</p>
      </el-form>
      </div>
      <div class="page-content-box">
        <el-table class="table-box" v-loading="loading" border :data="postList" @selection-change="handleSelectionChange">
          <el-table-column label="序号"  width="55" align="center"  type="index"/>
          <el-table-column label="身份名称" align="left" prop="postName" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="身份编码" align="left" prop="postCode" :show-overflow-tooltip="true" width="200"/>
          <el-table-column label="权限组" align="left" prop="roleNameStr" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="left" prop="createTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime,"{y}-{m}-{d} {h}:{i}") }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="180" v-if="tableButtonType">
            <template slot-scope="scope">
              <div class="table-button-box">
                <p class="table-button-null"></p>
                <p class="table-button-p"
                   v-hasPermiRouter="['system:post:edit']"
                   @click="moreClick({row:scope.row,command:1})"
                >编辑</p>
                <p class="table-button-p"
                   v-hasPermiRouter="['system:post:del']"
                   @click="moreClick({row:scope.row,command:2})"
                >删除</p>
                <p class="table-button-null"></p>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination :page-sizes="[20, 30, 40, 50]"
                    v-show="total>0"
                    :total="total"
                    layout="total, prev, pager, next, sizes, jumper"
                    :page.sync="queryParams.page"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
      </div>
    </div>
    <!-- 添加或修改身份对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body
               :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="身份名称" prop="postName">
          <el-input v-model="form.postName" placeholder="请输入身份名称" maxlength="10" />
        </el-form-item>
        <el-form-item label="身份编码" prop="postCode">
          <el-input v-model="form.postCode" placeholder="请输入编码名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="权限组" prop="roleIds">
          <el-select
            :disabled="userStanding === '-1'"
            style="width:380px;"
            v-model="form.roleIds"
            multiple
            collapse-tags
            placeholder="请选择">
            <el-option
              v-for="item in optionselectList"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer dialog-footer-box">
        <p class="dialog-footer-button-null"></p>
        <p class="dialog-footer-button-info" @click="cancel">取消</p>
        <p class="dialog-footer-button-primary" @click="submitForm">提交</p>
        <p class="dialog-footer-button-null"></p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { systemRoleDropList } from "@/api/commonality/permission";
  import { systemPostList,systemPostAdd,systemPostUpdate,systemPostDetail,systemPostDelete } from "@/api/integratedManagement/index";

export default {
  name: "Post",
  data() {
    return {
      tableButtonType: this.hasPermiDom(['system:post:edit', 'system:post:del']),
      // 身份
      userStanding:localStorage.getItem('userStanding'),
      isShow:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 身份表格数据
      postList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize:20,
        searchValue: null,
        postCode: undefined,
        postName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      pageType:1,
      postId:"",
      // 表单校验
      rules: {
        postName: [
          { required: true, message: "请输入身份名称", trigger: "blur" },
          { required: true, message: "请输入身份名称", validator: this.spaceJudgment, trigger: "blur" }
        ],
        postCode: [
          { required: true, message: "请输入身份编码", trigger: "blur" },
          { required: true, message: "请输入身份编码", validator: this.spaceJudgment, trigger: "blur" }
        ],
        postSort: [
          { required: true, message: "请输入身份顺序", trigger: "blur" },
          { required: true, message: "请输入身份顺序", validator: this.spaceJudgment, trigger: "blur" }
        ],
        roleIds: [
          { required: true, message: "请选择权限组", trigger: "blur" },
          { required: true, message: "请选择权限组", validator: this.spaceJudgment, trigger: "blur" }
        ]
      },
      //权限组列表
      optionselectList:[],
    };
  },
  created() {
    this.getList();
    this.systemRoleDropList();
  },
  methods: {
    //更多选项
    moreClick(item){
      let self = this;
      if(item.command == 1){
        this.handleUpdate(item.row)
      }else if(item.command == 2){
        this.$confirm('是否确认删除身份?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          self.handleDelete(item.row)
        }).then(() => {
        }).catch(() => {});
      }
    },
    clickPage(type){
      if(this.pageType != type){
        this.pageType = type;
      }
    },
    /** 查询身份列表 */
    getList() {
      let self = this;
      this.loading = true;
      systemPostList(this.queryParams).then(response => {
        for(let i=0;i<response.data.records.length;i++){
          let roleIds = response.data.records[i].roleIds?response.data.records[i].roleIds.split(','):[];
          let roleName = '';
          for(let o=0;o<roleIds.length;o++){
            for(let x=0;x<self.optionselectList.length;x++){
              if(roleIds[o] == self.optionselectList[x].roleId){
                roleName = roleName + (roleName[0]?'，':'') + self.optionselectList[x].roleName
              }
            }
          }
          response.data.records[i].roleNameStr = roleName;
        }
        this.postList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    //角色下拉列表
    systemRoleDropList(){
      systemRoleDropList({pageSize:100}).then(response => {
          this.$set(this,'optionselectList',response.data);
        }
      );
    },
    // 身份状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        postId: undefined,
        postCode: undefined,
        postName: undefined,
        postSort: 0,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.searchValue='';
      // this.resetForm("queryForm");
      this.$set(this,'queryParams',{
        page: 1,
        pageSize:20,
        searchValue:"",
      });
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增身份";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      systemPostDetail({postId:row.postId}).then(response => {
        if(response.data.roleIds){
          response.data.roleIds = response.data.roleIds.split(',')
          // for(let i=0;i<response.data.roleIds.length;i++){
          //   response.data.roleIds[i] = parseInt(response.data.roleIds[i]);//字符串转数字
          // }
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改身份";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      let self = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.form))
          let roleList = [];
          obj.roleIds.forEach((item)=>{
            self.optionselectList.forEach((minItem)=>{
              if(item == minItem.roleId){
                roleList.push(item);
              }
            })
          })
          obj.roleIds = roleList+'';
          if (this.form.postId != undefined) {
            systemPostUpdate(obj).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            systemPostAdd(obj).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      systemPostDelete({postId:row.postId}).then(response => {
        this.getList();
        this.msgSuccess("删除成功");
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
  .post-page{
    .post-page-min{
      .button-box{
        width:340px;
        display: flex;
      }
    }
  }
</style>
