<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="list_main">
      <van-form ref="formData">
        <van-field v-model="form.dkbm" label="地块代码：" placeholder="请选择地块代码" required :rules="[{ required: true }]" :border="false"
                   input-align="right" right-icon="arrow-down" readonly clickable @click="openLandCodePopup" :disabled="isDisabled" maxlength="19" />
        <van-popup v-model="showLandCode" position="bottom">
          <van-search v-model="searchKeyword"  placeholder="请输入地块名称搜索" />
          <van-picker
            ref="landCodePicker"
            show-toolbar
            :columns="filteredLandList"
            @confirm="onConfirmLandCodeOptions"
            @cancel="showLandCode = false"
          >
            <template #option="option">
              <div style="display: flex; flex-direction: column; align-items: center;">
                <div>{{option.dkmc}}-{{option.dkbm}}</div>
              </div>
            </template>
          </van-picker>
        </van-popup>
        <van-field v-model="form.dkmc" label="地块名称：" placeholder="请输入地块名称" required :rules="[{ required: true }]" :border="false" input-align="right" maxlength="50" />
        <van-field
          v-model="tdlylxText"
          label="土地利用类型："
          placeholder="请选择土地利用类型"
          required
          :rules="[{ required: true }]"
          :border="false"
          input-align="right"
          right-icon="arrow-down"
          readonly
          clickable
          @click="showLandUseType = true"
        />
        <van-popup v-model="showLandUseType" position="bottom">
          <van-picker
            show-toolbar
            :columns="tdlylxOptions"
            value-key="dictLabel"
            @confirm="onConfirmLandUseTypeOptions"
            @cancel="showLandUseType = 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="onConfirmTDYTOptions"
            @cancel="showLandPurpose = false"
          />
        </van-popup>
        <van-field v-model="form.sfjbnt" label="基本农田：" placeholder="请选择基本农田" required :rules="[{ required: true }]" :border="false" input-align="right">
          <template #input>
            <van-radio-group v-model="form.sfjbnt" direction="horizontal">
              <van-radio v-for="item in sfjbntOptions" :key="item.dictValue" :name="item.dictValue">{{ item.dictLabel }}</van-radio>
            </van-radio-group>
          </template>
        </van-field>
        <van-field v-model="form.htmjm" 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="contractedLandMap" :minMapZoom="15" :maxMapZoom="18" :allowDraw="true" @drawFinished="onMapDrawFinished" />
        </div>
      </van-form>
      <p class="btn" @click="submitForm" v-if="taskStatus === '2' && $route.params.surveyStatus !== '3'">保存</p>
    </div>


  </div>
