<template>
  <div class="app-container">
    <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>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="project_tenantList"
      :default-sort="{prop: 'expirationTime', order: 'descending'}"
      @sort-change="sortChange"
    >
      <el-table-column type="index" label="序号" align="center" :index="indexFormatter" width="80px"></el-table-column>
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="phoneNumber" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span v-text="scope.row.status === '0' ? '正常' : '停用'"></span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        sortable="custom"
        prop="createTime"
        width="160"
      />
      <el-table-column
        label="操作"
        align="center"
        width="200px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(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="选择用户"
      :visible.sync="selectTableShow"
      width="50%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <select-table-wrap
        v-if="selectTableShow"
        :tableOption="tableSelectOption.tableOpt"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        @parentGetList="childGetList($event)"
        :otherOption="tableSelectOption.otherOption"
        @returnEvent="returnEvent($event)"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="() =>{selectTableShow = false}">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProjectUser,
  delProjectUser,
  addProjectUser,
  exportProjectUser,
  listProjectNotUsed
} from "@/api/tenant/projectUser";
import SelectTableWrap from "@/components/SelectTable/index";
export default {
  name: "ProjectTenant",
  components: {
    SelectTableWrap
  },
  props: ["infoData"],
  data() {
    return {
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目用户关系表格数据
      project_tenantList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "createTime",
        isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 用户状态
      statusOptions: [],
      tenantTypeOptions: []
    };
  },
  created() {
    this.getDicts("sys_tenant_type").then(response => {
      this.tenantTypeOptions = response.data;
    });
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getList();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    // 打开厂商选择窗口 ——表格
    handleDetails() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device"
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            projectId: this.infoData.projectId,
            tenantName: ""
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "用户昵称",
              clearable: true,
              label: "用户昵称",
              type: "input",
              key: "nickName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "用户昵称",
              type: "",
              prop: "nickName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "手机号码",
              type: "",
              prop: "phoneNumber",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "邮箱",
              type: "",
              prop: "email",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "创建时间",
              type: "time",
              prop: "createTime",
              align: "center",
              width: "180",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    childGetList(data) {
      listProjectNotUsed(Object.assign(data.page, data.param)).then(
        response => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.form.userId = data.value.userId;
        this.form.tenantId = data.value.tenantId;
        this.submitForm();
      } else if (data.type === "click") {
        this.form.userId = data.value.userId;
        this.form.tenantId = data.value.tenantId;
      }
    },
    // 用户状态字典翻译
    statusFormat(row, column) {
      var rulesStr = "";
      this.statusOptions.forEach(v => {
        if (v.dictValue === row.status) {
          rulesStr = v.dictLabel;
        }
      });
      return rulesStr;
    },
    tenantTypeFormat(row, column) {
      var rulesStr = "";
      this.tenantTypeOptions.forEach(v => {
        if (v.dictValue === row.status) {
          rulesStr = v.dictLabel;
        }
      });
      return rulesStr;
    },
    /** 查询项目用户关系列表 */
    getList() {
      this.loading = true;
      this.queryParams.projectId = this.infoData.projectId;
      listProjectUser(this.queryParams).then(response => {
        this.project_tenantList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projectId: this.infoData.projectId,
        userId: null,
        tenantId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.projectId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleDetails();
    },
    /** 提交按钮 */
    submitForm() {
      addProjectUser(this.form).then(response => {
        this.msgSuccess("新增成功");
        this.selectTableShow = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = this.infoData.projectId;
      const userId = row.userId;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delProjectUser(projectIds, userId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有项目用户关系数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportProjectUser(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
