<template>
  <div class="execution">
    <Card style="margin-bottom: 5px;">
      <p>
        <el-button
          type="primary"
          @click="backPage"
          style="margin-left: 20px;margin-right: 50px;"
          >返回</el-button
        >
      </p>
    </Card>
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        v-model="form"
        :data="tableData"
        :before-open="beforeOpen"
        :permission="permissionList"
        :table-loading="tableLoading"
        :option="tableOption"
        @on-load="getList"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-update="handleUpdate"
        @row-save="handleSave"
        @row-del="rowDel"
      >
        <template slot="provinceTxtForm" slot-scope="scope">
          <span class="cityColor" @click="toAddress">{{ city }}</span>
        </template>
        <template slot="addressForm" slot-scope="scope">
          <div class="map">
            <el-input
              v-model="addressKeyword"
              placeholder="请输入地址来直接查找相关位置"
              clearable
              style="margin-bottom:20px"
              @keyup.enter.native="getAddressKeyword"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getAddressKeyword"
              ></el-button>
            </el-input>
            <div id="container" style="width:100%; height:300px"></div>
          </div>
        </template>
      </avue-crud>
    </basic-container>

    <el-dialog
      :visible.sync="showH5"
      class="auditH"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="true"
      :modal="false"
      @close="backPage"
      style="left:58%;height: 800px;width: 55%;"
      title="任务调研详情"
    >
      <el-card class="box-card">
        <div class="text">
          提交人：{{ mo.tjr }} &nbsp;&nbsp;&nbsp;&nbsp;联系电话：{{ mo.lxdh
          }}<br />
          提交时间：{{ mo.tjsj }}
        </div>
      </el-card>
      <div style="width: 100%">
        <iframe
          v-show="showH5"
          id="show-iframe"
          frameborder="0"
          name="showHere"
          scrolling="auto"
          :src="taskSrc"
          style="height: 560px;width: 98%"
        ></iframe>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="addInp"
      :close-on-click-modal="true"
      title="请选择区域"
    >
      <v-distpicker type="mobile" @selected="selected" v-show="addInp">
      </v-distpicker>
      <div slot="footer" class="dialog-footer">
        <el-button type="default" size="small" @click="cancal()"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  pageAudit,
  getObj,
  addObj,
  putObj,
  delObj
} from "@/api/wmdadistribution";
import { tableOptionAudit } from "@/const/crud/wmdadistribution";
import { mapGetters } from "vuex";
import VDistpicker from "v-distpicker";
import maps from "qqmap";
import Config from "@/settings";

