<template>
  <div class="app-container">

    <van-nav-bar left-arrow fixed placeholder @click-left="goBack" >
      <template #title>
        <div class="tb_main">
          {{ titleName }}
        </div>
      </template>
    </van-nav-bar>

    <!-- <div class="tap_block">
      <p @click="$router.push({path:'/contracted/village/contractor', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">承包方</p>
      <p @click="$router.push({path:'/contracted/village/employer', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">发包方</p>
      <p class="active">地块</p>
      <p @click="$router.push({path:'/contracted/village/map', query: { deptId: $route.query.deptId, deptName: $route.query.deptName }})">地图</p>
    </div> -->

    <div class="list_main">
      <van-form ref="formData">
        <van-field v-model="form.dkbm" label="地块代码：" placeholder="<自动生成>" :border="false" input-align="right" label-width="auto" :disabled="true" maxlength="19">
          <!-- <template #button v-if="!$route.query.id">
            <van-button size="mini" type="primary" native-type="button" @click="generateCode">生成代码</van-button>
          </template> -->
        </van-field>
        <van-field v-model="form.dkmc" label="地块名称：" placeholder="请输入地块名称" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field v-model="syqxzText" label="所有权性质："
                   placeholder="请选择所有权性质"
                   required
                   :rules="[{ required: true }]"
                   :border="false"
                   input-align="right"
                   right-icon="arrow-down"
                   readonly
                   clickable
                   @click="showOwnership = true"
        />
        <van-popup v-model="showOwnership" position="bottom">
          <van-picker
            show-toolbar
            :columns="syqxzOptions"
            value-key="dictLabel"
            @confirm="onConfirmOwnershipOptions"
            @cancel="showOwnership = false"
          />
        </van-popup>
        <van-field v-model="dklbText" label="地块类别："
                   placeholder="请选择地块类别"
                   required
                   :rules="[{ required: true }]"
                   :border="false"
                   input-align="right"
                   right-icon="arrow-down"
                   readonly
                   clickable
                   @click="openLandCategoryPopup"
        />
        <van-popup v-model="showLandCategory" position="bottom">
          <van-picker
            show-toolbar
            :columns="dklbOptions"
            value-key="dictLabel"
            @confirm="onConfirmLandCategoryOptions"
            @cancel="showLandCategory = false"
          />
        </van-popup>
        <van-field v-model="tdlylxText" label="土地利用类型："
                   placeholder="请选择土地利用类型"
                   required
                   :rules="[{ required: true }]"
                   :border="false"
                   input-align="right"
                   right-icon="arrow-down"
                   readonly
                   clickable
                   @click="showLandType = true"
        />
        <van-popup v-model="showLandType" position="bottom">
          <van-picker
            show-toolbar
            :columns="tdlylxOptions"
            value-key="dictLabel"
            @confirm="onConfirmLandTypeOptions"
            @cancel="showLandType = false"
          />
        </van-popup>
        <van-field v-model="dldjText" label="地力等级："
                   placeholder="请选择地力等级"
                   required
                   :rules="[{ required: true }]"
                   :border="false"
                   input-align="right"
                   right-icon="arrow-down"
                   readonly
                   clickable
                   @click="showLandGrade = true"
        />
        <van-popup v-model="showLandGrade" position="bottom">
          <van-picker
            show-toolbar
            :columns="dldjOptions"
            value-key="dictLabel"
            @confirm="onConfirmLandGradeOptions"
            @cancel="showLandGrade = false"
          />
        </van-popup>
        <van-field v-model="tdytText" label="土地用途："
                   placeholder="请选择土地用途"
                   required
                   :rules="[{ required: true }]"
                   :border="false"
                   input-align="right"
                   right-icon="arrow-down"
                   readonly
                   clickable
                   @click="showLandPurpose = true"
        />
        <van-popup v-model="showLandPurpose" position="bottom">
          <van-picker
            show-toolbar
            :columns="tdytOptions"
            value-key="dictLabel"
            @confirm="onConfirmLandPurposeOptions"
            @cancel="showLandPurpose = false"
          />
        </van-popup>
        <van-field v-model="form.sfjbnt" label="基本农田：" required :rules="[{ required: true }]" :border="false" input-align="right" >
          <template #input>
            <van-radio-group v-model="form.sfjbnt" direction="horizontal">
              <!-- <van-radio name="1">是</van-radio>
              <van-radio name="2">否</van-radio> -->
              <van-radio v-for="dict in sfjbntOptions" :ke="dict.dictValue" :name="dict.dictValue">{{ dict.dictLabel }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-model="form.scmjm" type="number" label="实测面积(亩)：" placeholder="请输入实测面积(亩)" required :rules="[{ required: true }]" :border="false" input-align="right" />
        <van-field v-model="form.zjrxm" label="指界人姓名：" placeholder="请输入指界人姓名" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="100" />
        <van-field v-model="form.dkdz" label="地块东至：" placeholder="请输入地块东至" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field v-model="form.dkxz" label="地块西至：" placeholder="请输入地块西至" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field v-model="form.dknz" label="地块南至：" placeholder="请输入地块南至" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field v-model="form.dkbz" label="地块北至：" placeholder="请输入地块北至" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field v-model="form.dkbzxx" label="地块备注信息：" placeholder="请输入地块备注信息" type="textarea" rows="3" :border="false" input-align="right" maxlength="250" />

        <div class="mapBox">
          <common-map ref="landMap" :minMapZoom="15" :maxMapZoom="18" :allowDraw="true" @drawFinished="onMapDrawFinished" />
        </div>
      </van-form>
      <p class="btn" @click="submitForm" v-if="taskStatus === '2'">保存</p>
    </div>


  </div>
</template>
<script>
  import Cookies from "js-cookie";
  import { getDk, addDk, updateDk, generateLandCode } from "@/api/contracted/dk";
  import { getDept } from "@/api/contracted";
  import CommonMap from "@/components/house/CommonMap";

  export default {
    name: "contractedVillageContractor",
    components: {
      CommonMap
    },
    data() {
      return {
        loading:false,
        finished:true,
        value:'',
        showType:false,
        showZjType:false,
        showTDYT:false,
        showSYQXZ:false,
        showDKLB:false,
        typeOptions:[{
          dictLabel:'类型1',
          dictValue:'1',
        }],
        zjTypeOptions:[{
          dictLabel:'类型2',
          dictValue:'1',
        }],
        TDYTOptions:[{
          dictLabel:'类型2',
          dictValue:'1',
        }],
        radio:1,
        minDate: new Date(2020, 0, 1),
        maxDate: new Date(2025, 10, 1),
        currentDate: new Date(2021, 0, 17),

        titleName: '',                    // 标题信息
        form: {},                         // 地块信息表单
        syqxzOptions: [],                 // 所有权性质字典
        syqxzText: null,                  // 所有权性质标签名
        showOwnership: false,             // 控制所有权性质字典弹出层的显示和隐藏
        dklbOptions: [],                  // 地块类别字典
        dklbText: null,                   // 地块类别标签名
        showLandCategory: false,          // 控制的地块类别字典弹出层的显示和隐藏
        dldjOptions: [],                  // 地力等级字典
        dldjText: null,                   // 地力等级标签名
        showLandGrade: false,             // 控制地力等级字典弹出层的显示和隐藏
        tdytOptions: [],                  // 土地用途字典
        tdytText: null,                   // 土地用途标签名
        showLandPurpose: false,           // 控制土地用途字典弹出层的显示和隐藏
        tdlylxOptions: [],                // 土地利用类型
        tdlylxText: null,                 // 土地利用类型标签名
        showLandType: false,              // 控制土地利用类型字典弹出层的显示和隐藏
        sfjbntOptions: [],                // 是否基本农田字典
        taskStatus: null,                 // 调查任务的完成状态：1表示已完成，2表示未完成
      };
    },
    created() {
      this.taskStatus = Cookies.get('taskStatus');
      this.getDicts("land_ownership").then(response => {
        this.syqxzOptions = response.data;
      });
      this.getDicts("land_type").then(response => {
        this.dklbOptions = response.data;
        /* // 新增地块信息的时候，去除地块类别中的承包地块选项
        if (!this.$route.query.id) {
          let index = this.dklbOptions.findIndex(item => item.dictValue === '10');
          this.dklbOptions.splice(index, 1);
        } */
        // 去除地块类别中的承包地块选项
        let index = this.dklbOptions.findIndex(item => item.dictValue === '10');
        this.dklbOptions.splice(index, 1);
      });
      this.getDicts("land_grade").then(response => {
        this.dldjOptions = response.data;
      });
      this.getDicts("use_code").then(response => {
        this.tdytOptions = response.data;
      });
      this.getDicts("land_use").then(response => {
        this.tdlylxOptions = response.data;
      });
      this.getDicts("is_common").then(response => {
        this.sfjbntOptions = response.data;
      });
    },
    mounted() {
      if (this.$route.query.id) {
        this.titleName = '修改地块信息';
        setTimeout(() => {
          this.getDetail();
        }, 500);
      } else {
        this.titleName = '新增地块信息';
        this.resetForm();
        this.getCoordinates();
      }
    },
    methods: {
      getDetail() {
        getDk(this.$route.query.id).then(response => {
          const data = response.data;
          this.form = data;
          this.syqxzText = this.selectDictLabel(this.syqxzOptions, data.syqxz);
          if (data.dklb === '10') {
            this.dklbText = '承包地块';
          } else {
            this.dklbText = this.selectDictLabel(this.dklbOptions, data.dklb);
          }
          this.dldjText = this.selectDictLabel(this.dldjOptions, data.dldj);
          this.tdytText = this.selectDictLabel(this.tdytOptions, data.tdyt);
          this.tdlylxText = this.selectDictLabel(this.tdlylxOptions, data.tdlylx);
          if (response.data.theGeomJson) {
            this.form.theGeom = JSON.stringify(JSON.parse(response.data.theGeomJson).coordinates);
            this.$nextTick(() => {
              this.$refs.landMap.setLayer('_Draw_layer', response.data.theGeomJson);
            });
          } else {
            this.getCoordinates();
          }
        });
      },
      resetForm() {
        this.form = {
          deptId: null,
          dkbm: null,
          dkmc: null,
          syqxz: '30',
          dklb: '99',
          tdlylx: '01',
          dldj: '01',
          tdyt: '1',
          sfjbnt: '1',
          scmjm: null,
          zjrxm: null,
          dkdz: null,
          dkxz: null,
          dknz: null,
          dkbz: null,
          dkbzxx: null,
          theGeom: null
        };
        this.syqxzText = '集体土地所有权';
        this.dklbText = '其他集体土地';
        this.tdlylxText = '【1】耕地';
        this.dldjText = '一等地';
        this.tdytText = '种植业';
      },
      getCoordinates() {
        getDept(this.$route.query.deptId).then(response => {
          const lng = response.data.lng;
          const lat = response.data.lat;
          if (lng && lat) {
            this.$nextTick(() => {
              this.$refs.landMap.setCoord(lng, lat);
            });
          }
        });
      },
      onConfirmOwnershipOptions(value){
        this.form.syqxz = value.dictValue;
        this.syqxzText = value.dictLabel;
        this.showOwnership = false;
      },
      onConfirmLandCategoryOptions(value){
        /* if (this.$route.query.id && this.form.dklb === '10') {
          this.$toast({
            icon: 'fail',
            message: '当前地块为承包地块，不能修改地块类别',
            duration: '2000'
          })
          this.showLandCategory = false;
          return ;
        } */
        this.form.dklb = value.dictValue;
        this.dklbText = value.dictLabel;
        this.showLandCategory = false;
      },
      onConfirmLandTypeOptions(value) {
        this.form.tdlylx = value.dictValue;
        this.tdlylxText = value.dictLabel;
        this.showLandType = false;
      },
      onConfirmLandGradeOptions(value) {
        this.form.dldj = value.dictValue
        this.dldjText = value.dictLabel;
        this.showLandGrade = false;
      },
      onConfirmLandPurposeOptions(value){
        this.form.tdyt = value.dictValue;
        this.tdytText = value.dictLabel;
        this.showLandPurpose = false;
      },
      submitForm() {
        this.$refs.formData.validate().then(() => {
          if (this.$route.query.id) {
            updateDk(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                  onClose: () => {
                    // this.goBack();
                    this.$router.push({
                      path:'/contracted/village/massif',
                      query: {
                        deptId: this.$route.query.deptId,
                        deptName: this.$route.query.deptName,
                        dklb: this.form.dklb
                      }
                    });
                  }
                });
              }
            });
          } else {
            this.form.deptId = this.$route.query.deptId;
            addDk(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                  onClose: () => {
                    // this.goBack();
                    this.$router.push({
                      path:'/contracted/village/massif',
                      query: {
                        deptId: this.$route.query.deptId,
                        deptName: this.$route.query.deptName,
                        dklb: this.form.dklb
                      }
                    });
                  }
                });
              }
            });
          }
        }).catch(() => {
          this.$notify({ type: 'danger', message: '请填写完整的表单项' });
        });
      },
      onMapDrawFinished(data) {
        if (data) {
          this.form.theGeom = JSON.stringify(data);
        } else {
          this.form.theGeom = null;
        }
      },
      /* generateCode() {
        generateLandCode({deptId: this.$route.query.deptId}).then(response => {
          this.$set(this.form, 'dkbm', response.data);
        });
      }, */
      goBack() {
        // history.back(-1);
        this.$router.push({
          path:'/contracted/village/massif',
          query: {
            deptId: this.$route.query.deptId,
            deptName: this.$route.query.deptName,
          }
        });
      },
      openLandCategoryPopup() {
        // 修改时 && 地块类别为承包地块  不允许打开地块类别弹出层
        if (this.$route.query.id && this.form.dklb === '10') {
          this.$toast({
            icon: 'fail',
            message: '当前地块为承包地块，不能更改地块类别',
            duration: '2000'
          })
          return ;
        }
        this.showLandCategory = true;
      }
    },
  };
