<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="tenantName" />
      <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="expirationTime" 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="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px"></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="选择租户"
      :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 {
  listProject_tenant,
  getProject_tenant,
  delProject_tenant,
  addProject_tenant,
  updateProject_tenant,
  exportProject_tenant,
  listUserdByProjectId
} from "@/api/iot/projectTenant";
import SelectTableWrap from "@/components/SelectTable/index";
export default {
  name: "EObjectTenant",
  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: "expirationTime",
	      isAsc: "desc"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 租户状态
      statusOptions: [],
      tenantTypeOptions: []
    };
  },
  watch: {
    infoData: {
      handler(newVal) {
        if (newVal) {
          this.getList()
        }
      },
      deep:true, // 深度监听
			immediate: false, // 初始化监听
    }
  },
  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: "tenantName",
              size: "small",
              value: ""
            }
          ]
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "企业名称",
              type: "",
              prop: "tenantName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "企业法人",
              type: "",
              prop: "corporation",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span"
            },
            {
              style: "",
              label: "状态",
              type: "",
              prop: "status",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "text1"
            },
            {
              style: "",
              label: "有效期",
              type: "time",
              prop: "expirationTime",
              align: "center",
              width: "180",
              "show-overflow-tooltip": false,
              tempType: "span"
            }
          ],
          tableList: {
            type: Array
          }
        },
        tableList: []
      };
      this.selectTableShow = true;
    },
    childGetList(data) {
      listUserdByProjectId(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.tenantId = data.value.tenantId;
        this.submitForm();
      } else if (data.type === "click") {
        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;
      listProject_tenant(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,
        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();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const projectId = row.projectId || this.ids;
      getProject_tenant(projectId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改项目租户关系";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if ((this.form.tenantId !== null && this.form.tenantId !==undefined) && (this.form.projectId !== null && this.form.projectId !==undefined)) {
        addProject_tenant(this.form).then(response => {
          this.msgSuccess("新增成功");
          this.selectTableShow = false;
          this.getList();
        });
      } else {
        this.$message.error('没有选择任何数据！');
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const projectIds = row.projectId;
      const tenantId = row.tenantId;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delProject_tenant(projectIds, tenantId);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有项目租户关系数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportProject_tenant(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        });
    }
  }
};
</script>
