<template>
  <div>
    <div class="cardTitle">住户信息</div>
    <div class="search-box">
      <a-row>
        <a-col :span="20">
          <a-space size="large">
            <a-select v-model='searchForm.sex' style="width: 200px" placeholder="请选择性别" >
              <a-select-option value="1">男</a-select-option>
              <a-select-option value="2">女</a-select-option>
              <a-select-option value="3">保密</a-select-option>
            </a-select>
            <a-input v-model='searchForm.keyword' style="width: 200px" placeholder="请输入关键字（姓名/手机号）" />
            <a-button type="primary" @click='getData'>查 询</a-button>
            <a-button @click='reset'>重 置</a-button>
          </a-space>
        </a-col>
        <a-col :span="4">
          <a-button class="add-btn" @click="show.add = true">添加住户</a-button>
        </a-col>
      </a-row>
    </div>
    <div class="main">
      <div style="margin-bottom: 16px">
        <!-- 批量操作 -->
        <a-select
          type="primary"
          v-model="activeAction"
          :disabled="!hasSelected"
          :loading="loading"
          style="width: 120px"
          @change="Actions"
          placeholder="请选择操作"
        >
          批量
          <a-select-option v-for="item in ActionsList" :key="item.value">
            {{ item.label }}
          </a-select-option>
        </a-select>
        <span style="margin-left: 8px">
          <template v-if="hasSelected">
            {{ `已选择 ${selectedRowKeys.length} 条` }}
          </template>
        </span>
      </div>
      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :scroll="{ x: 1400 }"
		@change="handleTableChange"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: selectionChoosed,
        }"
        :row-key="
          (record, index) => {
            return record.id;
          }
        "
      >
        <span slot="name" slot-scope="text, row">
          <a-select style="width :100%" @change='changeHouse' placeholder='请选择房屋'>
            <a-select-option v-for="item,index in row.residentListEstateVoList" :key='index' :value="item.id" @click="chooseHouse(row)">
              {{
            item.manageBuildingName +
            "栋/" +
            item.manageUnitName +
            "单元/" +
            item.floorLocation +
            "层-" +
            item.manageEstateName +
            "室"
          }}
            </a-select-option>
          </a-select>
        </span>
        <span slot="action" slot-scope="text, row">
            <a-space>
              <a class="ant-dropdown-link"  @click="edit(row)">编辑</a>
              <a class="ant-dropdown-link" @click="show.in=true,inform.residentId = row.id">迁入</a>
              <a class="ant-dropdown-link" @click="out(row)">迁出</a>
            </a-space>
        </span>
        <span slot="tags" slot-scope="tag">
          <a-tag
            :color="tag === 1 ? 'volcano' : tag === 2 ? 'geekblue' : tag === 3 ? 'geekblue' : 'red'"
          >
            {{ tag === 1 ? "业主" : tag === 2 ? "业主亲属" :tag === 3 ? "租户":tag === 4 ? "租户亲属":'-'  }}
          </a-tag>
        </span>
      </a-table>
    </div>
	<add-form :show="show.add" :editId="editId" @close='close' @success='success'></add-form>
	<a-modal
      title="迁入"
      :visible="show.in"
      @ok="insubmit"
      @cancel="inclose"
    >
      <div>
		<a-form-model
			ref="ruleForm"
			:model="inform"
			:rules="rules"
			layout="vertical"
		>
			<a-form-model-item label="关联房屋" prop="estateId">
				<a-cascader
                  :options="estateData"
                  v-model="estateArr"
                  :field-names="{ label: 'name', value: 'id', children: 'childList' }"
                  placeholder="楼栋/单元/房间号"
                  @change="onChange"
                  style="width: 90%"
                />
			</a-form-model-item>
			<a-form-model-item label="住户身份" prop="identity">
                <a-select v-model="inform.identity" placeholder="请选择住户身份" style="width: 90%">
                  <a-select-option v-for="item in options.identity" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
			  <a-form-model-item label="房屋租户" prop="linkUserId" v-if="inform.identity===4">
				<a-select v-model="inform.linkUserId" placeholder="请选择住户身份" style="width: 90%">
                  <a-select-option v-for="item in options.tenant" :key="item.id" :value="item.id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-model-item>
		</a-form-model>
	  </div>
    </a-modal>
  </div>
</template>

