<template>
  <div class="execution">
    <Tabs value="name1">
      <TabPane label="服务承接" name="name1">
        <basic-container>
          <!--            <Card style="margin-bottom: 20px;">-->
          <!--              <p style="height: 30px;">-->
          <!--                <span style="margin: 5px;">已提交{{rateForm.socreYtj}}/应完成{{rateForm.socreYjwc}} &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-->
          <!--                  <span style="margin-left: 200px;color: darkorange">当前已有积分总值：{{rateForm.dqyyjfzz}}</span></span>-->
          <!--              </p>-->
          <!--              <p>-->
          <!--                <Progress :percent="rateForm.socreShtgRate" :stroke-width="30" status="active" text-inside />-->
          <!--              </p>-->
          <!--            </Card>-->

          <avue-crud
            ref="crud"
            :page="pageTask"
            :data="tableDataTask"
            :table-loading="tableLoadingTask"
            :option="tableOptionTask"
            @on-load="getListTask"
            @search-change="searchChangeTask"
            @refresh-change="refreshChangeTask"
            @size-change="sizeChangeTask"
            @current-change="currentChangeTask"
            @row-update="handleUpdateTask"
            @row-save="handleSaveTask"
            @row-del="rowDelTask"
          >
            <template slot="menu" slot-scope="scope">
              <el-button
                v-if="roleSubmitType"
                :disabled="scope.row.packageFinishStatus == 1"
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="taskTj(scope.row, scope.index)"
                >生成报告
              </el-button>

              <el-button
                type="text"
                size="small"
                icon="el-icon-view"
                :disabled="
                  scope.row.ysh == '' ||
                    scope.row.ysh == 0 ||
                    scope.row.ysh == undefined
                "
                @click="taskTjCk(scope.row, scope.index)"
                >查看
              </el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-check"
                :disabled="
                  scope.row.packageFinishStatus != 1 ||
                    scope.row.ysh == '' ||
                    scope.row.ysh == 0 ||
                    scope.row.ysh == undefined
                "
                @click="showExportDia(scope.row, scope.index)"
                >导出
              </el-button>
            </template>
          </avue-crud>
        </basic-container>
      </TabPane>
      <TabPane label="全部任务" name="name2">
        <basic-container>
          <avue-crud
            ref="crud"
            :page="page"
            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"
          >
            <template slot="menu" slot-scope="scope">
              <el-button
                v-if="roleSubmitType"
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="showTaskInfo(scope.row, scope.index)"
                >查看详情
              </el-button>
            </template>
          </avue-crud>
        </basic-container>
      </TabPane>
    </Tabs>

    <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>

    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <span>
        <el-button
          @click="taskExport"
          :loading="taskExportLoading"
          style="margin-left: 50px;"
          >导出汇总报告</el-button
        >

        <el-button
          @click="taskExportInfo"
          :loading="taskExportInfoLoading"
          style="margin-left: 50px;"
          >导出报告详情</el-button
        >
      </span>
      <span slot="footer" class="dialog-footer">
        注意： 1.报告汇总为封面+任务数据汇总+任务列表明细。<br />

        2.报告详情为每条任务的任务详情+图片。
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  taskExportYq,
  taskExportNbqybg,
  taskExportNbqybgInfo,
  infoExportNbqybgInfo,
  pageExtList
} from "@/api/wmtask";
import { tableOption, tableOptionT_JXS } from "@/const/crud/wmtask";
import {
  fetchListTask,
  getObjTask,
  addObjTask,
  putObjTask,
  delObjTask,
  getTotalData,
  getWmScorePageTask,
  getWmScorePackagePageTask,
  getWmScorePackageTask
} from "@/api/wmscorepackage";
import { tableOptionTaskJsx } from "@/const/crud/wmscorepackage";
import { getObjDept } from "@/api/admin/dept";
import { mapGetters } from "vuex";
import VDistpicker from "v-distpicker";
import maps from "qqmap";
import Config from "@/settings";

