/**
 * @Author: Sun Rising
 * @Date: 2019-12-20 09:56:37
 * @Last Modified by: Myz
 * @Last Modified time: 2020-11-23 13:34:27
 * @Description: 岸基权限
 */
<template>
  <div class="box-body"
       v-loading="loadingList">
    <div class="search-box">
      <el-button type="primary"
                 @click="addJump">添加职务</el-button>
      <div class="search-info">
        <span>公司：</span>
        <el-select v-model="page.underCompId"
                   @change="underCompIdChange"
                   placeholder="请选择"
                   clearable>
          <el-option v-for="item in companyList"
                     :key="item.compId"
                     :label="item.compName"
                     :value="item.compId" />
        </el-select>
        <span>部门：</span>
        <el-select v-model="page.deptId"
                   @change="getList"
                   placeholder="请选择"
                   clearable>
          <el-option v-for="item in deptList"
                     :key="item.deptId"
                     :label="item.deptName"
                     :value="item.deptId" />
        </el-select>
      </div>
    </div>
    <el-table stripe
              :data="authList"
              @cell-mouse-enter="enterMouse"
              height="58.5vh">
      <el-table-column prop="no"
                       label="序号"
                       width="80"
                       align="center">
        <template slot-scope="scope">
          {{(page.currentPage - 1)*page.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="roleName"
                       label="职务名称"
                       width="200" />
      <el-table-column prop="deptName"
                       label="所属部门" />
      <el-table-column prop="underCompName"
                       label="所属公司" />
      <el-table-column prop="serviceNames"
                       label="职责范围">
        <template slot-scope="scope">
          <el-tooltip effect="light"
                      show-overflow-tooltip
                      visible-arrow
                      :content="scope.row.serviceNames"
                      placement="top-start">
            <span>{{scope.row.serviceNames?scope.row.serviceNames:'--'}}</span>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop
                       label="操作"
                       width="100"
                       align="center">
        <yh-operaction :lable="lable"
                       @skip="skipPage" />
      </el-table-column>
    </el-table>
    <pagination v-show="total>0"
                :total="total"
                :page.sync="page.currentPage"
                :limit.sync="page.pageSize"
                @pagination="getList" />

    <!--添加编辑职务-->
    <el-dialog v-loading="loadingSave"
               :title="deptTitle"
               :visible.sync="addCompanyFlag"
               width="800px"
               center
               :close-on-click-modal="false"
               @close="cancel">
      <div class="two-form">
        <el-form v-if="addCompanyFlag"
                 ref="addDeptInfo"
                 :rules="addDeptInfoRules"
                 :model="addDeptInfo">
          <el-form-item label="职务名称"
                        prop="roleName">
            <el-input maxlength="50"
                      v-model="addDeptInfo.roleName"
                      placeholder="请输入" />
          </el-form-item>
          <el-form-item label="所属公司"
                        prop="underCompId">
            <el-select v-model="addDeptInfo.underCompId"
                       placeholder="请选择"
                       @change="underCompIdFormChange">
              <el-option v-for="item in companyList"
                         :key="item.compId"
                         :label="item.compName"
                         :value="item.compId" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门"
                        prop="deptId">
            <el-select v-model="addDeptInfo.deptId"
                       placeholder="请选择">
              <el-option v-for="item in formDeptList"
                         :key="item.deptId"
                         :label="item.deptName"
                         :value="item.deptId" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer"
            class="dialog-footer">
        <el-button type="primary"
                   @click="saveAdd(false)">保存并继续新建</el-button>
        <el-button type="primary"
                   @click="saveAdd(true)">保 存</el-button>
        <el-button @click="cancel();addCompanyFlag=false">取 消</el-button>
      </span>
    </el-dialog>

    <!--编辑职务范围-->
    <el-dialog title="设置职责范围"
               :visible.sync="addRoleRanFlag"
               width="800px"
               center
               :close-on-click-modal="false">
      <div class="two-form"
           v-if="!loadingRoleRan">
        <el-menu v-if="addRoleRanFlag"
                 class="el-menu-vertical-demo"
                 ref="jobScopeMenu"
                 :default-openeds='defaultOpeneds'>
          <el-submenu v-for="(item,val) in queryList"
                      :key="val"
                      :index="item.pluginId"
                      class="one-menu">
            <template slot="title">
              <i class="el-icon-caret-right"></i>
              <span>{{ item.pluginName }}</span>
            </template>
            <!-- {{item.activatedServices}} -->
            <el-submenu v-for="service in item.activatedServices"
                        :key="service.serviceId"
                        :index="service.serviceId"
                        class="two-menu">
              <template slot="title">
                <i class="el-icon-caret-right-two-menu" />
                <span @click.stop="allSelect(service)">
                  <el-checkbox disabled
                               v-if="service.featureCheckeds.length!==service.features.length"
                               :indeterminate="service.featureCheckeds.length>0"
                               :value="false"></el-checkbox>
                  <el-checkbox disabled
                               v-else
                               :indeterminate="false"
                               :value="true"></el-checkbox>
                  {{ service.serviceName }}
                </span>
              </template>

              <el-checkbox-group v-model="service.featureCheckeds">
                <el-menu-item v-for="feature in service.features"
                              :key="feature.featureId"
                              :index="feature.featureId">
                  <el-checkbox :label='feature.featureId'>{{ feature.featureName }}</el-checkbox>
                </el-menu-item>
              </el-checkbox-group>
            </el-submenu>
          </el-submenu>
        </el-menu>
      </div>
      <div v-else
           v-loading="true"></div>
      <span slot="footer"
            class="dialog-footer">
        <el-button :disabled="queryList.length===0"
                   type="primary"
                   @click="saveRoleRan">保 存</el-button>
        <el-button :disabled="queryList.length===0"
                   @click="addRoleRanFlag=false">取 消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import shoreApi from "../../api/organization/shore";
import Pagination from "../../components/Pagination";
import yhOperaction from "../../layout/components/operaction.vue";

export default {
  name: "shoreAuth",
  components: {
    Pagination,
    yhOperaction
  },
  data () {
    return {
      loadingRoleRan: false,
      defaultOpeneds: [],
      queryList: [],
      formDeptList: [],
      addRoleRanFlag: false,
      authList: [],
      addDeptInfo: {
        vesselBankFlag: "B",
        deptId: "",
        roleName: "",
        compId: ""
      },
      addDeptInfoRules: {
        roleName: [{ required: true, trigger: "blur" }],
        underCompId: [{ required: true, trigger: "blur" }],
        deptId: [{ required: true, trigger: "change" }]
      },
      page: {
        compId: localStorage.getItem("enterprise-front-companyId"),
        pageSize: 10,
        currentPage: 1,
        vesselBankFlag: "B",
        underCompId: "",
        deptId: ""
      },
      deptList: [],
      companyList: [],
      deptTitle: "",
      addCompanyFlag: false,
      loadingSave: false,
      total: 0,
      msgRow: "",
      currRow: null
    };
  },
  computed: {
    lable () {
      return [
        {
          lab: "编辑",
          click: "editBtn"
        },
        {
          lab: "设置职责范围",
          click: "roleRan"
        },
        {
          lab: "删除",
          click: "deleteBtn"
        }
      ];
    },
    compTypeList () {
      return [
        {
          constValue: "船东及船管",
          constKey: "1"
        },
        {
          constValue: "船东",
          constKey: "2"
        },
        {
          constValue: "船管",
          constKey: "3"
        }
      ];
    }
  },
  async created () {
    await this.initDict();
  },
  methods: {
    // 初始化插件树
    async initPluginDetails () {
      try {
        this.loadingRoleRan = true;
        if (this.queryList.length === 0) {
          // 获取插件列表;
          const resp4 = await shoreApi.getTenantlist({
            tenantId: localStorage.getItem("enterprise-front-tenantId")
          });
          resp4.forEach((value, index) => {
            value.activatedServices.forEach((value2, index2) => {
              value2.featureCheckeds = [];
            });
          });
          this.$set(this, "queryList", resp4);
        }
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      }
    },
    // getResources (data) {
    //   let str = "";
    //   data.forEach(item => {
    //     str = str + item.resourceName + " | ";
    //   });
    //   if (str) {
    //     str = str.substring(0, str.length - 3);
    //   } else {
    //     str = " -- ";
    //   }
    //   return str;
    // },
    // 公司改变 动态部门
    async underCompIdChange (key) {
      try {
        if (!key) {
          this.getList();
          return;
        }
        let resp = await shoreApi.getDeptPageByCompId({
          underCompId: key,
          vesselBankFlag: "B"
        });
        this.page.deptId = "";
        this.$set(this, "deptList", resp.records);
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      } finally {
        this.getList();
      }
    },
    // 公司改变 表单
    async underCompIdFormChange (key) {
      try {
        if (!key) return;
        let resp = await shoreApi.getDeptPageByCompId({
          underCompId: key,
          vesselBankFlag: "B"
        });
        this.addDeptInfo.deptId = "";
        this.formDeptList = resp.records;
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      } finally {
      }
    },
    // 保存权限范围
    async saveRoleRan () {
      try {
        const roleId = this.currRow.roleId;
        const resources = [];
        this.queryList.forEach((value, index) => {
          value.activatedServices.forEach((value2, index2) => {
            value2.featureCheckeds.forEach((value3, index3) => {
              resources.push({ resourceId: value3 });
            });
          });
        });
        const data = {
          roleId,
          resources
        };
        await shoreApi.bindResources(data);
        this.$message({
          message: "保存成功!",
          type: "success"
        });
        this.addRoleRanFlag = false;
        this.getList();
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      }
    },
    // 鼠标移入获取当前行信息
    enterMouse (row, column, cell, event) {
      this.msgRow = row;
    },
    // 操作下拉
    skipPage (msg) {
      if (msg === "editBtn") {
        this.getEdit(this.msgRow);
      } else if (msg === "deleteBtn") {
        this.getDelete(this.msgRow);
      } else if (msg === "roleRan") {
        this.showRoleRan(this.msgRow);
      }
    },
    async showRoleRan (row) {
      this.addRoleRanFlag = true;
      try {
        await this.initPluginDetails();
        let resp = await shoreApi.getRoleInfo({ roleId: row.roleId });
        this.currRow = resp;
        let _defaultOpeneds = [];
        this.queryList.forEach(value => {
          value.activatedServices.forEach(value2 => {
            const _featureCheckeds = [];
            this.currRow.resources.forEach(value3 => {
              value2.features.forEach(value4 => {
                if (value4.featureId === value3.resourceId)
                  _featureCheckeds.push(value3.resourceId);
              });
            });
            if (_featureCheckeds.length > 0) {
              _defaultOpeneds.push(value2.serviceId);
              _defaultOpeneds.push(value.pluginId);
            }
            this.$set(value2, "featureCheckeds", _featureCheckeds);
          });
        });
        this.$set(this, "defaultOpeneds", _defaultOpeneds);
        this.loadingRoleRan = false;
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      }
    },
    // 删除
    getDelete (row) {
      this.$confirm("确认要删除该职务吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          shoreApi
            .delRole({ roleIds: [row.roleId] })
            .then(response => {
              this.$message({
                type: "success",
                message: "删除成功"
              });
              this.getList();
            })
            .catch(err => {
              if (err.code && err.code !== "200") {
                this.$message(err.message);
              }
              console.log(err);
            });
        })
        .catch(() => { });
    },
    // 编辑
    async getEdit (row) {
      this.addDeptInfo = JSON.parse(JSON.stringify(row));
      this.deptTitle = "编辑职务";
      await this.underCompIdFormChange(row.underCompId);
      this.addDeptInfo.deptId = row.deptId;
      this.addCompanyFlag = true;
    },
    cancel () {
      // this.addCompanyFlag = false;
      this.loadingSave = false;
      this.$refs.addDeptInfo.resetFields();
      this.addDeptInfo = {
        vesselBankFlag: "B",
        deptId: "",
        roleName: "",
        compId: "",
        deptId: ""
      };
    },
    getSelectLabel () {
      this.addDeptInfo.underCompName = this.companyList.find(
        item => item.compId === this.addDeptInfo.underCompId
      ).compName;
    },
    saveAdd (is) {
      this.$refs.addDeptInfo.validate(valid => {
        if (valid) {
          this.loadingSave = true;
          this.getSelectLabel();
          if (this.addDeptInfo.roleId) {
            shoreApi
              .editRole(this.addDeptInfo)
              .then(response => {
                if (is) this.addCompanyFlag = false;
                this.cancel();
                this.$message({
                  message: "修改成功",
                  type: "success"
                });
                this.getList();
              })
              .catch(err => {
                this.loadingSave = false;
                if (err === "MANAGEMENT_004") {
                  this.$message({
                    type: "error",
                    message: "角色名已存在！",
                    showClose: true
                  });
                  return false;
                }
                if (err === "MANAGEMENT-005") {
                  this.$message({
                    type: "error",
                    message: "角色英文名已存在！",
                    showClose: true
                  });
                  return false;
                }
              });
          } else {
            shoreApi
              .createRole(this.addDeptInfo)
              .then(response => {
                  if (is) this.addCompanyFlag = false;
                  this.cancel();
                  this.$message({
                    message: "保存成功",
                    type: "success"
                  });
                  this.getList();
              })
              .catch(err => {
                this.loadingSave = false;
                // this.$message.error(err.message)
              });
          }
        } else {
          this.$message({
            message: "带*号的为必填项！",
            type: "error"
          });
          return false;
        }
      });
    },
    addJump () {
      this.deptTitle = "添加职务";
      const t = Object.assign({}, this.addDeptInfo, {
        vesselBankFlag: "B",
        roleName: "",
        compId: "",
        deptId: ""
      });
      this.$set(this, "addDeptInfo", t);
      this.addCompanyFlag = true;
    },
    getClear () {
      this.page.underCompId = null;
      this.getList();
    },
    async getList () {
      try {
        this.loadingList = true;
        // 获取权限列表
        const resp3 = await shoreApi.company(this.page);
        this.authList = resp3.records;
        this.total = resp3.total;
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      } finally {
        this.loadingList = false;
      }
    },
    async initDict () {
      try {
        this.loadingList = true;
        // 获取公司
        const resp = await shoreApi.compAndChildrenInfo();
        resp[0].children.unshift({
          compId: resp[0].compId,
          compName: resp[0].compName
        });
        this.companyList = resp[0].children;
        await this.getList();
      } catch (error) {
        if (error.code && error.code !== "200") this.$message(error.message);
      } finally {
        this.loadingList = false;
      }
    },
    allSelect (data) {
      const sour = data.features;
      const selected = data.featureCheckeds;
      if (sour.length !== selected.length) {
        const _selected = [];
        sour.forEach((value, index) => {
          _selected.push(value.featureId);
        });
        this.$set(data, "featureCheckeds", _selected);
      } else {
        this.$set(data, "featureCheckeds", []);
      }
    }
  }
};
</script>
<style scoped lang="scss">
.el-menu-vertical-demo {
  width: 100%;
  border-width: 0px;
  & > li {
    background-color: #f6f6f6;
    margin: 2px;
    & > ul > li {
      border-bottom: 1px dashed #cccccc;
      & > ul li {
        display: inline-block;
        width: 20%;
      }
    }
  }
}
.two-form {
  max-height: 600px;
  overflow: auto;
}
/deep/.el-checkbox__input.is-disabled .el-checkbox__inner {
  cursor: auto !important;
  background-color: #fff;
}
/deep/.el-checkbox__input.is-checked .el-checkbox__inner,
/deep/.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #1d6ced !important;
  border-color: #1d6ced !important;
}
/deep/.el-submenu__title {
  height: 40px;
  line-height: 40px;
}
.el-checkbox {
  margin-right: 10px;
}
.one-menu {
  .el-submenu__title {
    background-color: #f6f6f6;
  }
}
.two-menu {
  .el-menu {
    border-bottom: 1px dashed #ccc;

    .el-menu-item {
      .el-checkbox {
        width: 23%;
      }
    }
  }

  .el-submenu__title {
    border-bottom: 1px dashed #ccc;
    background-color: #fff;
  }
}
.one-menu.is-opened .el-icon-caret-right {
  -webkit-transform: rotateZ(90deg);
  -moz-transform: rotateZ(90deg);
  -o-transform: rotateZ(90deg);
  -ms-transform: rotateZ(90deg);
  transform: rotateZ(90deg);
}

.el-icon-caret-right-two-menu:before {
  // content: "\E60E";
  content: "\E791";
}

.two-menu.is-opened .el-icon-caret-right-two-menu {
  -webkit-transform: rotateZ(90deg);
  -moz-transform: rotateZ(90deg);
  -o-transform: rotateZ(90deg);
  -ms-transform: rotateZ(90deg);
  transform: rotateZ(90deg);
}
.select-all {
  color: blue;
  display: inline-block;
  font-size: 12px;
  margin-left: 10px;
}
</style>
