<template>
    <div class="app-container">
      <van-nav-bar
        title="用地建房申请"
        left-arrow
        fixed
        placeholder
        @click-left="$router.back(-1)"
      />
      <p class="topTit">农村宅基地和建房（规划许可）申请表</p>
      <div class="main">
        <van-form @submit="onSubmit">
          <div v-if="applicationDetail.tHouseApplyProposer">
            <p class="main_title">申请户主信息</p>
            <div class="main_box">
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.memberName" label="姓名" placeholder="姓名" input-align="right"/>
            <van-field
              readonly
              clickable
              name="picker"
              v-model="sexValue"
              label="性别"
              placeholder="选择性别"
              @click=" auditStatus==true ? '' : showSex = true"
              input-align="right"
              right-icon="arrow-down"
              :rules="[{ required: true }]" required
            />
            <van-popup v-model="showSex" position="bottom">
              <van-picker
                show-toolbar
                :columns="userSex"
                @confirm="onConfirmSex"
                @cancel="showSex = false"
                :readonly="auditStatus"
              />
            </van-popup>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.age" label="年龄" placeholder="年龄" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.phone" label="联系电话" placeholder="联系电话" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.idcard" label="身份证号" placeholder="身份证号" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.householdRegister" label="户口所在地" placeholder="户口所在地" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.familyAddress" label="家庭住址" placeholder="家庭住址" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.members" label="家庭人口数" placeholder="家庭人口数" input-align="right"/>
            <van-cell title="是否已有宅基地">
              <template #right-icon>
                <van-radio-group :rules="[{ required: true }]" required :disabled="auditStatus" @change="existHomesteadChange" v-model="applicationDetail.tHouseApplyProposer.existHomestead" direction="horizontal">
                  <van-radio name="Y">是</van-radio>
                  <van-radio name="N">否</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
          </div>
          </div>

          <div v-if="applicationDetail.tHouseApplyFamilyMembers">
            <p class="main_title">家庭成员信息<van-button icon="plus" size="mini" type="info" native-type="button" class="addFamily" @click="addFamily" v-if="!auditStatus" /></p>
            <van-collapse  v-model="activeNames" v-if="auditStatus">
              <van-collapse-item  class="collapse" v-for="(item , index) in applicationDetail.tHouseApplyFamilyMembers" :key="index" :name="index+1">
                <template #title>
                  <van-row>
                    <van-col span="8">{{item.memberName}}</van-col>
                    <van-col span="8">{{item.age}}</van-col>
                    <van-col span="8">{{item.familyStatusName}}</van-col>
                  </van-row>
                </template>
                <van-field :readonly="auditStatus" v-model="item.memberName" label="姓名" placeholder="姓名" input-align="right"/>
                <van-field :readonly="auditStatus" v-model="item.age" label="年龄" placeholder="年龄" input-align="right"/>
                <van-field :readonly="auditStatus" v-model="item.familyStatusName" label="与户主关系" placeholder="与户主关系" input-align="right"/>
                <van-field :readonly="auditStatus" v-model="item.idcard" label="身份证号" placeholder="身份证号" input-align="right"/>
                <van-field :readonly="auditStatus" v-model="item.householdRegister" label="户口所在地" placeholder="户口所在地" input-align="right"/>
              </van-collapse-item>
            </van-collapse>
            <div class="familyList" v-if="!auditStatus" v-for="(item , index) in applicationDetail.tHouseApplyFamilyMembers" :key="index">
              <div class="main_box" style="margin-bottom: 20px">
                <van-button icon="minus" size="mini" type="danger" class="deleteFamily" native-type="button" v-if="index!=0" @click="deleteFamily(index)" />
                <van-field v-model="item.memberName" label="姓名" placeholder="姓名" input-align="right"/>
                <van-field v-model="item.age" label="年龄" placeholder="年龄" input-align="right"/>
                <van-field v-model="item.familyStatusName" label="与户主关系" placeholder="与户主关系" input-align="right"/>
                <van-field v-model="item.idcard" label="身份证号" placeholder="身份证号" input-align="right"/>
                <van-field v-model="item.householdRegister" label="户口所在地" placeholder="户口所在地" input-align="right"/>
              </div>
            </div>
