<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="企业名称" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入企业名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="企业编码" prop="tenantCode">
        <el-input
          v-model="queryParams.tenantCode"
          placeholder="请输入企业编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item label="类型" prop="tenantType">
        <el-select v-model="queryParams.tenantType" placeholder="请选择类型" clearable size="small">
          <el-option
            :label="item.dictLabel"
            v-for="item in tenantTypeOptions"
            :key="item.dictValue"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="租户状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="用户状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="有效期" prop="expirationTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.expirationTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择有效期"
        ></el-date-picker>
      </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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:tenant:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:tenant:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:tenant:remove']"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:tenant:export']"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="tenantList"
      :default-sort="{prop: 'expirationTime', order: 'descending'}"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="企业名称" align="center" sortable="custom" prop="tenantName" />
      <el-table-column label="企业编码" align="center" sortable="custom" prop="tenantCode" />
      <el-table-column label="类型" align="center" prop="tenantType" :formatter="tenantTypeFormat" />
      <el-table-column label="租户状态" align="center" :formatter="statusFormat" width="80" />

      <el-table-column
        label="有效期"
        sortable="custom"
        align="center"
        prop="expirationTime"
        width="160"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expirationTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">

          <buttons-set :option="bottonOption" :btnData="btnData()" :scope="scope"></buttons-set>
        </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"
      class="eldialog-wrap"
      :visible.sync="open"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="企业名称:" prop="tenantName">
          <el-input v-model="form.tenantName" placeholder="请输入企业名称" />
        </el-form-item>

        <el-form-item label="企业编码:" prop="tenantCode">
          <el-input v-model="form.tenantCode" placeholder="请输入企业编码" />
        </el-form-item>

        <el-form-item label="类型:">
          <el-select v-model="form.tenantType" style="width: 100%;" placeholder="请选择类型">
            <el-option
              :label="item.dictLabel"
              v-for="item in tenantTypeOptions"
              :key="item.dictValue"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="租户状态:">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="有效期:" prop="expirationTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 100%"
            v-model="form.expirationTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择有效期"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="企业法人:">
          <el-input v-model="form.corporation" placeholder="请输入企业法人" />
        </el-form-item>

        <el-form-item label="营业执照:">
          <upload-image
            :fileType="fileType"
            :imageUrl="form.businessLicense"
            compStyle="height: 100px; width: 100px;"
            @eventUrl="(data) => {form.businessLicense = data}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配用户租户对话框 -->
    <el-dialog
      :title="title_user"
      class="teant-child-dialog"
      :visible.sync="open_user"
      width="80%"
      :close-on-click-modal="false"
      append-to-body
    >
      <dis-user v-if="tempType === 'disUser'" :tenantId="tenantId"></dis-user>

      <dis-role v-else-if="tempType === 'disRole'" :tenantId="tenantId"></dis-role>

      <dis-post v-else-if="tempType === 'disPost'" :tenantId="tenantId"></dis-post>

      <dis-menu v-else-if="tempType === 'disMenu'" :tenantId="tenantId"></dis-menu>

      <dis-dept v-else-if="tempType === 'disDept'" :tenantId="tenantId"></dis-dept>

      <!-- <ts-config v-else-if="tempType === 'tsConfig'" :tenantId="tenantId"></ts-config>

      <ts-policy v-else-if="tempType === 'tsPolicy'" :tenantId="tenantId"></ts-policy>

      <msg-config v-else-if="tempType === 'smsTemp'" :tenantId="tenantId"></msg-config>

      <sms-firm v-else-if="tempType === 'smsFirm'" :tenantId="tenantId"></sms-firm>

      <email-config v-else-if="tempType === 'emailConfig'" :tenantId="tenantId"></email-config>

      <email-temp v-else-if="tempType === 'emailTemp'" :tenantId="tenantId"></email-temp> -->

      <div slot="footer" class="dialog-footer">
        <el-button @click="open_user = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTenant,
  getTenant,
  delTenant,
  addTenant,
  updateTenant,
  exportRecord
} from "@/api/system/tenant";
import disUser from "./profile/disUser.vue";
import disRole from "./profile/disRole.vue";
import disPost from "./profile/disPost.vue";
import nlSelectTable from "./profile/nl_select_table.vue";
import UploadImage from "@/components/Upload/Image.vue";

import TsConfig from "./profile/tsConfig.vue";
import ButtonsSet from "./buttonSet.vue";
import TsPolicy from "./profile/tspolicy.vue";
import MsgConfig from "./profile/smsTemp.vue";
import SmsFirm from "./profile/smsFirm.vue";
import EmailConfig from "./profile/emailConfig.vue";
import EmailTemp from "./profile/emailTemp.vue";

import disMenu from "./profile/disMenu.vue";
import disDept from "./profile/disDept.vue";

import { listUser } from "@/api/system/user";
import { listRole } from "@/api/system/role";
import { listDept } from "@/api/system/dept";
import { listPost } from "@/api/system/post";
import { listMenu } from "@/api/system/menu";

