<template>
  <div class="inspedtionDetail">
    <template v-if="baseInfo.online !== true">
      <div class="label">巡检信息</div>
      <div class="head">
        <p>
          <i class="iconfont icon-zuixinbaoxiu newPapir"></i>
          巡检单号
          <span class="num">{{ baseInfo.sign }}</span>
          <span class="btn zhixingzhong">{{ baseInfo.stateName }}</span>
        </p>
      </div>
      <div class="info">
        <p>
          <span class="fl">巡检范围</span>
          <span class="fr">{{ baseInfo.inspectionType.type }}</span>
        </p>
        <p>
          <span class="fl">计划主题</span>
          <span class="fr">{{ baseInfo.inspection.title }}</span>
        </p>
        <p>
          <span class="fl">计划内容</span>
          <span class="fr showwrap">{{ baseInfo.inspection.content }}</span>
        </p>
        <p>
          <span class="fl">巡检状态</span>
          <span class="fr">{{ baseInfo.stateName }}</span>
        </p>
        <p>
          <span class="fl">巡检策略</span>
          <span class="fr">{{ baseInfo.inspection.planStrategy.name }}</span>
        </p>
        <p>
          <span class="fl">执行时长</span>
          <span class="fr">{{ baseInfo.inspection.executionTime }}分钟</span>
        </p>
        <p>
          <span class="fl">开始时间</span>
          <span class="fr">{{
            baseInfo.inspection.planStartTime.slice(
              0,
              baseInfo.inspection.planStartTime.length - 2
            )
          }}</span>
        </p>
        <p>
          <span class="fl">逾期时间</span>
          <span class="fr">{{ baseInfo.overdueTime }}</span>
        </p>
      </div>
      <div class="label">巡检结果</div>
      <div class="form">
        <p v-for="(item, index) in forms" :key="index">
          <span>{{ item.name }}：</span>
          <cube-switch
            v-model="param[item.key]"
            class="abnormal"
            :data-label="item.name"
          ></cube-switch>
        </p>
      </div>
    </template>
    <div class="label formLabel">
      {{ xj_beizhu.name }}
    </div>
    <div class="textarea_div">
      <cube-textarea
        class="textarea"
        v-model="param[xj_beizhu.key]"
        placeholder="请输入整改意见"
      ></cube-textarea>
    </div>
    <div></div>
    <div class="label formLabel">
      图片上传
      <span>(最多可上传3张JPG或PNG,每张不能超过10M)</span>
    </div>
    <div class="uplod">
      <cube-upload
        ref="upload"
        :max="3"
        :action="action"
        :simultaneous-uploads="3"
        @files-added="filesAdded"
        @file-submitted="fileSubmitted"
      />
    </div>
    <div class="btns">
      <div class="btn" @click="createIncident()">生成事件</div>
      <div class="btn submit" @click="getLocation()">提交</div>
      <div class="btn cancel" @click="cancle()">取消</div>
    </div>
  </div>
