<template>
  <ai-detail showFooter class="add-detail">
    <template slot="title">
      <ai-title :title="isEdit ? '编辑小区信息' : '添加小区'" :isShowBack="true" @onBackClick="cancel()" :isShowBottomBorder="true"></ai-title>
    </template>
    <template slot="content">
      <div class="add-form">
        <ai-bar title="基础信息"></ai-bar>
        <el-form label-width="110px" style="padding-bottom: 80px;" :model="form" ref="form">
          <el-form-item label="小区名称" prop="communityName" :rules="[{ required: true, message: '请输入小区名称', trigger: 'blur' }]">
            <el-input size="small" v-model="form.communityName" :maxlength="50" placeholder="请输入小区名称"></el-input>
          </el-form-item>
          <el-form-item label="行政归属" prop="areaId" :rules="[{ required: true, message: '请选择行政归属', trigger: 'blur' }]">
            <ai-area-get :instance="instance" v-model="form.areaId" :root="user.info.areaId" @select="handleAreaSelect" />
          </el-form-item>

          <el-form-item label="小区地址" prop="address" :rules="[{ required: true, message: '请输入小区地址', trigger: 'blur' }]">
            <el-input size="small" v-model="form.address" placeholder="请输入小区名称" clearable=""></el-input>
          </el-form-item>

          <el-form-item label="所属网格" prop="girdInfoList" style="margin-top: 8px;" :rules="[{ required: true, message: '请选择所属网格', trigger: 'blur' }]">                                                                     
            <el-tag
              :key="index"
              v-for="(tag,index) in form.girdInfoList"
              closable
              style="margin-right: 16px;"
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag.girdName}}
            </el-tag>                                      
            <el-button size="small" @click="showGrid=true">选择网格</el-button>                                                                          
          </el-form-item>
        </el-form>
      </div>
      <ai-dialog title="选择网格" :visible.sync="showGrid" :customFooter="true"  :destroyOnClose="true"  @opened="beforeSelectTree"  border  width="720px">
        <div class="grid">
          <el-tree :data="treeObj.treeList"  :props="treeObj.defaultProps" node-key="id"  ref="tree" :check-strictly="true" show-checkbox
            :default-checked-keys="treeObj.checkedKeys" default-expand-all  highlight-current>                  
          </el-tree> 
        </div>
        <div class="dialog-footer" slot="footer" >
          <el-button  size="medium" @click="showGrid=false">取消</el-button>
          <el-button  type="primary" size="medium" @click="getCheckedTree()">确认</el-button>
        </div>
      </ai-dialog>
    </template>
    <template slot="footer" class="footer">
      <el-button class="delete-btn footer-btn" @click="cancel(false)">取消</el-button>
      <el-button class="footer-btn" type="primary" @click="onSubmit('0')">保存</el-button>
    </template>
  </ai-detail>
</template>

<script>
import { mapState } from 'vuex'

export default {
  name: 'Add',

  props: {
    dict: Object,
    params: Object,
    instance: Function,
  },

  data() {
    return {
      gridList: [],
      girdId: '',
      subGridId: '',
      subGridList: [],
      sonGridList: [],
      form: {
        communityName: '',
        areaName: '',
        areaId: '',
        girdId: '',
        dealOpinion: '',
        recordUser: '',
        address: '',
        girdInfoList: [],
        girdName: '',
      },
      showGrid: false,
      treeObj: {
        treeList: [],
        defaultProps: {
          children: "girdList",
          label: "girdName",
        },
        checkedKeys: [],
      },
    }
  },

  computed: {
    ...mapState(['user']),

    isEdit() {
      return !!this.params.id
    },
  },

  created() {
    this.dict.load('cardType', 'sex', 'nation').then(() => {
      if (this.params && this.params.id) {
        this.getInfo(this.params.id)
      }
    })
  },
  methods: {
    beforeSelectTree() {
      this.treeObj.checkedKeys = [];
      this.instance.post(`/app/appgirdinfo/listAll`, null, null).then((res) => {
        if (res.code == 0) {
          this.treeObj.treeList = res.data;
          if(this.form.girdInfoList.length) {
            this.form.girdInfoList.map((e) => {
              this.treeObj.checkedKeys.push(e.id);
            });
          }
        }
      });
    },
    getCheckedTree() {
      if (this.$refs.tree.getCheckedNodes().length > 1) {
        return this.$message.error('不能绑定多个网格')
      }
      this.form.girdInfoList = this.$refs.tree.getCheckedNodes();
      this.showGrid = false;
    },
    handleClose(tag) {
      this.form.girdInfoList.splice(this.form.girdInfoList.indexOf(tag), 1);
    },
    getInfo(id) {
      this.instance.post(`/app/appcommunityinfo/queryDetailById?id=${id}`).then((res) => {
        if (res.code === 0) {
          this.girdId = res.data.girdId0
          this.form.communityName = res.data.communityName
          this.form.address = res.data.address
          this.form.areaName = res.data.areaName
          this.form.girdId = res.data.girdId
          this.form.girdName = res.data.girdName
          this.form.girdInfoList = [{id:res.data.girdId, girdName: res.data.girdName}]
          this.$set(this.form, 'areaId', res.data.areaId)
        }
      })
    },

    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.girdInfoList.length > 1) {
            return this.$message.error('不能绑定多个网格')
          }

          this.form.girdName = this.form.girdInfoList[0].girdName
          this.form.girdId = this.form.girdInfoList[0].id
          this.instance
            .post(`/app/appcommunityinfo/addOrUpdate`, {
              ...this.form,
              id: this.params ? this.params.id : '',
            })
            .then((res) => {
              if (res.code === 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 800)
              }
            })
        }
      })
    },

    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh,
      })
    },
    handleAreaSelect(v) {
      this.form.areaName = v?.[0]?.label
    },
  },
}
</script>

<style lang="scss" scoped>
.add-detail {
  height: 100%;
  overflow: hidden;
  background: #f2f4f6 !important;

  .add-form__item {
    display: flex;
    align-items: center;
  }

  ::v-deep .el-form-item__label {
    padding-right: 40px;
  }

  ::v-deep .ai-detail__footer {
    background: #fff !important;
  }

  ::v-deep .ai-detail__content--active {
    padding: 20px;

    .ai-detail__content--wrapper {
      width: 100%;
    }

    .aibar {
      padding: 0 16px;
    }

    .el-form {
      padding: 0 96px 0 50px;
    }

    .add-form {
      background: #fff;
    }
  }

  ::v-deep .ai-wrapper {
    align-items: inherit !important;
  }

  .user-wrapper {
    display: flex;
    justify-content: space-between;
  }

  .avatar {
    width: 100px;
    height: 100px;
    object-fit: contain;
    border-radius: 10px;
  }

  .footer-btn {
    width: 130px;
  }

  .el-form {
    padding-bottom: 80px;
  }
}
</style>