</template>
<script>
  import Cookies from "js-cookie";
  import { getCbdkxx, addCbdkxx, updateCbdkxx } from "@/api/contracted/cbdkxx";
  import { listDk } from "@/api/contracted/dk";
  import { getDept } from "@/api/contracted";
  import CommonMap from "@/components/house/CommonMap";

  export default {
    name: "contractedVillageContractor",
    components: {
      CommonMap
    },
    data() {
      return {
        titleName: '',                    // 标题信息
        isDisabled: false,                // 是否禁用
        form: {},                         // 承包地信息表单
        showLandCode: false,              // 控制地块代码弹出层的显示和隐藏
        tdlylxOptions: [],                // 土地利用类型字典
        tdlylxText: null,                 // 土地利用类型标签名
        showLandUseType: false,           // 控制土地利用类型字典弹出层的显示和隐藏
        dldjOptions: [],                  // 地力等级字典
        dldjText: null,                   // 地力等级标签名
        showLandGrade: false,             // 控制地力等级字典弹出层的显示和隐藏
        tdytOptions: [],                  // 土地用途字典
        tdytText: null,                   // 土地用途标签名
        showLandPurpose: false,           // 控制土地用途字典弹出层的显示和隐藏
        sfjbntOptions: [],                // 是否基本农田字典
        landList: [],                     // 地块信息列表
        taskStatus: null,                 // 调查任务的完成状态：1表示已完成，2表示未完成
        searchKeyword: '',                // 弹出框查询关键字
      };
    },
    created() {
      this.taskStatus = Cookies.get('taskStatus');
      this.getDicts("land_use").then(response => {
        this.tdlylxOptions = response.data;
      });
      this.getDicts("land_grade").then(response => {
        this.dldjOptions = response.data;
      });
      this.getDicts("use_code").then(response => {
        this.tdytOptions = response.data;
      });
      this.getDicts("is_common").then(response => {
        this.sfjbntOptions = response.data;
      });
    },
    mounted() {
      if (this.$route.params.id) {
        this.titleName = '修改承包地信息';
        this.isDisabled = true;
        setTimeout(() => {
          this.getDetail();
        }, 500)
      } else {
        this.titleName = '新增承包地信息';
        this.resetForm();
        this.getCoordinates();
        this.getLandList();
      }
    },
    computed: {
      filteredLandList() {
        return this.landList.filter(item => {
          return item.dkmc.indexOf(this.searchKeyword) !== -1;
        })
      }
    },
    methods: {
      getCoordinates() {
        getDept(this.$route.params.deptId).then(response => {
          const lng = response.data.lng;
          const lat = response.data.lat;
          if (lng && lat) {
            this.$nextTick(() => {
              this.$refs.contractedLandMap.setCoord(lng, lat);
            });
          }
        });
      },
      getLandList() {
        // 查询出非承包地块(dklb != '10')且未流转(dkzt = '1')的地块信息
        listDk({deptId: this.$route.params.deptId, jtdklb: '10', dkzt: '1'}).then(response => {
          this.landList = response.rows;
        });
      },
      getDetail(){
        getCbdkxx(this.$route.params.id).then(response => {
          this.form = response.data;
          this.tdlylxText = this.selectDictLabel(this.tdlylxOptions, response.data.tdlylx);
          this.dldjText = this.selectDictLabel(this.dldjOptions, response.data.dldj);
          this.tdytText = this.selectDictLabel(this.tdytOptions, response.data.tdyt);
          if (response.data.theGeomJson) {
            this.form.theGeom = JSON.stringify(JSON.parse(response.data.theGeomJson).coordinates);
            this.$nextTick(() => {
              this.$refs.contractedLandMap.setLayer('_Draw_layer', response.data.theGeomJson);
            });
          } else {
            this.getCoordinates();
          }
        });
      },
      resetForm() {
        this.form = {
          deptId: null,
          cbfbm: null,
          dkbm: null,
          dkmc: null,
          tdlylx: null,
          dldj: null,
          tdyt: null,
          sfjbnt: null,
          htmjm: null,
          zjrxm: null,
          dkdz: null,
          dkxz: null,
          dknz: null,
          dkbz: null,
          dkbzxx: null,
          theGeom: null
        };
      },
      openLandCodePopup() {
        /* if (this.form.dkbm) {
          const index = this.landList.findIndex(item => item.dkbm === this.form.dkbm);
          this.$refs.landCodePicker.setColumnIndex(0, index);
        } */
        if (!this.isDisabled) {
          this.showLandCode = true;
          this.searchKeyword = '';
        }
      },
      onConfirmLandCodeOptions(value) {
        this.form.dkbm = value.dkbm;
        this.form.dkmc = value.dkmc;
        this.form.tdlylx = value.tdlylx;
        this.tdlylxText = this.selectDictLabel(this.tdlylxOptions, value.tdlylx);
        this.form.dldj = value.dldj;
        this.dldjText = this.selectDictLabel(this.dldjOptions, value.dldj);
        this.form.tdyt = value.tdyt
        this.tdytText = this.selectDictLabel(this.tdytOptions, value.tdyt);
        this.form.sfjbnt = value.sfjbnt;
        this.form.htmjm = value.scmjm;
        this.form.zjrxm = value.zjrxm;
        this.form.dkdz = value.dkdz;
        this.form.dkxz = value.dkxz
        this.form.dknz = value.dknz;
        this.form.dkbz = value.dkbz;
        this.form.dkbzxx = value.dkbzxx;
        if (value.theGeomJson) {
          this.form.theGeom = JSON.stringify(JSON.parse(value.theGeomJson).coordinates);
          this.$refs.contractedLandMap.setLayer('_Draw_layer', value.theGeomJson);
        } else {
          this.form.theGeom = null;
        }
        this.showLandCode = false;
      },
      onConfirmLandUseTypeOptions(value) {
        this.form.tdlylx = value.dictValue;
        this.tdlylxText = value.dictLabel;
        this.showLandUseType = false;
      },
      onConfirmLandGradeOptions(value) {
        this.form.dldj = value.dictValue;
        this.dldjText = value.dictLabel;
        this.showLandGrade = false;
      },
      onConfirmTDYTOptions(value){
        this.form.tdyt = value.dictValue;
        this.tdytText = value.dictLabel;
        this.showLandPurpose = false;
      },
      goBack() {
        this.$router.push({
          name: 'contractedVillageContractorLand',
          params: {
            deptId: this.$route.params.deptId,
            cbfbm: this.$route.params.cbfbm,
            cbfmc: this.$route.params.cbfmc,
            surveyStatus: this.$route.params.surveyStatus
          }
        });
      },
      submitForm() {
        this.$refs.formData.validate().then(() => {
          if (this.$route.params.id) {
            updateCbdkxx(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                  onClose: () => {
                    this.goBack();
                  }
                });
              }
            });
          } else {
            this.form.deptId = this.$route.params.deptId;
            this.form.cbfbm = this.$route.params.cbfbm;
            addCbdkxx(this.form).then(response => {
              if (response.code == 200) {
                this.$toast({
                  icon: 'success',
                  message: '保存成功',
                  duration:"1000",
                  onClose: () => {
                    this.goBack();
                  }
                });
              }
            });
          }
        }).catch(() => {
          this.$notify({ type: 'danger', message: '请填写完整的表单项' });
        });
      },
      onMapDrawFinished(data) {
        if (data) {
          this.form.theGeom = JSON.stringify(data);
        } else {
          this.form.theGeom = null;
        }

      },
    },
  };
</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-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>
