<template>
  <section style="height: 100%">
    <ai-detail class="Add">
      <!-- 返回按钮 -->
      <template #title>
        <ai-title :title="isEdit ? '编辑宅基地信息' : '添加宅基地'" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
      </template>
      <template #content>
        <el-form :model="formData" :rules="formRules" ref="ruleForm" label-width="150px" label-suffix="：" align-items="center">
          <ai-card title="户主信息" >
            <template slot="content">
              <div class="flex">
                <el-form-item label="姓名" prop="name">
                  <el-input size="small" class="user-selecter" v-model="formData.name" placeholder="请输入" clearable>
                    <template slot="append">
                      <ai-person-select :instance="instance" @selectPerson="checkName">
                      </ai-person-select>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="身份证号码" prop="idNumber">
                  <ai-id size="small" v-model="formData.idNumber" @change="IdCard(formData.idNumber)"/>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <ai-select v-model="formData.sex" placeholder="请选择" :selectList="dict.getDict('sex')" disabled />
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                  <el-input size="small" v-model="formData.age" placeholder="请输入" clearable disabled></el-input>
                </el-form-item>
                <el-form-item label="联系电话">
                  <el-input size="small" v-model="formData.phone" placeholder="请输入" clearable :maxlength="20"></el-input>
                </el-form-item>
              </div>
              <el-form-item label="所属村" prop="areaId">
                <ai-area-get :instance="instance" v-model="formData.areaId" :name.sync="formData.areaName" />
              </el-form-item>
            </template>
          </ai-card>
          <ai-card title="宅基地情况" >
            <template slot="content">
              <div class="flex">
                <el-form-item label="宅基地面积">
                  <el-input size="small" v-model="formData.homesteadArea" placeholder="请输入" clearable maxlength="10">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="房基占地面积">
                  <el-input size="small" v-model="formData.houseArea" placeholder="请输入" clearable maxlength="10">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </div>
              <el-form-item label="宅基地地址">
                <el-input size="small" v-model="formData.homesteadAddress" placeholder="请输入" clearable maxlength="20"></el-input>
              </el-form-item>
              <div class="flex">
                <el-form-item label="四至-东至">
                  <el-input size="small" v-model="formData.eastTo" placeholder="请输入" clearable maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="四至-南至">
                  <el-input size="small" v-model="formData.southTo" placeholder="请输入" clearable maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="四至-西至">
                  <el-input size="small" v-model="formData.westTo" placeholder="请输入" clearable maxlength="20"></el-input>
                </el-form-item>
                <el-form-item label="四至-北至">
                  <el-input size="small" v-model="formData.northTo" placeholder="请输入" clearable maxlength="20"></el-input>
                </el-form-item>
              </div>
              <el-form-item label="地类" class="buildingTypes">
                <el-radio-group v-model="formData.landType">
                  <el-radio :label="item.dictValue" v-for="(item, index) in dict.getDict('homesteadLandType')" :key="index">{{item.dictName}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="性质" class="buildingTypes">
                <el-radio-group v-model="formData.houseType">
                  <el-radio :label="item.dictValue" v-for="(item, index) in dict.getDict('homesteadHouseType')" :key="index">{{item.dictName}}</el-radio>
                </el-radio-group>
              </el-form-item>
              <div class="flex">
                <el-form-item label="住宅建筑面积">
                  <el-input size="small" v-model="formData.liveBuildingArea" placeholder="请输入" clearable maxlength="10">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="建筑层数">
                  <el-input size="small" v-model="formData.buildingFloorNumber" placeholder="请输入" clearable maxlength="10">
                    <template slot="append">层</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="建筑高度">
                  <el-input size="small" v-model="formData.buildingHeight" placeholder="请输入" clearable maxlength="10">
                    <template slot="append">m</template>
                  </el-input>
                </el-form-item>
              </div>
            </template>
          </ai-card>
          <ai-card title="位置信息" >
            <template slot="content">
              <div class="flex">
                <el-form-item label="楼栋经度">
                  <el-input size="small" v-model="formData.lng" placeholder="请输入" clearable maxlength="10"></el-input>
                </el-form-item>
                <el-form-item label="楼栋纬度">
                  <el-input size="small" v-model="formData.lat" placeholder="请输入" clearable maxlength="10"></el-input>
                </el-form-item>
              </div>
              <el-form-item label="地图位置">
                <el-button @click="showMap = true">地图标绘</el-button>
              </el-form-item>
            </template>
          </ai-card>
        </el-form>
      </template>
      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm()">提交</el-button>
      </template>
    </ai-detail>
    <ai-dialog title="地图" :visible.sync="showMap" @opened="getCorpLocation" width="800px" class="mapDialog" @onConfirm="selectMap">
      <div id="map"></div>
      <el-form label-width="80px" style="padding: 10px 20px 0 20px;">
        <el-row type="flex" justify="space-between">
          <el-form-item label="经度">
            <el-input disabled size="small" v-model="placeDetail.lng"></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input disabled size="small" v-model="placeDetail.lat"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <el-input id="searchPlaceInput" size="medium" class="searchPlaceInput" clearable v-model="searchPlace" autocomplete="on" @change="placeSearch.search(searchPlace)" placeholder="请输入关键字">
        <el-button type="primary" slot="append" @click="placeSearch.search(searchPlace)">搜索</el-button>
      </el-input>
      <div id="searchPlaceOutput" />
    </ai-dialog>
  </section>
</template>

<script>
import { mapState } from 'vuex'
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'Add',
  props: {
    dict: Object,
    params: Object,
    instance: Function,
  },
  data() {
    return {
      formData: {
        name: '',
        idNumber: '',
        age: '',
        sex: '',
        phone: '',
        areaId: '',
        homesteadArea: '',
        houseArea: '',
        homesteadAddress: '',
        eastTo: '',
        southTo: '',
        westTo: '',
        northTo: '',
        landType: '0',
        houseType: '0',
        liveBuildingArea: '',
        buildingFloorNumber: '',
        buildingHeight: '',
        lng: '',
        lat: '',
        id: '',
        areaName: ''
      },
      formRules: {
        name: [
          { required: true, message: '请选择人员', trigger: 'change' },
        ],
        age: [
          { required: true, message: '请输入年龄', trigger: 'change' },
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' },
        ],
        idNumber: [
          { required: true, message: '请输入身份证号码', trigger: 'change' },
        ],
        areaId: [
          { required: true, message: '请选择所属村', trigger: 'change' },
        ]
      },
      map: null,
      placeDetail: {
        lng: '',
        lat: '',
      },
      showMap: false,
      searchPlace: '',
    }
  },
  computed: {
    ...mapState(['user']),

    isEdit() {
      return !!this.params.id
    },
  },
  mounted() {
    this.dict.load('homesteadLocationStatus', 'homesteadHouseType', 'homesteadLandType', 'sex').then(() => {
      if(this.params.id) {
        this.getListinfo()
      }
    })

  },
  methods: {
    checkName(e) {
      this.formData.name = e.name
      this.formData.idNumber = e.idNumber
      this.formData.phone = e.phone
      this.formData.areaId = e.householdAreaId
    },
    IdCard(UUserCard) {
      if (UUserCard) {
        let arr = [];
        if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
          arr.push("1");
        } else {
          arr.push("0");
        }

        const myDate = new Date();
        const month = myDate.getMonth() + 1;
        const day = myDate.getDate();
        let age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
        if (
            UUserCard.substring(10, 12) < month ||
            (UUserCard.substring(10, 12) == month &&
                UUserCard.substring(12, 14) <= day)
        ) {
          age++;
        }
        arr.push(age);
        this.formData.sex = arr[0];
        this.formData.age = arr[1];
      }
    },
    decimalInput(name) {
      if(!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/g.test(this.formData[name])){
        this.formData[name] = ''
        return this.$message.error('最多只保留两位小数点')
      }
    },
    numberInput(name) {
      if(!/^[1-9]\d*|0$/g.test(this.formData[name])){
        this.formData[name] = ''
        return this.$message.error('请输入正整数')
      }
    },
    selectMap() {
      this.formData.lng = this.placeDetail.lng
      this.formData.lat = this.placeDetail.lat
      this.showMap = false
    },
    getCorpLocation() {
      this.instance.post('/app/appdvcpconfig/getCorpLocation').then((res) => {
        if (res.code == 0) {
          this.initMap(res.data)
        }
      })
    },
    initMap({ lng, lat }) {
      AMapLoader.load({
        key: '54a02a43d9828a8f9cd4f26fe281e74e',
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],
      }).then((AMap) => {
        this.placeDetail.lng = this.formData.lng
        this.placeDetail.lat = this.formData.lat
        this.map = new AMap.Map('map', {
          resizeEnable: true,
          zooms: [6, 20],
          center: [lng, lat],
          zoom: 11,
        })
        this.placeSearch = new AMap.PlaceSearch({ map: this.map })
        new AMap.AutoComplete({
          input: 'searchPlaceInput',
          output: 'searchPlaceOutput',
        }).on('select', (e) => {
          if (e?.poi) {
            this.placeSearch.setCity(e.poi.adcode)
            this.movePosition(e.poi.location)
          }
        })
        this.map.on('click', (e) => {
          new AMap.Geocoder().getAddress(e.lnglat, (sta, res) => {
            if (res?.regeocode) {
              this.placeDetail = {
                lng: e.lnglat?.lng,
                lat: e.lnglat?.lat,
                address: res.regeocode.formattedAddress,
              }
            }
          })
          this.movePosition(e.lnglat)
        })
      })
    },

    movePosition(center) {
      if (this.map) {
        this.map.clearMap()
        this.map.panTo(center)
        this.map.add([
          new AMap.Marker({
            position: center,
            clickable: true,
          }),
        ])
        this.map.setFitView()
      }
    },

    getListinfo() {
      return this.instance
        .post('/app/apphomesteadinfo/queryDetailById', null, {
          params: {
            id: this.params.id,
          },
        })
        .then((res) => {
          if (res.data) {
            this.formData = res.data
          }
        })
    },

    confirm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.instance
            .post(`/app/apphomesteadinfo/addOrUpdate`, {
              ...this.formData,
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 1000)
              }
            })
        }
      })
    },

    // 返回按钮
    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh,
      })
    },
  },
  watch: {
    communityNameContent: {
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.Add {
  height: 100%;
  .ai-detail__title {
    background-color: #fff;
  }
  .ai-detail__content {
    .ai-detail__content--wrapper {
      .el-form {
        // background-color: #fff;
        // padding: 0 60px;
        .flex {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-form-item {
            width: 48%;
          }
          .buildingTypes {
            width: 100%;
          }
        }
      }
    }
  }

  .user-selecter {
    ::v-deep .el-input-group__append {
      width: 68px;
      background: transparent;
    }

    ::v-deep .el-button {
      color: #fff;

      &:hover {
        opacity: 0.8;
        background: linear-gradient(90deg, #299FFF 0%, #0C61FF 100%);
      }
    }
  }
}

::v-deep .mapDialog {
  .el-dialog__body {
    padding: 0;

    .ai-dialog__content {
      padding: 0;
    }

    .ai-dialog__content--wrapper {
      padding: 0 !important;
      position: relative;
    }

    #map {
      width: 100%;
      height: 420px;
    }

    .searchPlaceInput {
      position: absolute;
      width: 250px;
      top: 30px;
      left: 25px;
    }

    #searchPlaceOutput {
      position: absolute;
      width: 250px;
      left: 25px;
      height: initial;
      top: 80px;
      background: white;
      z-index: 250;
      max-height: 300px;
      overflow-y: auto;

      .auto-item {
        text-align: left;
        font-size: 14px;
        padding: 8px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