<!--            <div class=" familyList">-->
<!--              <van-button icon="minus" size="mini" type="danger" class="deleteFamily" />-->
<!--              <div class="main_box">-->
<!--                <van-field label="姓名" placeholder="姓名" input-align="right"/>-->
<!--                <van-field label="年龄" placeholder="年龄" input-align="right"/>-->
<!--                <van-field label="与户主关系" placeholder="与户主关系" input-align="right"/>-->
<!--                <van-field label="身份证号" placeholder="身份证号" input-align="right"/>-->
<!--                <van-field label="户口所在地" placeholder="户口所在地" input-align="right"/>-->
<!--              </div>-->
<!--            </div>-->
          </div>

          <div v-if="CurrentSituation">
            <p class="main_title">现宅基地及农房状况</p>
            <div class="main_box">
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.landArea" label="宅基地面积" placeholder="宅基地面积" input-align="right"/>
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.landPerArea" label="人均宅基地面积" placeholder="人均宅基地面积㎡" input-align="right" label-width="auto"/>
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.landCertificateNo" label="不动产单元号" placeholder="不动产单元号" input-align="right"/>
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.buildingArea" label="建筑面积" placeholder="建筑面积㎡" input-align="right"/>
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.buildingPerArea" label="人均建筑面积" placeholder="人均建筑面积㎡" input-align="right"/>
              <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyCurrentSituation.houseCertificateNo" label="农民房屋幢号" placeholder="户口所在地" input-align="right"/>
              <van-field
                readonly
                clickable
                name="picker"
                :value="landIsposalValue"
                label="处置情况"
                placeholder="选择宅基地处置情况"
                @click=" auditStatus==true ? '' : showLandIsposal = true"
                input-align="right"
                right-icon="arrow-down"
                :readonly="auditStatus"
                :rules="[{ required: true }]" required
              />
              <van-popup v-model="showLandIsposal" position="bottom">
                <van-picker
                  show-toolbar
                  :columns="landIsposal"
                  @confirm="onConfirmLandIsposal"
                  @cancel="showLandIsposal = false"
                  :readonly="auditStatus"
                />
              </van-popup>

  <!--            <van-field-->
  <!--              readonly-->
  <!--              clickable-->
  <!--              name="picker"-->
  <!--              :value="applicationDetail.tHouseApplyCurrentSituation.buildingType"-->
  <!--              label="建房类型"-->
  <!--              placeholder="选择建房类型"-->
  <!--              @click="showBuildingType = true"-->
  <!--              input-align="right"-->
  <!--              right-icon="arrow-down"-->
  <!--            />-->
  <!--            <van-popup v-model="showBuildingType" position="bottom">-->
  <!--              <van-picker-->
  <!--                show-toolbar-->
  <!--                :columns="buildingType"-->
  <!--                @confirm="onConfirmBuildingType"-->
  <!--                @cancel="showBuildingType = false"-->
  <!--              />-->
  <!--            </van-popup>-->
            </div>
          </div>

          <div v-if="applicationDetail.tHouseApplyProposedSituation">
            <p class="main_title">拟申请宅基地及建房情况</p>
            <div class="main_box">
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.location" label="拟建位置" placeholder="拟建位置" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.landArea" label="宅基地面积" placeholder="宅基地面积" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.east" label="东至" placeholder="东至" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.west" label="西至" placeholder="西至" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.south" label="南至" placeholder="南至" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.north" label="北至" placeholder="北至" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.buildingArea" label="建筑面积" placeholder="建筑面积" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.buildingFloors" label="建筑层数" placeholder="建筑层数" input-align="right"/>
            <van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.buildingHight" label="建筑高度" placeholder="建筑高度" input-align="right"/>
            <van-cell title="是否征求相邻权利人意见">
              <template #right-icon>
                <van-radio-group :disabled="auditStatus" v-model="applicationDetail.tHouseApplyProposedSituation.isAdvice" direction="horizontal">
                  <van-radio name="1">是</van-radio>
                  <van-radio name="2">否</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
            <van-field
              readonly
              clickable
              name="picker"
              v-model="housingStructureValue"
              label="房屋构造"
              placeholder="选择房屋构造"
              @click=" auditStatus==true ? '' : showHousingStructure = true"
              input-align="right"
              right-icon="arrow-down"
              :rules="[{ required: true }]" required
            />
            <van-popup v-model="showHousingStructure" position="bottom">
              <van-picker
                show-toolbar
                :columns="housingStructure"
                @confirm="onConfirmHousingStructure"
                @cancel="showHousingStructure = false"
                :readonly="auditStatus"
              />
            </van-popup>
            <van-field
              readonly
              clickable
              name="picker"
              :value="buildingTypeValue"
              label="建房类型"
              placeholder="选择建房类型"
              @click=" auditStatus==true ? '' : showBuildingType = true"
              input-align="right"
              right-icon="arrow-down"
              :rules="[{ required: true }]" required
            />
            <van-popup v-model="showBuildingType" position="bottom">
              <van-picker
                show-toolbar
                :columns="buildingType"
                @confirm="onConfirmBuildingType"
                @cancel="showBuildingType = false"
              />
            </van-popup>
            <van-cell title="设计图纸">
              <template #right-icon>
                <van-radio-group :disabled="auditStatus" @change="designPaperChange" v-model="applicationDetail.tHouseApplyProposedSituation.designPaper" direction="horizontal">
                  <van-radio name="1">委托设计</van-radio>
                  <van-radio name="2">选通用图</van-radio>
                </van-radio-group>
              </template>
            </van-cell>
            <van-field
              readonly
              clickable
              name="picker"
              :value="houseTypeValue"
              placeholder="选择户型图"
              @click=" auditStatus==true ? '' : showHouseType = true"
              input-align="right"
              right-icon="arrow-down"
              v-if="showHouse"
              :rules="[{ required: true }]" required
            />
            <van-popup v-model="showHouseType" position="bottom">
              <van-picker
                show-toolbar
                :columns="houseType"
                @confirm="onConfirmHouseType"
                @cancel="showHouseType = false"
              />
            </van-popup>
          </div>
            <div class="mapBox">
              <div id="mapWrap" style="height: 200px;"></div>
              <div class="mapBox_button">
                <van-button id="drawPolygon" native-type="button" icon="../../../static/images/icon/icon_ht.png" type="default" block round size="small"></van-button>
                <van-button id="drawRemove" native-type="button" icon="cross" type="default" block round size="small" style="margin-top: 0.2rem"></van-button>
              </div>
            </div>
          </div>

          <div v-if="applicationDetail.tHouseApplyProposer">
            <p class="main_title">申请理由</p>
            <div class="main_box">
            <van-field
              rows="3"
              autosize
              type="textarea"
              placeholder="申请理由"
              input-align="left"
              v-model="applicationDetail.tHouseApplyProposer.applyReasion"
              :readonly="auditStatus"
              :rules="[{ required: true }]" required
            />
            <van-row>
              <van-col span="12"><van-field :rules="[{ required: true }]" required :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.memberName" label="申请人" placeholder="申请人" input-align="left" label-width="auto"/></van-col>
              <van-col span="12">
                <van-field :rules="[{ required: true }]" required :readonly="auditStatus" clickable v-model="applicationDetail.tHouseApplyProposer.applyTime" label-width="auto" placeholder="选择日期" @click="showApplyTime = true">
                  <template #label>
                    <van-icon name="notes-o" size="20"/>
                  </template>
                </van-field>
                <van-calendar v-model="showApplyTime" @confirm="onConfirmApplyTime" />