export default {
  name: "Tenant",
  components: {
    nlSelectTable,
    disUser,
    disRole,
    disPost,
    disMenu,
    disDept,
    TsConfig,
    ButtonsSet,
    TsPolicy,
    MsgConfig,
    SmsFirm,
    EmailConfig,
    EmailTemp,
    UploadImage
  },
  data() {
    return {
      fileType: ["image/jpeg", "image/png"],
      tempType: "",
      tenantId: "",
      title_user: "用户管理",
      open_user: false,
      childTitle: "",
      childOpen: false,
      queryOption: {},
      tableOption: {},
      tableList: [],
      otherOption: {},
      childIds: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      title_select: "选择分配租户",
      open_select: false,
      // 总条数
      total: 0,
      // 企业租户表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型
      tenantTypeOptions: [],
      // 租户状态
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        tenantName: undefined,
        tenantCode: undefined,
        tenantType: undefined,
        status: undefined,
        expirationTime: undefined,
        orderByColumn: "expirationTime",
        isAsc: "desc"
      },
      bottonOption: {
        isHidden: true,
        showNum: 2,
        appendId: "#realpagetable_1",
        trigger: "click",
        placement: "top-start"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tenantName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" },
          {
            required: true,
            min: 2,
            max: 64,
            message: "企业名称长度在2-64",
            trigger: "blur"
          }
        ],
        tenantCode: [
          { min: 2, max: 8, message: "用户名称长度在2-8", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9]{2,8}$/,
            message: "允许字母数字",
            trigger: ["blur", "change"]
          }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    // 表格按钮初始化数据
    btnData() {
      var vm = this;
      return [
        {
          icon: "el-icon-edit",
          name: "修改",
          size: "mini",
          type: "text",
          qx: ["system:tenant:edit"],
          handler: function(scope) {
            vm.handleUpdate(scope.row);
          }
        },
        {
          icon: "el-icon-delete",
          name: "删除",
          size: "mini",
          type: "text",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleDelete(scope.row);
          }
        },
        {
          icon: "el-icon-edit",
          name: "用户",
          type: "text",
          size: "mini",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleAddChildUser(scope.row, "disUser", "租户管理");
          }
        },
        {
          icon: "el-icon-edit",
          name: "角色",
          size: "mini",
          type: "text",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleAddChildUser(scope.row, "disRole", "角色管理");
          }
        },
        {
          icon: "el-icon-edit",
          name: "菜单",
          size: "mini",
          type: "text",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleAddChildUser(scope.row, "disMenu", "菜单管理");
          }
        },
        {
          icon: "el-icon-edit",
          name: "部门",
          size: "mini",
          type: "text",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleAddChildUser(scope.row, "disDept", "部门管理");
          }
        },
        {
          icon: "el-icon-edit",
          name: "岗位",
          size: "mini",
          type: "text",
          qx: ["system:tenant:add"],
          handler: function(scope) {
            vm.handleAddChildUser(scope.row, "disPost", "岗位管理");
          }
        },
        // {
        //   icon: "el-icon-edit",
        //   name: "时序库",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "tsConfig", "时序库配置");
        //   }
        // },
        // {
        //   icon: "el-icon-edit",
        //   name: "策略",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "tsPolicy", "策略配置");
        //   }
        // },
        // {
        //   icon: "el-icon-edit",
        //   name: "短信厂商",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "smsFirm", "短信厂商");
        //   }
        // },
        // {
        //   icon: "el-icon-edit",
        //   name: "短信模板",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "smsTemp", "短信模板");
        //   }
        // },
        // {
        //   icon: "el-icon-edit",
        //   name: "邮件服务",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "emailConfig", "邮件服务");
        //   }
        // },
        // {
        //   icon: "el-icon-edit",
        //   name: "邮件模板",
        //   size: "mini",
        //   type: "text",
        //   qx: ["system:tenant:add"],
        //   handler: function(scope) {
        //     vm.handleAddChildUser(scope.row, "emailTemp", "邮件模板");
        //   }
        // }
      ];
    },
    // 初始加载页面默认属性
    init() {
      this.getDicts("sys_tenant_type").then(response => {
        this.tenantTypeOptions = response.data;
      });
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
    },
    // 类型字典翻译
    tenantTypeFormat(row, column) {
      var rulesStr = "";
      this.tenantTypeOptions.forEach(v => {
        if (v.dictValue === row.tenantType) {
          rulesStr = v.dictLabel;
        }
      });
      return rulesStr;
    },
    // 租户状态字典翻译
    statusFormat(row, column) {
      var rulesStr = "";
      this.statusOptions.forEach(v => {
        if (v.dictValue === row.status) {
          rulesStr = v.dictLabel;
        }
      });
      return rulesStr;
    },
    /** 查询企业租户列表 */
    getList() {
      this.loading = true;
      listTenant(this.queryParams).then(response => {
        this.tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        tenantId: undefined,
        tenantName: undefined,
        tenantCode: undefined,
        tenantType: undefined,
        status: "0",
        expirationTime: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined,
        corporation: "",
        businessLicense: ""
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tenantId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业租户";
    },
    // 添加子租户
    handleAddChildUser(row, type, title) {
      this.tenantId = row.tenantId;
      this.tempType = type;
      this.title_user = title;
      this.open_user = true;
    },

    // 勾选数据保存操作
    submitFileForm() {
      // 目前从选择到逻辑都是没有问题的，数据都到位了，就差接口
      // console.log(this.otherOption["inputType"], ":", this.childIds);
    } /** 修改按钮操作 */,
    handleUpdate(row) {
      this.reset();
      var tenantId;
      if (row.tenantId === 0) {
        tenantId = row.tenantId;
      } else {
        tenantId = row.tenantId || this.ids;
      }
      getTenant(tenantId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改企业租户";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tenantId != undefined) {
            updateTenant(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addTenant(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // console.log(row);
      const tenantIds = row.tenantId || this.ids;
      this.$confirm(
        // '是否确认删除序号为"' + tenantIds + '"的数据项?',
        "是否删除该选项",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delTenant(tenantIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // this.download(
      //   "system/tenant/export",
      //   {
      //     ...this.queryParams
      //   },
      //   `system_tenant.xlsx`
      // );
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出租户数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportRecord(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
<style lang="scss" scoped>
.teant-dialog {
  .el-select {
    width: 100%;
  }
}
.teant-child-dialog {
  .el-select {
    .el-dialog__body {
      padding: 5px 20px;
    }
  }
}
</style>
