<template>
  <div class="app-container enterprise-management-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="请输入企业名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="用户名称" prop="contactUserName">
        <el-input v-model="queryParams.contactUserName" placeholder="请输入用户名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号码" prop="contactPhone">
        <el-input v-model="queryParams.contactPhone" placeholder="请输入手机号码" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="账号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="角色状态" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.sys_user_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </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">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantList" @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="companyName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="用户名称" prop="contactUserName" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="手机号码" prop="contactPhone" width="120" />
      <el-table-column label="企业方案" prop="packageName" />
      <el-table-column label="续约开始时间" prop="startTime" />
      <el-table-column label="续约结束时间" prop="expireTime" />
      <el-table-column label="账号状态" align="center" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_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" fixed="right" width="300">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleSync(scope.row)">同步</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleAddAccount(scope.row)">添加账号</el-button>
          <el-button size="mini" type="text" icon="el-icon-zoom-in" @click="handleLook(scope.row)">查看</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="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业名称" prop="companyName">
              <el-input :disabled="disabled" v-model="form.companyName" placeholder="请输入企业名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="contactUserName">
              <el-input :disabled="disabled" v-model="form.contactUserName" placeholder="请输入用户名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="续约时间" prop="dateRange">
              <el-date-picker :disabled="disabled" v-model="form.dateRange" style="width: 100%" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="contactPhone">
              <el-input :disabled="disabled" v-model="form.contactPhone" placeholder="请输手机号码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="企业方案" prop="packageId">
              <el-select :disabled="disabled" v-model="form.packageId" placeholder="企业方案" clearable style="width: 100%">
                <el-option v-for="dict in packageList" :key="dict.packageId" :label="dict.packageName" :value="dict.packageId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业规模" prop="accountCount">
              <el-input onkeyup="this.value=this.value.replace(/[^0-9]/g,'')" :disabled="disabled" v-model="form.accountCount" placeholder="请输入企业规模" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status" :disabled="disabled">
                <el-radio v-for="dict in dict.type.sys_user_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </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>

    <el-dialog title="权限同步" :visible.sync="dialogVisible1" custom-class="sync" width="400px">
      <p style="font-size: 16px;"><i class="el-icon-warning-outline" style="margin-right: 8px;"></i>是否确认同步？</p>
      <p>温馨提示：此操作可能会影响正在使用的用户，建议合理安排同步时间</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm()" :loading="state">同步</el-button>
      </div>
    </el-dialog>

    <!-- 添加账号 -->
    <enterprise-add-account :openStatus="addAccountDialog" :enterpriseInfo="addAccountEnterpriseInfo" @dialogClose="enterpriseDialogClose"
      :addAccountCount="addAccountCount"></enterprise-add-account>

  </div>
</template>

<script>
import {
  deleteTenant,
  editTenant,
  getTenant,
  getTenantList,
  saveTenant,
  selectTenant,
  syncTenantPackage,
  getEnterpriseAddAccountCountApi
} from '@/api/enterpriseManagement/enterpriseManagement';

import EnterpriseAddAccount from "./components/EnterpriseAddAccount";