export default {
  name: "wmtask",
  data() {
    return {
      entLevel: 0,
      rateForm: {
        socreShtgRate: 0,
        socreYtj: 0,
        socreYjwc: 0,
        dqyyjfzz: 0
      },
      roleSubmitType: true,
      roleAudioType: true,
      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: tableOptionT_JXS,

      taskExportLoading: false,
      taskExportInfoLoading: false,
      infoExportLoading: false,
      centerDialogVisible: false,
      checkRow: null,

      formTask: {},
      searchFormTask: {},
      tableDataTask: [],
      pageTask: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      tableLoadingTask: false,
      tableOptionTask: tableOptionTaskJsx
    };
  },
  components: {
    VDistpicker
  },
  watch: {
    entLevel: function(val, oldVal) {
      if (val == "2") {
        this.roleSubmitType = false;
      }
    }
  },
  mounted() {
    this.getWmScorePackageTask();
    this.getObjDept1();
  },
  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)
      };
    },
    permissionListList() {
      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 = "";
  },
  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.init();
      //this.city =  data.area.value
    },
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        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;
        })
        .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);
    },

    sizeChangeTask(pageSize) {
      this.pageTask.pageSize = pageSize;
    },
    currentChangeTask(current) {
      this.pageTask.currentPage = current;
    },
    searchChangeTask(form, done) {
      this.searchFormTask = form;
      this.pageTask.currentPage = 1;
      this.getListTask(this.pageTask, form);
      done();
    },
    refreshChangeTask() {
      this.getListTask(this.pageTask);
    },
    getListTask(page, params) {
      this.tableLoadingTask = true;
      // this.searchFormTask.agentTypeId=1;
      getWmScorePageTask(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize
          },
          params,
          this.searchFormTask
        )
      )
        .then(response => {
          this.tableDataTask = response.data.data.records;
          this.pageTask.total = response.data.data.total;
          this.tableLoadingTask = false;
        })
        .catch(() => {
          this.tableLoadingTask = false;
        });
    },
    rowDelTask: function(row, index) {
      this.$confirm("是否确认删除ID为" + row.id, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return delObjTask(row.id);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.getListTask(this.pageTask);
        });
    },
    handleUpdateTask: function(row, index, done, loading) {
      putObjTask(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.getListTask(this.pageTask);
        })
        .catch(() => {
          loading();
        });
    },
    handleSaveTask: function(row, done, loading) {
      addObjTask(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.getListTask(this.pageTask);
        })
        .catch(() => {
          loading();
        });
    },
    taskTj(row, index) {
      this.$router.push({
        path: "/admin/wmtask/indexJxsTj?taskStatus=1&packageId=" + row.id
      });
    },
    taskTjCk(row, index) {
      this.$router.push({
        path: "/admin/wmtask/indexJxsTj?packageId=" + row.id + "&type=show"
      });
    },
    getWmScorePackageTask() {
      // var obj={
      //   agentTypeId:1
      // }
      getWmScorePackageTask(obj)
        .then(response => {
          let answer = response.data.data;
          this.rateForm.dqyyjfzz = answer.dqf;
          this.rateForm.socreYtj = answer.ytj;
          this.rateForm.socreYjwc = answer.ywc;
          if (undefined != answer.ywc && 0 != answer.ywc) {
            this.rateForm.socreShtgRate = parseInt(
              (answer.ytj * 100) / answer.ywc
            );
          }
        })
        .catch(() => {});
    },
    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=750, width=400, top=200, left=300, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no"
      );
    },
    showExportDia(row, index) {
      this.checkRow = row;
      this.centerDialogVisible = true;
    },
    taskExport() {
      this.taskExportLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id
      };
      taskExportNbqybg(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出学术推广服务报告成功");
          this.taskExportLoading = false;
        })
        .catch(() => {
          this.taskExportLoading = false;
        });
    },
    taskExportInfo() {
      this.taskExportInfoLoading = true;
      let row = this.checkRow;
      var obj = {
        scorePackageDrugId: row.id
      };
      taskExportNbqybgInfo(obj)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出学术推广服务任务明细成功");
          this.taskExportInfoLoading = false;
        })
        .catch(() => {
          this.taskExportInfoLoading = false;
        });
    },
    exportTaskInfo() {
      this.infoExportLoading = true;
      infoExportNbqybgInfo(this.searchForm)
        .then(response => {
          if (undefined == response.data || undefined == response.data.data) {
            this.$message.error("导出失败");
            return false;
          }
          let obj = response.data.data;
          let a = document.createElement("a");
          a.href = obj.url; // 这里的请求方式为get，如果需要认证，接口上需要带上token
          a.click();
          this.$message.success("导出学术推广服务报告成功");
          this.infoExportLoading = false;
        })
        .catch(() => {
          this.infoExportLoading = false;
        });
    }
  }
};
</script>
