<template>
  <div class="execution">
    <Card style="margin-bottom: 5px;" v-show="roleSubmitType">
      <p>
        <el-button
          type="primary"
          @click="submitCheck"
          style="margin-left: 20px;margin-right: 50px;"
          v-show="isSHow"
          >提交</el-button
        >
        <!--          <el-button type="primary" @click="submitckeckAll" style="margin-left: 20px;margin-right: 50px;">全部提交</el-button>-->
        <el-button
          type="primary"
          @click="backPage"
          style="margin-left: 20px;margin-right: 50px;"
          >返回</el-button
        >
      </p>
      <!--        <p style="margin-top: 30px;margin-left: 20px;">-->
      <!--          全部任务{{cardInfo.totalNum}}条，共计{{cardInfo.totalScore}}分-->
      <!--        </p>-->
      <p style="margin-top: 30px;margin-left: 20px;" v-show="isSHow">
        已选{{ cardInfo.checkNum }}条，共计{{ cardInfo.checkScore }}分
      </p>
      <p
        style="margin-top: 10px;margin-left: 20px;color: #ed3f14"
        v-show="isSHow"
      >
        （温馨提示：由于积分规则原因，系统自动计算出最接近分值，超出分值则失效处理）
      </p>
    </Card>
    <basic-container>
      <avue-crud
        ref="crud"
        v-model="form"
        :data="tableData"
        :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"
        @selection-change="selectionchange"
      >
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="showTaskInfo(scope.row, scope.index)"
            >查看详情
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  fetchSubList,
  getObj,
  addObj,
  putObj,
  delObj,
  getTotalScore,
  submitTask
} from "@/api/wmtask";
import { tableOption, tableOptionJSX } from "@/const/crud/wmtask";
import { mapGetters } from "vuex";
import VDistpicker from "v-distpicker";
import { getObjDept } from "@/api/admin/dept";
import maps from "qqmap";
import Config from "@/settings";
export default {
  name: "wmtask",
  data() {
    return {
      isSHow: true,
      roleSubmitType: true,
      entLevel: 0,
      checkRow: [],
      cardInfo: {
        checkNum: 0,
        checkScore: 0,
        totalNum: 0,
        totalScore: 0
      },
      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: tableOptionJSX
    };
  },
  components: {
    VDistpicker
  },
  mounted() {
    this.getObjDept1();
    this.getTotalScore1();
    if (undefined != this.$route.query.type) {
      this.isSHow = false;
    }
  },
  computed: {
    ...mapGetters(["permissions", "userInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.admin_wmtask_add, false),
        delBtn: this.vaildData(this.permissions.admin_wmtask_del, false),
        editBtn: this.vaildData(this.permissions.admin_wmtask_edit, false)
      };
    }
  },
  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 = "";
  },
  watch: {
    entLevel: function(val, oldVal) {
      if (val == "2") {
        this.isSHow = false;
      }
    }
  },
  methods: {
    getTotalScore1() {
      var obj = {};
      this.cardInfo.checkNum = 0;
      this.cardInfo.totalNum = 0;
      this.cardInfo.totalScore = 0;
      this.cardInfo.checkNum = 0;
      this.cardInfo.checkScore = 0;
      getTotalScore(obj)
        .then(data => {
          var data = data.data.data;
          this.cardInfo.totalNum = data.totalCount;
          this.cardInfo.totalScore = data.countScore;
        })
        .catch(() => {});
    },
    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.init();
      //this.city =  data.area.value
    },
    getList(page, params) {
      if (undefined != this.$route.query.taskStatus) {
        this.searchForm.taskStatus = this.$route.query.taskStatus;
      }

      if (undefined != this.$route.query.packageId) {
        this.searchForm.id = this.$route.query.packageId;
      }

      this.cardInfo.checkNum = 0;
      this.cardInfo.totalNum = 0;
      this.cardInfo.totalScore = 0;
      this.cardInfo.checkNum = 0;
      this.cardInfo.checkScore = 0;

      this.tableLoading = true;
      fetchSubList(
        Object.assign(
          {
            current: 1,
            size: 1000
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          for (var i = 0; i < this.tableData.length; i++) {
            this.cardInfo.checkScore += this.tableData[i].score;
            this.cardInfo.checkNum += 1;
          }
          this.tableLoading = false;
        })
        .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;
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      row.address = this.addressKeyword;
      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);
    },
    backPage() {
      this.$router.push({ path: "/admin/wmtask/indexJxs" });
    },
    submitCheck() {
      if (this.tableData.length == 0) {
        this.$message.error("请选择需要提交的任务");
        return false;
      } else {
        var ids = "";
        for (var i = 0; i < this.tableData.length; i++) {
          if (i > 0) {
            ids = ids + "," + this.tableData[i].id;
          } else {
            ids = this.tableData[i].id;
          }
        }
        var obj = {
          ids: ids,
          type: "1",
          packageId: this.$route.query.packageId
        };

        submitTask(obj)
          .then(data => {
            this.$message.success("提交成功");
            this.$router.$avueRouter.closeTag();
            this.$router.push({ path: "/admin/wmtask/indexJxs" });
          })
          .catch(() => {});
      }
    },
    submitckeckAll() {},
    backPage() {
      this.$router.$avueRouter.closeTag();
      this.$router.push({ path: "/admin/wmtask/indexJxs" });
    },
    selectionchange(selection, row) {
      this.cardInfo.checkNum = selection.length;
      this.cardInfo.checkScore = 0;
      this.checkRow = selection;
      if (undefined != selection) {
        for (var i = 0; i < selection.length; i++) {
          this.cardInfo.checkScore += selection[i].score;
        }
      }
    },
    getObjDept1() {
      let deptId = this.userInfo.deptId;
      getObjDept(deptId)
        .then(data => {
          var deptInfo = data.data.data;
          if (deptInfo.level == 3) {
            this.entLevel = 1;
          }

          if (deptInfo.level == 4) {
            this.entLevel = 2;
          }
        })
        .catch(() => {});
    },
    showTaskInfo(row, index) {
      window.open(
        Config.outsideUrl + "/h5/#/pages/task/task-detail/index?id=" + row.id,
        "newwindow",
        "height=500, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no"
      );
    }
  }
};
</script>
