<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="方案名称" prop="packageName">
        <el-input
          v-model="queryParams.packageName"
          placeholder="请输入方案名称"
          clearable
          style="width: 240px"
          @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-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="['system:role:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="packList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column  label="序号" width="60">
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) *queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="方案名称" prop="packageName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="备注" prop="remark" width="400">
      <template slot-scope="scope">
        <el-popover
          title=""
          :visible-arrow="false"
          width="400"
          trigger="hover"
          popper-class="popovers"
          :content="scope.row.remark">
          <div class="over" slot="reference">{{scope.row.remark}}</div>
        </el-popover>

      </template>
      </el-table-column>
      <el-table-column label="方案状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ent_pro_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-zoom-in"
            @click="handleLook(scope.row)"
            v-hasPermi="['system:role:edit']"
          >查看</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-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="方案名称" prop="packageName">
          <el-input :disabled="disabled" v-model="form.packageName" placeholder="请输入方案名称" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio :disabled="disabled" v-model="form.status" label="0">正常</el-radio>
          <el-radio :disabled="disabled" v-model="form.status" label="1">停用</el-radio>
        </el-form-item>
        <el-form-item label="角色授权" prop="menuIds">
          <el-checkbox :disabled="disabled" v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox :disabled="disabled" v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
          <el-checkbox :disabled="disabled" v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</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-tree>
        </el-form-item>
        <el-form-item label="备注">
          <el-input :disabled="disabled" v-model="form.remark" maxlength="50" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!disabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { treeselect as qytreeselect} from "@/api/system/menu";


  import { addTenantPackage ,getTenantPackage,detailTenantPackage,saveTenantPackage,deleteTenantPackage} from "@/api/enterpriseManagement/enterpriseManagement";

  export default {
    name: "Programme",
    dicts: ['ent_pro_status'],
    data() {
      return {
        disabled:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 方案表格数据
        packList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        menuExpand: false,
        menuNodeAll: false,
        deptExpand: true,
        // 日期范围
        dateRange: [],
        // 菜单列表
        menuOptions: [],
        // 部门列表
        deptOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          packageName:'',
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label",
          disabled:this.disabledFn
        },
        // 表单校验
        rules: {
          packageName: [
            { required: true, message: "套餐名称不能为空", trigger: "blur" }
          ],
          status: [
            { required: true, message: "状态不能为空", trigger: "blur" }
          ],
          menuIds: [
            { required: true, message: "权限不能为空", trigger: "blur" }
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getMenuTreeselect();
    },
    methods: {
      disabledFn(){
        return this.disabled
      },
      /** 查询方案列表 */
      getList() {
        this.loading = true;
        getTenantPackage(this.queryParams).then(response => {
            this.packList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        qytreeselect().then(response => {
          this.menuOptions = response.data;
        });
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
        this.menuExpand = false,
          this.menuNodeAll = false,
          this.deptExpand = true,
          this.form = {
            packageId: undefined,
            packageName: undefined,
            remark: undefined,
            menuCheckStrictly:true,
            status: "0",
            menuIds: [],
          };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.packageId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      // 树权限（展开/折叠）
      handleCheckedTreeExpand(value, type) {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      },
      // 树权限（全选/全不选）
      handleCheckedTreeNodeAll(value, type) {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions: []);
      },
      // 树权限（父子联动）
      handleCheckedTreeConnect(value, type) {
        if (type == 'menu') {
          this.form.menuCheckStrictly = value ? true: false;
        } else if (type == 'dept') {
          this.form.deptCheckStrictly = value ? true: false;
        }
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.disabled = false
        this.reset();
        this.open = true;
        this.title = "添加方案";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.disabled = false
        this.reset();
        const packageId = row.packageId
        detailTenantPackage(packageId).then(response => {
          response.data.menuIds = response.data.menuIds.split(',')
          this.form = response.data;
          this.open = true;
              this.$nextTick(() => {
                let checkedKeys = response.data.menuIds
                // menuOptions

                checkedKeys.forEach((v) => {
                  v = v.trim()
                  let nodes = this.$refs.menu.getNode(v)
                  if(nodes.isLeaf && nodes.isLeaf == true){
                    this.$refs.menu.setChecked(v,true,true);
                  }else{
                    this.$refs.menu.setChecked(v,true,false);
                  }
                })
              })
          this.title = this.disabled == true?'查看方案':"修改方案";
        });
      },
      //查看
      handleLook(row){
        this.handleUpdate(row)
        this.disabled = true
      },
      /** 提交按钮 */
      submitForm: function() {
        this.form.menuIds = this.getMenuAllCheckedKeys();
        this.$refs["form"].validate(valid => {
          if (valid) {
            // return false
            if (this.form.packageId != undefined) {
              saveTenantPackage(this.form).then(response => {
                if(response.code == 200){
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }else{
                  this.$message.error(response.msg)
                }
              });
            } else {
              // this.form.menuIds = this.getMenuAllCheckedKeys();
              addTenantPackage(this.form).then(response => {
                if(response.code == 200){
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }else{
                  this.$message.error(response.msg)
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const packageIds = row.packageId || this.ids;
        let _this = this
        this.$modal.confirm('是否确认删除选中的方案数据项？').then(function() {
          deleteTenantPackage(packageIds).then(res=>{
            if(res.code == 200){
              _this.getList();
              _this.$message.success("删除成功");
            }else{
              _this.$message.error(res.msg);
            }
          });
        }).catch(() => {});
      },
    }
  };
</script>

<style scoped lang="scss">
  .over{
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
</style>
<style lang="scss">
  .popovers {
    padding: 6px 12px !important;
    line-height: 20px;
    color: rgba(35, 35, 35, 0.80);
    font-size: 12px;
  }
</style>
