<template>
  <!-- 基于 Element UI 新增和修改弹窗 -->
  <el-dialog
      :title="!dataForm.id ? '添加' : '修改'"
      :close-on-click-modal="false"
      :visible.sync="visible">
    <!-- 新增和修改表单 -->
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataSubmit()" label-width="100px">
    <el-form-item label="业主姓名" prop="ownerName">
      <el-input v-model="dataForm.ownerName" placeholder="业主姓名"></el-input>
    </el-form-item>
    <el-form-item label="业主类型" prop="ownerType">
      <el-input v-model="dataForm.ownerType" placeholder="业主类型"></el-input>
    </el-form-item>
    <el-form-item label="业主身份证" prop="ownerIdcard">
      <el-input v-model="dataForm.ownerIdcard" placeholder="业主身份证"></el-input>
    </el-form-item>
    <el-form-item label="联系电话" prop="phone">
      <el-input v-model="dataForm.phone" placeholder="联系电话"></el-input>
    </el-form-item>
    <el-form-item label="电子邮箱" prop="email">
      <el-input v-model="dataForm.email" placeholder="电子邮箱"></el-input>
    </el-form-item>
    <el-form-item label="紧急联系人" prop="emergencyContact">
      <el-input v-model="dataForm.emergencyContact" placeholder="紧急联系人"></el-input>
    </el-form-item>
    <el-form-item label="紧急联系电话" prop="emergencyPhone">
      <el-input v-model="dataForm.emergencyPhone" placeholder="紧急联系电话"></el-input>
    </el-form-item>
    <el-form-item label="所属部门" prop="deptId">
      <treeselect
        v-model="dataForm.deptId"
        :options="deptTreeOptions"
        :normalizer="normalizer"
        placeholder="选择部门"
        style="width: 100%"
      ></treeselect>
    </el-form-item>
    <el-form-item label="所属房屋" prop="houseId">
      <el-select v-model="dataForm.houseId" placeholder="选择房屋" clearable style="width: 100%">
        <el-option
          v-for="item in houseList"
          :key="item.id"
          :label="`${item.unitNo}单元 ${item.floorNo}层 ${item.houseNo}室`"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="业主状态" prop="status">
      <el-input v-model="dataForm.status" placeholder="业主状态"></el-input>
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="dataForm.remark" placeholder="备注" type="textarea"></el-input>
    </el-form-item>
    <!-- 显示添加租户按钮 -->
    <el-form-item>
      <el-button type="success" @click="addTenant">添加租户</el-button>
    </el-form-item>
    </el-form>

    <!-- 租户列表 -->
    <div class="tenant-list-container">
      <el-table :data="tenantList" style="width: 100%">
        <el-table-column prop="tenantName" label="租户姓名" width="120"></el-table-column>
        <el-table-column prop="phome" label="联系电话" width="120"></el-table-column>
        <el-table-column prop="idCard" label="身份证号" width="180"></el-table-column>
        <el-table-column prop="company" label="工作单位" width="150"></el-table-column>
        <el-table-column prop="status" label="状态" width="100"></el-table-column>
        <el-table-column prop="remark" label="备注" width="150"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="editTenant(scope.row.id)">{{ '修改' }}</el-button>
            <el-button type="text" size="small" @click="deleteTenant(scope.row.id, scope.$index)">{{ '删除' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataSubmit()">确定</el-button>
    </span>

    <!-- 租户弹窗 -->
    <tenant-add-and-update ref="tenantAddOrUpdate" :ownerId="dataForm.id" @refreshDataList="getTenantList"></tenant-add-and-update>
  </el-dialog>
</template>

<script>
  import * as api from '@/api/pmowner.js'
  import * as deptApi from '@/api/sysdept.js'
  import * as tenantApi from '@/api/pmtenant.js'
  import * as houseApi from '@/api/pmhouse.js'
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import TenantAddAndUpdate from './tenant-add-and-update.vue'

  export default {
    components: { Treeselect, TenantAddAndUpdate },
    data () {
      return {
        visible: false,
        deptTreeOptions: [],
        houseList: [],
        tenantList: [],
        dataForm: {
          id: 0,
          ownerName: '' ,
          ownerType: '' ,
          ownerIdcard: '' ,
          phone: '' ,
          email: '' ,
          emergencyContact: '' ,
          emergencyPhone: '' ,
          status: '' ,
          deptId: null ,
          houseId: null ,
          remark: '' ,
        },
        dataRule: {
          ownerName: [
            { required: true, message: '业主姓名  为必填项', trigger: 'blur' }
          ],
          ownerType: [
            { required: true, message: '业主类型  为必填项', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '业主状态  为必填项', trigger: 'blur' }
          ],
        }
      }
    },
    mounted() {
      this.handleGetDeptList()
      this.handleGetHouseList()
    },
    methods: {
      handleGetDeptList() {
        deptApi.deptTreeSelect().then(res => {
          this.deptTreeOptions = res
        })
      },
      handleGetHouseList() {
        houseApi.pmhouseListApi({ page: 1, limit: 9999 }).then(res => {
          this.houseList = res.list || []
        })
      },
      // 获取租户列表
      getTenantList() {
        if (!this.dataForm.id) return
        tenantApi.pmtenantListByOwnerIdApi(this.dataForm.id, { page: 1, limit: 9999 }).then(res => {
          try {
            this.tenantList = Array.isArray(res) ? res : (res.list || [])
          } catch (error) {
            this.tenantList = []
          }
        }).catch(err => {
          this.tenantList = []
        })
      },
      // 添加租户
      addTenant() {
        if (this.$refs.tenantAddOrUpdate) {
          this.$refs.tenantAddOrUpdate.init(0, this.dataForm.id)
        }
      },
      // 编辑租户
      editTenant(id) {
        if (this.$refs.tenantAddOrUpdate) {
          this.$refs.tenantAddOrUpdate.init(id, this.dataForm.id)
        }
      },
      // 删除租户
      deleteTenant(id, index) {
        this.$confirm('确定要删除这条租户记录吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          if (id) {
            // 已有ID的记录，调用API删除
            tenantApi.pmtenantDeleteApi([id]).then(() => {
              this.$message.success('删除成功')
              // 从列表中移除这条记录
              this.tenantList.splice(index, 1)
            }).catch(() => {
              this.$message.error('删除失败')
            })
          } else {
            // 还没有ID的新增记录，直接从列表中删除
            this.tenantList.splice(index, 1)
            this.$message.success('删除成功')
          }
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.deptId ? node.deptId : '0',
          label: node.deptName ? node.deptName : '顶级部门',
          children: node.children
        };
      },
      init (id) { // 初始化表单验证规则
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(function() {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            api.pmownerDetailApi(id).then(function(res) {
              this.dataForm = res;
              // 获取该业主的租户列表
              this.getTenantList()
            }.bind(this))
          } else {
            // 新增时清空租户列表
            this.tenantList = []
          }
        }.bind(this))
      },
      // 表单数据提交
      dataSubmit () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
              api.pmownerUpdateApi(this.dataForm).then(function(res) {
                this.$message.success('保存成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            } else {
              api.pmownerCreateApi(this.dataForm).then(function(res) {
                this.$message.success('新增成功')
                this.visible = false
                this.$emit('refreshDataList')
              }.bind(this));
            }
          }
        })
      }
    }
  }
</script>
<style>
.tenant-list-container {
  margin-top: 20px;
}
</style>