</template>
<script>
let sdk = new jssdk(3, "https://wx2.zuel.edu.cn"); // 域名更换为对应环境域名， 204 更换为对应环境wid
sdk.config(0); //1表示调试模式，生产环境传0
import { GL } from "./../http/http";
export default {
  data() {
    return {
      toast: null,
      action: {
        target:
          this.$host + "/service/common/common/uploadAttachment/inspection/",
        data: {}
      },
      loginUser: JSON.parse(localStorage.getItem("loginUser")),
      valConfig: JSON.parse(localStorage.getItem("valConfig")) - 0, //报修主体
      baseInfo: {}, //巡检基础信息
      items: [], //巡检项目
      xj_arr: [], //巡检项目数组key和name
      xj_beizhu: {}, //巡检-整改意见（备注）
      forms: [], //巡检结果
      abnormal: "", //异常项
      param: {
        sdCheckEnable1: true,
        sdCheckEnable2: true,
        sdCheckEnable3: true,
        sdCheckEnable4: true,
        sdCheckEnable5: true,
        sdCheckEnable6: true,
        sdCheckEnable7: false,
        sdCheckEnable8: true,
        sdCheckEnable9: true,
        sdCheckEnable10: true,
        sdCheckEnable11: false,
        sdCheckEnable12: false,
        descriptionTextarea: "",
        inspectionProcessActual: {}
      },
      model: {}
    };
  },
  methods: {
    //获取位置，经纬度
    getLocation() {
      // this.submit("香港");
      // return;
      // 判断是否处于微信浏览器环境
      if (!/MicroMessenger/i.test(window.navigator.userAgent)) {
        this.$createToast({
          txt: "请前往微信中操作",
          type: "warn",
          mask: true
        }).show();
        return;
      }
      this.toast = this.$createToast({
        time: 0,
        mask: true,
        txt: "正在加载中"
      });
      this.toast.show();
      // 中南财大
      if (this.isZncd) {
        //第二个参数 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
        sdk.getLocation(res => {
          // alert(JSON.stringify(res));
          // latitude
          // longitude
          this.gl(res);
        });
      } else {
        GL(this).then(res => {
          this.gl(res);
        });
      }
    },
    //获取地理位置方法
    gl(res) {
      let _this = this;
      $.ajax({
        url: "https://apis.map.qq.com/ws/geocoder/v1",
        data: {
          location: res.latitude + "," + res.longitude,
          key: "TADBZ-IRBWU-QAXVE-2IWED-UW2F5-YVF66",
          output: "jsonp"
        },
        dataType: "jsonp",
        success(result) {
          if (result.status === 0) {
            let address = result.result.formatted_addresses.recommend;
            _this.submit(address);
          }
        }
      });
    },
    fileSubmitted(files) {
      this.action.data = { fileName: files.name };
    },
    filesAdded(files) {
      let hasIgnore = false;
      const maxSize = 10 * 1024 * 1024; // 10M
      for (let k in files) {
        const file = files[k];
        if (file.size > maxSize) {
          file.ignore = true;
          hasIgnore = true;
        }
      }
      hasIgnore &&
        this.$createToast({
          type: "warn",
          time: 1000,
          txt: "不能上传超过10M的文件"
        }).show();
    },
    // 获取项目异常状态
    getItems() {
      var that = this;
      that.toast = that.$createToast({
        time: 0,
        mask: true,
        txt: "正在加载中"
      });
      that.toast.show();
      that.$http
        .get(
          "/service/form/renderForm/inspection_LinHu_confirm/" +
            that.baseInfo.processInstanceId +
            "/" +
            that.loginUser.id +
            "/" +
            that.baseInfo.id,
          {}
        )
        .then(function(res) {
          that.toast.hide();
          console.log(res.data);
          that.model = res.data.model;
          var fields = res.data.fields;
          console.log(fields);
          fields.forEach(v => {
            v.key = (v.key || "").toString();
            if (v.key.indexOf("sdCheckEnable") > -1) {
              that.xj_arr.push(v);
            }
            if (v.key.indexOf("descriptionTextarea") > -1) {
              that.xj_beizhu = {
                key: v.key,
                name: v.templateOptions.label
              };
            }
          });
          console.log(that.xj_arr);
          console.log(that.xj_beizhu);
          that.forms = that.xj_arr.map(v => ({
            key: v.key,
            name: v.templateOptions.label
          }));
          window.localStorage.setItem("forms", JSON.stringify(that.forms));
        });
    },
    // 提交
    submit(address) {
      this.param.loginUser = this.loginUser;
      this.param.save = this.model.save;
      this.param.close = this.model.close;
      this.param.submit = this.model.submit;
      this.param.toIncident = this.model.toIncident;
      this.param.handler_code = "resolve";
      this.param.inspectionProcessActual = this.baseInfo;
      this.param.address = address;
      console.log(this.param);
      if (
        this.param.inspectionProcessActual.group &&
        this.param.inspectionProcessActual.group.id
      ) {
        //处理组
        this.$http
          .post("/service/bpm/InspectionProcessActual/batchAssign", {
            ids: this.param.inspectionProcessActual.id.toString(),
            userId: this.loginUser.id
          })
          .then(res => {
            if (res.data.status == 200) {
              this.completeIt();
            }
          });
      } else {
        this.completeIt();
      }
    },
    // 完成-公共
    completeIt() {
      var that = this;
      that.$http
        .post(
          "/service/bpm/bpm/completeTask/" +
            that.baseInfo.processInstanceId +
            "/" +
            that.loginUser.id,
          that.param
        )
        .then(function(res) {
          console.log(res.data);
          if (res.data.status == 200) {
            that.toast.hide();
            that.action.target =
              that.action.target +
              that.param.inspectionProcessActual.processInstanceId;
            setTimeout(function() {
              that.$refs.upload.start();
            }, 100);
            $("#fade").fadeIn();
            that.promptingConent = "恭喜您,提交成功!";
            that.promptingStatus = true;
            that.dialog = that
              .$createDialog({
                type: "alert",
                title: "提交成功",
                content: "点击返回列表",
                icon: "cubeic-right",
                onConfirm: (e, promptValue) => {
                  that.$router.push({ path: "/main/inspection" });
                }
              })
              .show();
            setTimeout(function() {
              $("#fade").fadeOut();
            }, 2000);
          }
        });
    },
    // 取消
    cancle() {
      var that = this;
      that.$router.go(-1);
    },
    // 生成事件
    createIncident() {
      for (var i = 0; i < $(".cube-switch.abnormal").length; i++) {
        this.abnormal += $(".cube-switch.abnormal")[i].dataset.label + ",";
      }
      this.$router.push({
        name: "NewIncident",
        params: { data: this.baseInfo, abnormal: this.abnormal }
      });
    }
  },
  created() {
    this.baseInfo =
      this.$route.params.data ||
      JSON.parse(window.localStorage.getItem("insDetailInfo"));
    this.forms = JSON.parse(window.localStorage.getItem("forms")) || [];
    this.title = this.baseInfo.inspectionType.type;
    this.getItems();
  },
  mounted() {
    this.$refs.upload.pause();
  }
};
</script>
<style lang="less" scoped>
.inspedtionDetail {
  .textarea_div {
    margin: 0.4rem;
    .textarea {
      height: 2rem;
    }
  }
  .uplod {
    padding: 0.24rem;
    border-bottom: 0.02rem solid rgb(245, 245, 245);
  }
  .label {
    background-color: #eee;
    height: 0.6rem;
    line-height: 0.6rem;
    padding-left: 0.2rem;
    font-size: 0.24rem;
    color: #666;
  }

  .head {
    font-size: 0.34rem;
    line-height: 0.45rem;
    border-bottom: 0.01rem solid #e6e6e6;
    p {
      padding: 0.24rem 0.48rem;
      i {
        color: #00559d;
      }
      .num {
        margin-left: 1rem;
      }
      .btn {
        float: right;
      }
    }
  }

  .info {
    color: #999;
    font-size: 0.28rem;
    overflow: hidden;
    p {
      line-height: 0.4rem;
      padding: 0.1rem 0.24rem;
      overflow: hidden;
      .overflowEllipsis2 {
        margin-left: 1.96rem;
      }
    }
  }

  .form {
    font-size: 0.32rem;
    color: #333;
    line-height: 0.86rem;
    overflow: hidden;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    .cube-switch {
      margin-top: 0.2rem;
    }
    p {
      line-height: 0.4rem;
      padding: 0.2rem 0.24rem;
      width: 100%;
    }
  }

  .btns {
    font-size: 0.32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.24rem;
    display: flex;
    .btn {
      border: 0.01rem solid #005395;
      color: #005395;
      background-color: #fff;
      flex: 1;
      margin: 0 0.1rem;
      height: 0.88rem;
      line-height: 0.88rem;
      text-align: center;
      border-radius: 0.1rem;
      &.submit {
        background-color: #005395;
        color: #fff;
      }
      &.cancel {
        border-color: #ccc;
        color: #333;
      }
    }
  }
  .showwrap {
    width: 75%;
    text-align: right;
  }
}
</style>