<!--                <van-field :readonly="auditStatus" v-model="applicationDetail.tHouseApplyProposer.applyTime == '' ? nowTime : applicationDetail.tHouseApplyProposer.applyTime" label-width="auto">-->
<!--                  <template #label>-->
<!--                    <van-icon name="notes-o" size="20"/>-->
<!--                  </template>-->
<!--                </van-field>-->
              </van-col>
            </van-row>
          </div>
          </div>

          <div v-for="(item , index) in fileArray" :key="index">
            <p class="main_title">{{item.fileTypeName}}</p><!-- 未对接 -->
            <div class="main_box file-box">
<!--              <van-uploader v-if="item.findList" v-model="item.findList" multiple />-->
              <van-uploader :after-read="afterRead" :before-delete="deleteFile" v-model="item.findList" multiple />
            </div>
          </div>
          <div v-if="applicationDetail.tHouseApplyProposer" style="margin: 16px;">
            <van-row>
              <van-col span="12" align="center">
                <van-button type="info" native-type="submit" class="submitButton">保存</van-button>
              </van-col>
              <van-col span="12" align="center">
                <van-button type="info" native-type="submit" class="submitButton">保存并提交</van-button>
              </van-col>
            </van-row>
            <div class="clear"></div>
          </div>
        </van-form>
      </div>
    </div>
