<template>
  <div class="divBox">
    <el-row :gutter="20">
      <!--部门数据-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable size="small" prefix-icon="el-icon-search"
                    style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree :data="deptTreeOptions" :props="defaultProps" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="tree" node-key="deptId" default-expand-all highlight-current
                   @node-click="handleNodeClick" />
        </div>
      </el-col>
      <!--租户数据-->
      <el-col :span="20" :xs="24">
        <el-form v-if="showSearch" :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="租户姓名">
        <el-input v-model="dataForm.tenantName" placeholder="请输入租户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="租户类型">
        <el-select v-model="dataForm.tenantType" placeholder="请选择租户类型" clearable>
          <el-option
            v-for="item in dict.type.tenant_type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="dataForm.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="item in dict.type.tenant_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="option-bth">
<!--      <el-button v-hasPermi="['autogencode:pmtenant:save']" plain size="small" type="primary" @click="addOrUpdateHandle()">新增租户</el-button>-->
        <!-- <el-button v-hasPermi="['autogencode:pmtenant:delete']" type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
    </div>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;">
      <el-table-column
        v-if="showSearch"
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column
        prop="tenantName"
        header-align="center"
        align="center"
        label="租户姓名">
      </el-table-column>
      <el-table-column
        prop="tenantType"
        header-align="center"
        align="center"
        label="租户类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tenant_type" :value="scope.row.tenantType"/>
        </template>
      </el-table-column>
      <el-table-column
        prop="idCard"
        header-align="center"
        align="center"
        label="租户身份证">
      </el-table-column>
      <el-table-column
        prop="phome"
        header-align="center"
        align="center"
        label="联系电话">
      </el-table-column>
      <el-table-column
        prop="company"
        header-align="center"
        align="center"
        label="工作单位">
      </el-table-column>
      <el-table-column prop="deptId" label="所属部门" width="150">
        <template slot-scope="scope">
          {{ getDeptName(scope.row.deptId) }}
        </template>
      </el-table-column>
      <el-table-column
          prop="status"
          header-align="center"
          align="center"
          label="状态">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tenant_status" :value="scope.row.status"/>
        </template>
        </el-table-column>
      <!-- <el-table-column
        prop="remark"
        header-align="center"
        align="center"
        label="备注">
      </el-table-column> -->
      <!-- <el-table-column
        prop="delFlag"
        header-align="center"
        align="center"
        label="删除标志（0代表存在 2代表删除）">
      </el-table-column> -->
      <!-- <el-table-column
        prop="createDept"
        header-align="center"
        align="center"
        label="创建部门">
      </el-table-column> -->
      <!-- <el-table-column
        prop="createBy"
        header-align="center"
        align="center"
        label="创建人">
      </el-table-column> -->
      <!-- <el-table-column
        prop="createTime"
        header-align="center"
        align="center"
        label="创建时间">
      </el-table-column> -->
      <el-table-column
        prop="updateBy"
        header-align="center"
        align="center"
        label="修改人">
      </el-table-column>
      <!-- <el-table-column
        prop="updateTime"
        header-align="center"
        align="center"
        label="修改时间">
      </el-table-column> -->
      <el-table-column
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="addOrUpdateHandle(scope.row.id)">{{ '修改' }}</el-button>
          <el-button v-hasPermi="['autogencode:pmtenant:delete']" type="text" size="small" @click="deleteHandle(scope.row.id)" style="color: #f56c6c;">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      hide-on-single-page
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 表单弹窗, 新增数据和修改数据 -->
    <!-- <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update> -->
    <tenant-add-and-update ref="tenantAddOrUpdate" :ownerId="dataForm.id" @refreshDataList="getDataList"></tenant-add-and-update>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import TenantAddAndUpdate from '@/views/pm/pmowner/tenant-add-and-update'
  import * as api from '@/api/pmtenant.js'
  import * as deptApi from "@/api/sysdept";
  export default {
    dicts: ['owner_Type','owner_status','tenant_status','tenant_type'],
    props: {
      // 业主ID
      ownerId: {
        type: String,
        default: ''
      },
      showSearch: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        deptTreeOptions: [],
        deptMap: {}, // 部门映射关系
        deptName: undefined,
        defaultProps: {
          children: "children",
          label: "deptName"
        },
        dataForm: {
          // 业主ID
          ownerId: this.ownerId,
          tenantName: '',
          tenantType: '',
          idCard: '',
          phome: '',
          company: '',
          status: '',
          remark: '',
        },

        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false
      }
    },
    components: {
      // AddOrUpdate,
      TenantAddAndUpdate
    },
    watch: {
      // 监听业主ID变化
      ownerId(newVal) {
        this.dataForm.ownerId = newVal;
        this.getDataList();
      },
      deptName(val) {
        this.$refs.tree.filter(val);
      }
    },
    activated () {
      this.getDataList()
    },
    mounted() {
      this.handleGetDeptList()
      // 确保页面加载时自动查询
      this.getDataList()
    },
    methods: {
      handleGetDeptList() {
          // 为了确保租户部门也能正确翻译，需要获取所有部门
          deptApi.deptTreeSelect({type: '2'}).then(allRes => {
            this.deptTreeOptions = allRes
            // 合并所有部门到映射关系中
            this.buildDeptMap(allRes)
            // 再次更新租户部门名称，确保所有部门都能翻译
            if (this.tenantList && this.tenantList.length > 0) {
              this.tenantList.forEach(tenant => {
                if (tenant.deptId) {
                  tenant.deptName = this.getDeptName(tenant.deptId)
                } else {
                  tenant.deptName = null
                }
              })
            }
          })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.deptName.indexOf(value) !== -1;
      },
      handleNodeClick(data) {
        this.dataForm.deptId = data.deptId;
        this.getDataList();
      },
      // 构建部门映射关系
      buildDeptMap(depts) {
        depts.forEach(dept => {
          this.deptMap[dept.deptId] = dept.deptName
          if (dept.children && dept.children.length > 0) {
            this.buildDeptMap(dept.children)
          }
        })
      },
      // 根据部门ID获取部门名称
      getDeptName(deptId) {
        return this.deptMap[deptId] || '未分配'
      },
      // 重置表单
      resetForm() {
        this.dataForm = {
          // 业主ID
          ownerId: this.ownerId,
          tenantName: '',
          tenantType: '',
          idCard: '',
          phome: '',
          company: '',
          status: '',
          remark: '',
          deptId: null,
        }
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataListLoading = true
        // 根据后端PmTenantController和PageParamRequest的期望格式构建参数
        const params = {
          page: this.pageIndex,
          limit: this.pageSize
        }

        // 将查询条件添加到参数中
        if (this.dataForm.tenantName) params.tenantName = this.dataForm.tenantName;
        if (this.dataForm.tenantType) params.tenantType = this.dataForm.tenantType;
        if (this.dataForm.idCard) params.idCard = this.dataForm.idCard;
        if (this.dataForm.phome) params.phome = this.dataForm.phome;
        if (this.dataForm.company) params.company = this.dataForm.company;
        if (this.dataForm.status) params.status = this.dataForm.status;
        if (this.dataForm.remark) params.remark = this.dataForm.remark;
        if (this.dataForm.ownerId) params.ownerId = this.dataForm.ownerId;
        if (this.dataForm.deptId) params.deptId = this.dataForm.deptId;

        api.pmtenantListApi(params).then(res => {
          this.dataListLoading = false
          this.dataList = res.list || [];
          this.totalPage = res.total;
        }).catch(e => {
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        if (this.$refs.tenantAddOrUpdate) {
          this.$refs.tenantAddOrUpdate.init(id, this.dataForm.ownerId)
        }
      },
      // 删除处理（支持单个删除和批量删除）
      deleteHandle (id) {
        let ids = []
        let idText = ''

        // 如果传入了单个id参数，则为单个删除
        if (id) {
          ids = [id]
          idText = id
        } else {
          // 否则为批量删除
          ids = this.dataListSelections.map(item => {
            return item.id
          })
          idText = ids.join(',')
        }

        this.$confirm(`确定进行删除操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用批量删除API
          api.pmtenantDeleteApi(ids).then(res => {
            this.$message.success('删除成功')
            this.getDataList()
          })
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
::v-deep .el-table__expanded-cell {
  padding: 0 !important;
}
</style>