<script>
import { columns,pagination,searchForm, rules } from './depend/config.js'
import { estate } from '@/api/basic/estate'
import { residentList, moveIn, moveOut, findTenantByEstateId } from '@/api/basic/resident'
import addForm from './depend/addForm.vue'
export default {
	components:{
		addForm
	},
	data() {
		return {
			editId:null,
			form: {
				identity: 2
			},
			inform:{
				estateId:undefined,
				residentId:undefined,
				identity:undefined,
				linkUserId:undefined,
			},
			estateArr:[],
			estateData:[],
			rules,
			show: {
				add: false,
				in:false,
				detail:{}
			},
			table_row:{},
			changeId:null,
			loading: false,
			pagination,
			searchForm,
			activeAction: undefined,
			
			// 选择的index
			selectedRowKeys: [],
			// 分页
			//   列
			columns,
			newData:[],
			//   数据
			tableData:[],
			options:{
				identity:[
					{ id:1, name:'业主' },
					{ id:2, name:'业主亲属' },
					{ id:3, name:'租户' },
					{ id:4, name:'租户亲属' },
				],
				tenant:[]
			},
			ActionsList: [
				// {
				// 	label: "批量删除",
				// 	value: 1,
				// },
				// {
				// 	label: "批量导出",
				// 	value: 2,
				// },
			],
		};
	},
	mounted(){
		this.getData()
		this.getEstate()
	},
	methods: {
		async getData() {
			const res = await residentList({
				pageNum: this.pagination.current,
				size :this.pagination.pageSize,
				sex:this.searchForm.sex,
				keyword:this.searchForm.keyword,
			})
			this.tableData = res.data.rows
			this.pagination.total = res.data.total
		},
		// 所有房屋
		async getEstate(){
			let res = await estate()
			this.estateData = res.data
			this.estateDisable(this.estateData)
		},
		estateDisable(arr){
			arr.forEach((item,index)=>{
				if(!item.manageEstateTypeName && item.childList.length === 0){
					arr[index].disabled = true
				}else if(item.manageEstateTypeName || item.childList.length > 0){
					arr[index].disabled = false
				}else{
					this.estateDisable(item.childList)
				}
			})
		},
		// 重置
		reset(){
			this.searchForm = {
				keyword: "",
				sex: undefined,
			}
			this.getData()
		},
		// 编辑住户
		edit(data){
			this.editId = data.id
			this.show.add = true;
		},
		// form提交成功的回调
		close(){
			this.show.add = false;
			this.editId = null
		},
		// form提交成功的回调
		success(){
			this.getData()
		},
		// 表格行切换房屋
		changeHouse(value){
			// 选中的行
			this.tableData.forEach((item,index)=>{
				if(item.id === this.table_row.id) {
					item.residentListEstateVoList.forEach((items)=>{
						if(items.id === value){
							this.$set(this.tableData[index],'identity' ,items.identity )
							this.$set(this.tableData[index],'manageEstateTypeName' ,items.manageEstateTypeName )
							this.$set(this.tableData[index],'houseId' ,items.id )
						}
					})
				}
			})
		},
		chooseHouse(row){
			this.table_row  = row
		},
		handleTableChange(pagination) {
			const pager = { ...this.pagination };
			pager.current = pagination.current;
			pager.pageSize = pagination.pageSize;
			this.pagination = pager;
			this.getData()
		},
		Actions(data) {
			console.log(data);
			this.activeAction = undefined;
		},
		selectionChoosed(data) {
			this.selectedRowKeys = data;
		},
		async insubmit(){// 迁入提交
			console.log(this.inform);
			this.$refs.ruleForm.validate(async valid => {
				if(valid){let res = await moveIn(this.inform)
					if(res.code === 200){
						this.$message.success(res.msg)
						this.getData()
						this.inclose()
					}else{
						this.$message.error(res.msg)
					}}
			})
		},
		inclose(){
			this.$refs.ruleForm.resetFields();
			this.estateArr = []
			this.show.in = false
		},
		out(data) {// 迁出
			if(!data.houseId) {
				this.$message.error('请先选择房屋')
				return
			}
			this.$confirm({
				title: "是否迁出",
				// okText:'删除',
				// cancelText:'取消',
				icon: "logout",
				onOk:async ()=> {
					let res = await moveOut({estateId:data.houseId,residentId:data.id})
					if(res.code === 200){
						this.$message.success(res.msg)
						this.getData()
					}else{
						this.$message.error(res.msg)
					}
				},
			});
		},
		onChange(value, selectedOptions){
			if(value.length > 0){
				this.inform.estateId = value[value.length - 1];
				findTenantByEstateId({estateId:this.inform.estateId}).then(res =>{
					this.options.tenant = res.data
				})
			}else{
				this.inform.estateId = undefined;
			}
		},
	},
	computed: {
		// 是否选择selection
		hasSelected() {
			return this.selectedRowKeys.length > 0;
		},
	},
};
</script>

<style lang="less" scoped>
/deep/.ant-upload.ant-upload-select-picture-card{
  width: 240px;
  height: 160px;
}
/deep/.avatar-uploader > .ant-upload {
  width: 240px;
  height: 160px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>