export default {
  name: "EnterpriseManagement",
  dicts: ['sys_user_status'],
  components: {
    EnterpriseAddAccount
  },
  data() {
    return {
      disabled: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业表格数据
      tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogVisible1: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
        contactPhone: undefined,
        contactUserName: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contactPhone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        contactUserName: [
          { required: true, message: "用户名称不能为空", trigger: "blur" }
        ],
        companyName: [
          { required: true, message: "企业名称不能为空", trigger: "blur" }
        ],
        packageId: [
          { required: true, message: "企业方案不能为空", trigger: "blur" }
        ],
        dateRange: [
          { required: true, message: "续约时间不能为空", trigger: "blur" }
        ],
        accountCount: [
          { required: true, message: "企业规模不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "账号状态不能为空", trigger: "blur" }
        ],
      },
      //企业方案列表
      packageList: [],
      syncItem: {},
      state: false,
      // 添加账号弹窗
      addAccountDialog: false,
      // 企业信息
      addAccountEnterpriseInfo: {},
      // 该租户下已经创建账号数量 默认1个
      addAccountCount: 1
    };
  },
  created() {
    this.getList();
  },
  methods: {
    enterpriseDialogClose() {
      this.addAccountDialog = false;
      this.getAccountCount(this.addAccountEnterpriseInfo.tenantId);
      this.addAccountEnterpriseInfo = this.$options.data.call(this).addAccountEnterpriseInfo;
    },
    async getAccountCount(tenantId) {
      try {
        const countResult = await getEnterpriseAddAccountCountApi(tenantId);
        if (countResult.code == 200) {
          this.addAccountCount = countResult.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 新增用户账号
    async handleAddAccount(row) {
      try {
        if (row.status == "1") return this.$message.warning("该企业账号已过期，不能添加用户");
        if (!row.tenantId) return this.$message.warning("缺少租户ID");
        await this.getAccountCount(row.tenantId);
        if (this.addAccountCount >= 6) {
          return this.$message.warning("该租户下已经添加过五个账号");
        }
        this.addAccountEnterpriseInfo = row;
        this.addAccountDialog = true;
      } catch (error) {
        console.log(error);
      }
    },
    //获取企业方案列表
    getpack() {
      selectTenant().then(res => {
        if (res.code = 200) {
          this.packageList = res.data;
          // this.packageList.forEach(item=>{
          //   if(item.status == '0'){
          //     item.disabled = false
          //   }else{
          //     item.disabled = true
          //   }
          // })
        }
      });
    },
    /** 查询角色列表 */
    getList() {
      this.loading = true;
      getTenantList(this.queryParams).then(response => {
        this.tenantList = response.rows ? response.rows : [];
        this.total = response.total ? response.total : 0;
        this.loading = false;
      }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dateRange: undefined,
        id: undefined,
        tenantId: undefined,
        contactUserName: undefined,
        contactPhone: undefined,
        companyName: undefined,
        packageId: undefined,
        accountCount: undefined,
        status: "0",
      };
      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.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.disabled = false;
      this.reset();
      this.open = true;
      this.title = "添加企业";
      this.getpack();
    },
    /** 同步弹窗显示 */
    handleSync(row) {
      this.dialogVisible1 = true;
      this.syncItem = row;
    },
    /** 同步按钮操作 */
    handleConfirm() {
      let _this = this;
      this.state = true;
      syncTenantPackage({ tenantId: this.syncItem.tenantId, packageId: this.syncItem.packageId }).then(res => {
        if (res.code === 200) {
          this.state = false;
          _this.$message.success(res.msg);
          this.dialogVisible1 = false;
        }

      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.disabled = false;
      this.reset();
      const id = row.id;
      this.getpack();
      getTenant(id).then(response => {
        this.form = response.data;
        this.form.dateRange = [response.data.startTime, response.data.expireTime];
        this.open = true;
        this.title = this.disabled == true ? '查看企业' : "修改企业";
      });
    },
    //查看
    handleLook(row) {
      this.handleUpdate(row);
      this.disabled = true;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const text = this.form.id ? "正在修改企业数据,请耐心等待" : "正在添加企业数据,请耐心等待";
          const loading = this.$loading({
            lock: true,
            text,
          });
          this.form.startTime = this.form.dateRange[0];
          this.form.expireTime = this.form.dateRange[1];
          let thistime = new Date(this.form.expireTime).getTime();
          if (thistime < new Date().getTime()) {
            this.$message.error('不能选择过去时间！');
            return false;
          }
          if (this.form.id != undefined) {
            editTenant(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess('修改成功');
                this.open = false;
                this.getList();
                loading.close();
              } else {
                this.$modal.msgError(response.msg);
                loading.close();
              }
            }).catch(response => {
              this.$modal.msgError(response.msg);
              loading.close();
            });
          } else {
            saveTenant(this.form).then(response => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
                loading.close();
              } else {
                this.$modal.msgError(response.msg);
                loading.close();
              }
            }).catch(response => {
              this.$modal.msgError(response.msg);
              loading.close();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const Ids = row.id || this.ids;
      let _this = this;
      this.$modal.confirm('是否确认删除选中的企业数据项？').then(function () {
        deleteTenant(Ids).then(res => {
          if (res.code == 200) {
            _this.getList();
            _this.$message.success("删除成功");
          } else {
            _this.$message.error(res.msg);
          }
        });
      }).catch(() => { });
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .sync {
  .el-dialog__header {
    border-bottom: 1px solid #eee;
  }

  .el-dialog__body {
    padding: 15px 20px;
  }
}

.enterprise-management-container {
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 16px 24px;
  box-sizing: border-box;
  position: absolute;
  top: 0;
  left: 0;
  overflow: auto;
}
</style>