</template>

<script>
  import { treeSingleProcessView  , saveHouseBaseInfo , houseList , attach , removeFile , getHouseMembers } from "@/api/onlineHome/homestead/application";
  import {getQueryLand} from "@/api/homesteadSurvey/zjdzd";
  import $ from "jquery";
  export default {
  name: "applicationForm",
  data() {
    return {
      active: 0,
      nowTime: '',//当前日期
      fileList: [],
      fileList2: [],
      radio:'1',
      value: '',
      columns: ['杭州', '宁波', '温州', '嘉兴', '湖州'],
      showPicker: false,
      showBuildingType: false,
      showLandIsposal: false,
      showHousingStructure: false,
      showStartDate: false,
      showEndDate: false,
      showApplyTime:false,
      showHouseType:false,
      showHouse:false,
      showSex:false,
      id:'',
      applicationDetail:{
        //上传文件id
        fileList: [],
        tHouseApplyProposer: {
          memberName: '',
          farmerCode: "",
          sex: "",
          age: '',
          phone: "",
          idcard: "",
          householdRegister: "",
          familyAddress: "",
          members: '',
          applyReasion: "",
          houseSource: '',
          existHomestead: "Y"
        },
        tHouseApplyFamilyMembers: [
          {
            memberName: "",
            age: '',
            idcard: "",
            familyStatusName: "",
            householdRegister: ""
          }
        ],
        tHouseApplyCurrentSituation: {
          landArea: "",
          landPerArea: "",
          landCertificateNo: "",
          buildingPerArea: "",
          houseCertificateNo: "",
          landIsposal: "",
          reservedArea: "",
          otherRemark: "",
          buildingType: "",
          buildingArea: ""
        },
        tHouseApplyProposedSituation: {
          location: "",
          landArea: "",
          east: "",
          west: "",
          south: "",
          north: "",
          geographicType: "",
          constructionLandArea: "",
          unusedLandArea: "",
          agriculturalLandArea: "",
          farmLandArea: "",
          forestLandArea: "",
          buildingArea: "",
          buildingFloors: "",
          buildingHight: "",
          designPaper: "1",
          housingStructure: "",
          isAdvice: "1",
          buildingType: "",
          theGeom:''
        }
      },
      //建房类型字典
      buildingType:[],
      //处置情况字典
      landIsposal:[],
      //房屋构造字典
      housingStructure:[],
      //性别字典
      userSex:[],
      //户型
      houseType:[],
      //请求参数
      parameter:{
        businessType: "house",
        houseApplyStatus: 1,
        processKey: "baseApply",
        tableName: "t_house_apply_proposer"
      },
      //文件配置
      fileArray:[],
      //获取上传附件
      params:{
        tableId: '',
        tableName: "t_house_apply_proposer",
        fileType: ''
      },
      auditStatus:false,
      activeNames:['1'],
      housingStructureValue:'',//当前显示房屋构造
      buildingTypeValue:'',//当前显示建房类型
      landIsposalValue:'',//当前显示处置情况
      houseTypeValue:'',//当前显示户型
      sexValue:'',//当前显示性别
      CurrentSituation:false,
    };
  },
  created() {
    this.getDetail()
  },
  methods: {
    afterRead(file) {
      this.$forceUpdate();
      return;
      // 此时可以自行将文件上传至服务器
      for ( var i = 0 ; i < this.fileList.length ; i++){
        if(this.fileList[i].url == undefined&&this.fileList!='') {
          this.fileList[i] = {url:this.fileList[i].content, id: '', isImage: true};
        }
      }
    },
    //删除图片
    deleteFile(elIndex){
      if(elIndex.id != ''){
        removeFile(elIndex.id).then(response => {});
      }
      this.$forceUpdate();
      return (file, name) => {
        let fileIndex = name.index
        this.fileList[elIndex].splice(fileIndex, 1)
        this.upLoadList[elIndex].splice(fileIndex, 1)
      }
    },
    //获取数据集合
    getDetail(){
      //性别字典查询
      // this.houseGetDicts("sys_user_sex").then((res) => {
      //   response.data.tHouseApplyProposer.sex = this.selectDictLabel(res.data, response.data.tHouseApplyProposer.sex);
      // });

      //建房类型字典查询
      this.houseGetDicts("building_type").then((res) => {
        res.data.map(item => {
          this.buildingType.push({ value:item.dictValue, text: item.dictLabel});
        });
      });
      //房屋构造字典查询
      this.houseGetDicts("housing_structure").then((res) => {
        res.data.map(item => {
          this.housingStructure.push({ value:item.dictValue, text: item.dictLabel});
        });
      });
      //处置情况字典查询
      this.CurrentSituation = true ;
      this.houseGetDicts("land_isposal").then((res) => {
        res.data.map(item => {
          this.landIsposal.push({ value:item.dictValue, text: item.dictLabel});
        });
      });
      //户型图查询
      houseList().then(res => {
        res.rows.map(item => {
          this.houseType.push({ value:item.id, text: item.name});
        });
      });
      //获取上传文件列表
      treeSingleProcessView(this.parameter).then(res => {
        this.fileArray = res.rows
      });
      //获取上传文件列表
      getHouseMembers().then(res => {
        this.applicationDetail.tHouseApplyProposer = res.data.tHouseApplyProposer;
        this.applicationDetail.tHouseApplyFamilyMembers = res.data.tHouseApplyFamilyMembers;
        //性别字典查询
        this.houseGetDicts("sys_user_sex").then((res2) => {
          res2.data.map(item => {
            this.userSex.push({ value:item.dictValue, text: item.dictLabel});
          });
          this.sexValue = this.selectDictLabel(res2.data, res.data.tHouseApplyProposer.sex);
        });
        var that = this ;
        setTimeout(function(){
          that.pointDarw();
        },2000)
      });
    },
    onConfirmApplyTime(date) {
      this.applicationDetail.tHouseApplyProposer.applyTime = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      this.showApplyTime = false;
    },
    //基地开工时间
    onConfirmStartDate(date) {
      this.applicationDetail.tHouseApplyStart.startDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      this.showStartDate = false;
    },
    //基地竣工时间
    onConfirmEndDate(date) {
      this.applicationDetail.tHouseApplyStart.endDate = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
      this.showEndDate = false;
    },
    //选择性别
    onConfirmSex(data){
      this.sexValue = data.text;
      this.applicationDetail.tHouseApplyProposer.sex = data.value;
      this.showSex = false;
    },
    //选择建房类型
    onConfirmBuildingType(data){
      this.buildingTypeValue = data.text;
      this.applicationDetail.tHouseApplyProposedSituation.buildingType = data.value;
      this.showBuildingType = false;
    },
    //选择宅基地处置情况
    onConfirmLandIsposal(data){
      this.landIsposalValue = data.text;
      this.applicationDetail.tHouseApplyCurrentSituation.landIsposal = data.value;
      this.showLandIsposal = false;
    },
    //选择房屋构造
    onConfirmHousingStructure(data){
      this.housingStructureValue = data.text;
      this.applicationDetail.tHouseApplyProposedSituation.housingStructure = data.value;
      this.showHousingStructure = false;
    },
    //选择户型
    onConfirmHouseType(data){
      this.houseTypeValue = data.text;
      this.applicationDetail.tHouseApplyProposedSituation.houseTypeId = data.value;
      this.showHouseType = false;
    },
    //添加家庭成员
    addFamily(){
      this.applicationDetail.tHouseApplyFamilyMembers.push({
        applyProposerId:this.applicationDetail.tHouseApplyFamilyMembers[0].applyProposerId,
        memberName:'',
        age:'',
        familyStatusName:'',
        idcard :'',
        householdRegister:'',
      });
    },
    //删除家庭成员
    deleteFamily(index){
      this.applicationDetail.tHouseApplyFamilyMembers.splice(index,1)
    },
    //是否有宅基地选项改变
    existHomesteadChange(name){
      if (name == 'Y'){
        if (this.applicationDetail.tHouseApplyCurrentSituation == null){
          //现宅基地情况
          this.applicationDetail.tHouseApplyCurrentSituation = {
            //宅基地面积
            landArea: '',
            //人均宅基地面积
            landPerArea: '',
            //不动产单元号
            landCertificateNo: '',
            //农民房屋幢号
            houseCertificateNo: '',
            //建筑面积
            buildingArea: '',
            //人均建筑面积
            buildingPerArea: '',
            //现宅基地处置情况 字典 land_isposal
            landIsposal: ""
          };
          this.CurrentSituation = true ;
          //处置情况字典查询
          this.houseGetDicts("land_isposal").then((res) => {
            res.data.map(item => {
              this.landIsposal.push({ value:item.dictValue, text: item.dictLabel});
            });
            this.landIsposalValue= this.selectDictLabel(res.data, this.applicationDetail.tHouseApplyCurrentSituation.landIsposal);
          });
        }
        this.CurrentSituation = true;
      }else{
        this.CurrentSituation = false;
      }
    },
    //图纸选择改变
    designPaperChange(name){
      if(name == 2){
        this.showHouse = true;
      }else{
        this.showHouse = false;
      }
    },
    base64toFile(dataurl, filename = "file") {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    //申请提交
    onSubmit(){
      var that = this;
      let form = {};
      form.fileList=[];
      if (this.drawInsert != null) {
        this.applicationDetail.tHouseApplyProposedSituation.theGeom = JSON.stringify(this.drawInsert);
      }
      for (let i = 0 ; i < this.fileArray.length ; i++){
        if (this.fileArray[i].findList == null || this.fileArray[i].findList == undefined || this.fileArray[i].findList == ''){
          continue
        }
        for (let j = 0 ; j < this.fileArray[i].findList.length ; j++){
          const params = new FormData()
          params.append('tableId', '')
          params.append('tableName', 't_house_apply_proposer')
          params.append('bizPath', 't_house_apply_proposer')
          params.append('fileType', this.fileArray[i].fileType)
          if (this.fileArray[i].findList[j].url){
            continue;
          }
          params.append('file', this.base64toFile(this.fileArray[i].findList[j].content))
          attach(params).then(res => {
            form.fileList.push(res.id);
          });
        }
      }
      form.tHouseApplyProposer=this.applicationDetail.tHouseApplyProposer;
      form.tHouseApplyFamilyMembers=this.applicationDetail.tHouseApplyFamilyMembers;
      form.tHouseApproveVillageOptions=this.applicationDetail.tHouseApproveVillageOptions;
      form.tHouseApplyCurrentSituation=this.applicationDetail.tHouseApplyCurrentSituation;
      form.tHouseApplyProposedSituation=this.applicationDetail.tHouseApplyProposedSituation;
      setTimeout(function(){
        saveHouseBaseInfo(form).then(res => {
          console.log(res)
          if(res.code = 200){
            that.$toast.success('保存成功');
          }
        });
      },1000)
    },
    pointDarw() {
      //地图只加载一次
      this.landOpen = false;
      //加载地图编辑
      var that = this;
      var map;
      //var hc_land;
      var draw; // global so we can remove it later
      var vector_drawing;
      var minMapZoom;
      var maxMapZoom;
      var zoomLook;
      if (this.formEditor) {
        zoomLook = 18
        minMapZoom = 18
        maxMapZoom = 18
      } else {
        zoomLook = 16.9
        minMapZoom = 16
        maxMapZoom = 18.9
      }
      if (this.applicationDetail.tHouseApplyProposedSituation.theGeom != null && this.applicationDetail.tHouseApplyProposedSituation.theGeom != ""
        && this.applicationDetail.tHouseApplyProposedSituation.theGeom != undefined) {
        this.startDarw = true;
        this.openDarw = false;
      } else {
        this.startDarw = false;
        this.openDarw = true;
      }
      if (this.startDarw) {
        document.getElementById("mapWrap").innerHTML = '';
        var hc_land;
        var draw; // global so we can remove it later
        var vector_drawing;
        var projection = new ol.proj.Projection({
          //地图投影类型
          code: "EPSG:3857",
          units: "degrees",
          //extent:extent
        });

        var aerial = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "http://t0.tianditu.gov.cn/img_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "卫星影像图",
        });

        var yingxzi = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "天地图文字标注--卫星影像图",
        });
        //加载地图
        map = new ol.Map({
          // interactions: ol.interaction.DragPan({
          //   onFocusOnly: false
          // }),
          controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]), //隐藏放大缩小按钮
          layers: [aerial, yingxzi],
          projection: projection,
          target: "mapWrap",
          view: new ol.View({
            //center: ol.proj.fromLonLat([115.452752, 31.789033]),
            zoom: zoomLook,
            minZoom: minMapZoom, //地图缩小限制
            maxZoom: maxMapZoom, //地图放大限制
          }),
        });
        if (this.formEditor) {
          let pan = getPan();
          //false：当前地图不可拖动。true：可拖动
          pan.setActive(false);

          function getPan() {
            let pan = '';
            map.getInteractions().forEach(function (element, index, array) {
              if (element instanceof ol.interaction.DragPan) {
                pan = element;
              }
            })
            return pan;
          }
        }
        //图层查询定位开始 ---------start
        hc_land = new ol.layer.Vector({
          title: "add Layer",
          source: new ol.source.Vector({
            projection: projection,
            features: new ol.format.GeoJSON().readFeatures("{\n" +
              "    \"type\": \"Feature\",\n" +
              "    \"geometry\":" + this.applicationDetail.tHouseApplyProposedSituation.theGeom + "}"),
          }),
          style: new ol.style.Style({
            fill: new ol.style.Fill({
              //矢量图层填充颜色，以及透明度
              color: "rgba(204, 255, 204,0.3)",
            }),
            stroke: new ol.style.Stroke({
              //边界样式
              color: "#47c68f",
              width: 3,
            }),
          }),
        });
        map.addLayer(hc_land);
        var maxXMap = hc_land.values_.source.featuresRtree_.rbush_.data.maxX;
        var maxYMap = hc_land.values_.source.featuresRtree_.rbush_.data.maxY;
        var minXMap = hc_land.values_.source.featuresRtree_.rbush_.data.minX;
        var minYMap = hc_land.values_.source.featuresRtree_.rbush_.data.minY;
        //定位查询位置
        var center = ol.extent.getCenter([maxXMap, maxYMap, minXMap, minYMap]); //获取边界区域的中心位置
        map.getView().animate({
          // 只设置需要的属性即可
          center: center, // 中心点
          zoom: 17.9, // 缩放级别
          rotation: undefined, // 缩放完成view视图旋转弧度
          duration: 1000, // 缩放持续时间，默认不需要设置
        });
        //图层查询定位结束 ---------end
        //开始绘制地图
        $("#drawPolygon").click(function () {
          map.removeLayer(hc_land);
          map.removeLayer(vector_drawing);
          that.drawInsert = null;
          map.removeInteraction(draw);
          var source = new ol.source.Vector({wrapX: false});
          vector_drawing = new ol.layer.Vector({
            source: source,
          });
          map.addLayer(vector_drawing);
          var typeSelect = "Polygon";

          function addInteraction() {
            var value = typeSelect;
            draw = new ol.interaction.Draw({
              source: source,
              type: typeSelect
            });
            draw.on('drawend', function (evt) {
              console.log(that.drawInsert);
              if(that.drawInsert != null){
                $("#drawRemove").trigger('click');
              }
              var feature = evt.feature;
              var geometry = feature.getGeometry();
              var coordinate = geometry.getCoordinates();
              that.drawInsert = coordinate;
              map.removeInteraction(draw);
            });
            map.addInteraction(draw);
          }
          addInteraction();
        });
        //清除画图鼠标点击事件
        $("#drawRemove").click(function () {
          that.drawInsert = null;
          map.addLayer(hc_land);
          map.removeInteraction(draw);
          map.removeLayer(vector_drawing);
        });
      }
      if (this.openDarw) {
        document.getElementById("mapWrap").innerHTML = '';
        var projection = new ol.proj.Projection({
          //地图投影类型
          code: "EPSG:3857",
          units: "degrees",
          //extent:extent
        });

        var aerial = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "http://t0.tianditu.gov.cn/img_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "卫星影像图",
        });

        var yingxzi = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "天地图文字标注--卫星影像图",
        });
        //获取坐标是否存在
        var Zb;
        getQueryLand().then((response) => {
          if (response.code == 200) {
            let InsertCode = response.data;
            console.log(response);
            if (InsertCode != null) {
              var lat = InsertCode.lat;
              var lng = InsertCode.lng;
              if (lat != null && lng != null && lat != "" && lng != "") {
                Zb = [lng,lat];
              } else {
                Zb = [115.452752, 31.789033];
              }
            }
          }
          //加载地图
          map = new ol.Map({
            controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]), //隐藏放大缩小按钮
            layers: [aerial, yingxzi],
            projection: projection,
            logo: 'false',
            target: "mapWrap",
            view: new ol.View({
              center: ol.proj.fromLonLat(Zb),
              //center: ol.proj.fromLonLat([115.452752, 31.789033]),
              zoom: 16.9,
              minZoom: minMapZoom, //地图缩小限制
              maxZoom: maxMapZoom, //地图放大限制
            }),
          });
        });

        //图层查询定位结束 ---------end
        //开始绘制地图
        $("#drawPolygon").click(function () {
          //map.removeLayer(hc_land);
          map.removeLayer(vector_drawing);
          that.drawInsert = null;
          map.removeInteraction(draw);
          var source = new ol.source.Vector({wrapX: false});
          vector_drawing = new ol.layer.Vector({
            source: source,
          });
          map.addLayer(vector_drawing);
          var typeSelect = "Polygon";

          function addInteraction() {
            var value = typeSelect;
            draw = new ol.interaction.Draw({
              source: source,
              type: typeSelect
            });
            draw.on('drawend', function (evt) {
              console.log(that.drawInsert);
              if(that.drawInsert != null){
                $("#drawRemove").trigger('click');
              }
              var feature = evt.feature;
              var geometry = feature.getGeometry();
              var coordinate = geometry.getCoordinates();
              that.drawInsert = coordinate;
              map.removeInteraction(draw);
            });
            map.addInteraction(draw);
          }
          addInteraction();
        });
        //清除画图鼠标点击事件
        $("#drawRemove").click(function () {
          that.drawInsert = null;
          map.removeInteraction(draw);
          map.removeLayer(vector_drawing);
        });
      }
    },
  },
}
</script>