export default {
  name: "wmdadistribution",
  data() {
    return {
      showH5: false,
      mo: {
        tjr: "",
        tjsj: "",
        lxdh: ""
      },
      taskSrc: "",
      map: null,
      getAddress: null,
      getAddCode: null,
      addressKeyword: "",
      shopInfo: {
        lng: null,
        lat: null
      },
      city: "请选择区域",
      addInp: false,
      mask: false,
      form: {},
      searchForm: {},
      tableData: [],
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoading: false,
      tableOption: tableOptionAudit
    };
  },
  components: {
    VDistpicker
  },
  mounted() {
    debugger;
    this.mo.lxdh = this.$route.query.phone;
    this.mo.tjr = this.$route.query.taskUser;
    this.mo.tjsj = this.$route.query.date;
    this.taskSrc =
      Config.outsideUrl +
      "/h5/#/pages/task/task-detail/index?id=" +
      this.$route.query.taskId +
      "&r=" +
      Math.random();
  },
  beforeUpdate: function() {
    if (undefined != this.form.province && "" != this.form.province) {
      this.city =
        this.form.province + " " + this.form.city + " " + this.form.area;
    }
    if (undefined != this.form.address && "" != this.form.address) {
      this.addressKeyword = this.form.address;
    }
  },

  beforeCreate: function() {
    this.city = "请选择区域";
    this.addressKeyword = "";
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(
          this.permissions.admin_wmdadistribution_add,
          false
        ),
        delBtn: this.vaildData(
          this.permissions.admin_wmdadistribution_del,
          false
        ),
        editBtn: this.vaildData(
          this.permissions.admin_wmdadistribution_edit,
          false
        )
      };
    }
  },
  methods: {
    init() {
      var that = this;
      maps.init("C4ABZ-HWE3X-5DW4J-ZO4GH-IQBWK-TXF2X", () => {
        var myLatlng = new qq.maps.LatLng(
          22.547931568083015,
          114.1306221485138
        );
        var myOptions = {
          zoom: 16,
          center: myLatlng,
          mapTypeId: qq.maps.MapTypeId.ROADMAP
        };
        that.map = new qq.maps.Map(
          document.getElementById("container"),
          myOptions
        );
        //获取点击后的地址
        qq.maps.event.addListener(that.map, "click", function(event) {
          // 获取点击后的地图坐标
          that.shopInfo.lng = event.latLng.getLng();
          that.shopInfo.lat = event.latLng.getLat();
          that.getAddressCode();
        });
        //调用地址显示地图位置并设置地址
        that.getAddress = new qq.maps.Geocoder({
          complete: function(result) {
            that.map.setCenter(result.detail.location);
            console.log(result.detail.location);
            that.shopInfo.lng = result.detail.location.lng;
            that.shopInfo.lat = result.detail.location.lat;
            var marker = new qq.maps.Marker({
              map: that.map,
              position: result.detail.location
            });
          }
        });
        //通过坐标来显示地图地址
        that.getAddCode = new qq.maps.Geocoder({
          complete: function(result) {
            that.addressKeyword = result.detail.address;
          }
        });
        if (undefined != this.city && "" != this.city) {
          this.getAddress.getLocation(this.city); //调用自带的接口
        }

        if (undefined != this.addressKeyword && "" != this.addressKeyword) {
          this.getAddress.getLocation(this.addressKeyword); //调用自带的接口
        }
      });
    },
    getAddressKeyword() {
      //通过getLocation();方法获取位置信息值
      if (undefined == this.getAddress) {
        this.init();
      } else {
        this.getAddress.getLocation(this.addressKeyword); //调用自带的接口
      }
    },
    // 通过坐标获得地址
    getAddressCode() {
      var lat = parseFloat(this.shopInfo.lat);
      var lng = parseFloat(this.shopInfo.lng);
      var latLng = new qq.maps.LatLng(lat, lng);
      //调用获取位置方法
      this.getAddCode.getAddress(latLng);
      this.form.longitude = lng;
      this.form.latitude = lat;
    },
    toAddress() {
      console.log(111);
      this.mask = true;
      this.addInp = true;
    },
    // 省市区三级联动
    selected(data) {
      this.mask = false;
      this.addInp = false;
      this.city =
        data.province.value + " " + data.city.value + " " + data.area.value;
      this.form.province = data.province.value;
      this.form.city = data.city.value;
      this.form.area = data.area.value;
      this.addressKeyword =
        data.province.value + data.city.value + data.area.value;
      this.init();
      //this.city =  data.area.value
    },
    getList(page, params) {
      if (undefined != this.$route.query.taskId) {
        this.searchForm.updateUser = this.$route.query.taskId;
      }
      this.tableLoading = true;
      pageAudit(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
          if (this.tableData.length > 0) {
            this.$refs.crud.rowEdit(this.tableData[0], 0);
            this.showH5 = true;
          } else {
            this.$refs.crud.rowAdd();
            this.showH5 = true;
          }
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObj(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getList(this.page);
        });
    },
    handleUpdate: function(row, index, done, loading) {
      row.address = this.addressKeyword;
      if (undefined == this.addressKeyword || "" == this.addressKeyword) {
        this.$message.error("地址不能为空");
        return false;
      }

      if (undefined == row.city || "" == row.city) {
        this.$message.error("区域不能为空");
        return false;
      }
      row.updateUser = this.$route.query.taskId;
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.$router.push({ path: "/admin/wmtask/auditCheck" });

          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      row.address = this.addressKeyword;
      if (undefined == this.addressKeyword || "" == this.addressKeyword) {
        this.$message.error("地址不能为空");
        return false;
      }

      if (undefined == row.city || "" == row.city) {
        this.$message.error("区域不能为空");
        return false;
      }
      row.updateUser = this.$route.query.taskId;
      this.$router.push({ path: "/admin/wmtask/auditCheck" });
      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    refreshChange() {
      this.getList(this.page);
    },
    taskTj(row, index) {
      this.$refs.crud.rowEdit(row, index);
      this.showH5 = true;
    },
    backPage() {
      this.$router.push({ path: "/admin/wmtask/auditCheck" });
    },
    beforeOpen(show, type) {
      if (type == "add") {
        this.addressKeyword = "";
        this.city = "请选择区域";
        this.init();
        window.boxType = type;
        show();
      } else {
        let form = this.form;
        this.addressKeyword = this.form.address;
        if (undefined != this.form.province && "" != this.form.province) {
          this.city =
            this.form.province + " " + this.form.city + " " + this.form.area;
        }

        this.init();
        window.boxType = type;
        show();
      }
    }
  }
};
</script>

<style lang="less" scoped>
.distpicker-address-wrapper {
  color: #000000 !important;
}

.distpicker-address-wrapper .address-header ul li.active {
  color: #000000 !important;
}
/*.el-dialog{*/
/*  width:60%!important;*/
/*  margin-left: 10px !important;*/
/*}*/
.auditH {
  z-index: 5000 !important;
}
</style>