</script>
<style scoped lang="scss">

  .app-container{
    background: #fff url("../../../../../static/images/contracted/contracted_index_bg.png") no-repeat center;
    background-size: 100% 100%;
    height: 100vh;
    padding: 0 4vw;
    overflow: hidden;
  }

  /deep/ .van-nav-bar{
    background: transparent;
  }

  /deep/ .van-nav-bar .van-icon{
    color: #000000;
  }

  /deep/ .van-hairline--bottom::after{
    border: none;
  }

  /deep/ .van-search__content{
    background: rgba(255,255,255,.5);
  }
  /deep/ .van-search{
    padding: 0;
    flex: 1;
  }

  /deep/ .van-ellipsis{
    overflow: initial;
  }

  /deep/ .van-field--disabled .van-field__label {
    color: #646566;
  }

  /deep/ .van-field__label {
    width: 7em;
  }

  .tb_main{
    position: relative;
    p{
      position: absolute;
      display: inline-block;
      margin-left: 10PX;
    }
  }

  .tb{
    font-size: 12px;
    color: #ff8900;
    background: #daf6e7;
    border: 1px solid #d7be6e;
    padding: 2PX 8PX;
    border-radius: 50PX;
    margin-right: 5PX;
  }

  .tap_block{
    width: 100%;
    display: flex;
    justify-content: space-between;
    background: #ebfaf2;
    padding: 2PX 4PX;
    border-radius: 10PX;
    margin-top: 1vh;
    .active{
      background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
      box-shadow: 0 0 10PX #cccccc;
      color: #333333;
    }
    p{
      width: 25%;
      text-align: center;
      padding: 5PX 0;
      border-radius: 10PX;
      color: #666666;
    }
  }

  .search_main{
    display: flex;
    margin-top: 2vh;
    .search_btn{
      background: rgba(255,255,255,.5);
      width: 25%;
      border-radius: 50PX;
      margin-left: 10PX;
      padding: 2PX;
      .active{
        background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
        color: #333333;
        border-radius: 50PX;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
      }
    }
  }

  .second_tap{
    display: flex;
    align-items: center;
    margin-top: 1vh;
    p{
      background: #dbf1ea;
      border: 1px solid #cdcdcd;
      color: #5f5f5f;
      padding: 5PX 15PX;
      margin-right: 3vw;
      border-radius: 50PX;
    }
    .active{
      background: #99eecb;
      border-color: #48e5a2;
      color: #333333;
    }
  }

  .list_main{
    margin-top: 2vh;
    overflow-y: scroll;
    text-align: center;
    background: #ffffff;
    border-top-left-radius: 10PX;
    border-top-right-radius: 10PX;
    height: 88vh;
    .btn{
      background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
      box-shadow: 0 0 10PX #cccccc;
      padding: 10PX 0PX;
      border-radius: 50PX;
      display: inline-block;
      width: 40%;
      margin-top: 2vh;
    }
  }

  .mapBox{
    width: 94%;
    height: 50vw;
    background-image: linear-gradient(to right,#c6fe8b,#48e5a2);
    border-radius: 10PX;
    margin: 2vh auto;
  }

</style>