<style scoped lang="scss">
  .app-container {
    padding-bottom: 5%;
  }
  #mapWrap{
    width: 96%;
    margin: 0 auto;
    border-bottom-left-radius: 12px;
    border-bottom-right-radius: 12px;
    overflow: hidden;
  }
  .mapBox{
    position: relative;
    .mapBox_button{
      position: absolute;
      top: 0.2rem;
      right: 2%;
    }
  }
  .van-steps{
    padding: 2% 6% 0;
  }
  .topTit{
    margin-top: 0.4rem;
    font-size: 0.45rem;
    background-color: #1D6FE9;
    color: #FFFFFF;
    line-height: 58px;
    text-align: center;
    padding: 15px 0;
    box-shadow: 0px 3px 6px 0px rgba(15,67,145,0.40);
  }
  .main_title{
    font-size: 0.4rem;
    color: #1D6FE9;
    margin: 0.2rem 6%;
    position: relative;
  }
  .main_box{
    width: 96%;
    margin: 0 auto;
    border-radius: 6px;
    box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);
    overflow: hidden;
    background-color: #FFF;
  }
  .collapse{
    width: 96%;
    margin: 0 auto;
    border-radius: 6px;
    box-shadow: 0px 3px 6px 0px rgba(0,0,0,0.16);
    overflow: hidden;
    margin-bottom: 15px;
  }
  /deep/.van-radio--horizontal{
    margin-left: 20px;
    margin-right: 0;
  }
  .file-box{
    padding: 2% 5% 0;
  }
  .submitButton{
    width: 80%;
    margin: 0 auto;
    background-color: #1D6FE9;
    border-radius: 14px;
  }
  .timeTit{
    text-align: center;
    font-size: 16px;
    line-height: 27px;
  }
  .action-box{
    padding: 15px 0!important;
    margin-top: 0.4rem;
  }
  .check-box{
    margin-top: 0.4rem;
  }
  .addFamily{
    position: absolute;
    top: -2px;
    right: 0;
    border-radius: 50%;
  }
  .deleteFamily{
    position: absolute;
    top: -0.3rem;
    right: 6%;
    z-index: 9;
    border-radius: 50%;
  }
  .familyList{
    margin-top: 0.4rem;
    position: relative;
  }
  .noModify{
    .topTit{
      background-color:#ABABAB ;
      box-shadow: 0px 3px 6px 0px rgba(171,171,171,0.40);
    }
    .van-cell__title{
      color: #B4B0B0;
    }
  }
</style>
