<template>
  <div class="repair-detail-box">
    <div :class="[
      'repair-content',
      detailStatus === 'unAcceptance' ? 'fixed-page-content' : 'page-content',
    ]">
      <div class="white-box page-1">
        <div class="cell-item">
          <p class="label">当前企业</p>
          <p class="tit">{{ detail.companyName }}</p>
        </div>
        <!-- <div class="cell-item">
          <p class="label">您是想</p>
          <div class="tit">{{ detail.type === "1" ? "报事" : "咨询" }}</div>
        </div> -->
        <div class="cell-item">
          <p class="label">快捷选择</p>
          <div class="tit">{{ detail.serviceType }}</div>
        </div>
        <div class="block-cell-item">
          <p class="label">工单描述</p>
          <div class="tit">
            <div class="textarea">
              {{ !detail.description ? "暂无" : detail.description }}
            </div>
          </div>
        </div>
      </div>
      <div class="white-box page-2">
        <!-- <div class="cell-item">
          <p class="label">位置</p>
          <div class="tit">{{ detail.position === "1" ? "室内" : "公区" }}</div>
        </div> -->
        <div class="block-cell-item">
          <p class="label">补充说明</p>
          <div class="tit">
<!--            <ul class="annex-list-box">-->
<!--              <li class="annex-item" v-for="(item, index) in explainAnnexList" :key="index">-->
<!--&lt;!&ndash;                {{ item }}&ndash;&gt;-->
<!--                <img :src="item" alt="" />-->
<!--              </li>-->
              <van-uploader :file-list="explainAnnexList" disabled class="infoUpload"/>

<!--            </ul>-->
          </div>
        </div>
        <div class="cell-item flex-item">
          <p class="label">联系方式</p>
          <p class="tit tel-box">
            <span>{{ detail.contact }}</span>
            <!-- {{ detail.phone }} -->
            <TelNum :num="detail.contact" :showTel="false" v-if="detail.contact && detail.contact.length > 0" />
          </p>
        </div>
        <div class="cell-item flex-item">
          <p class="label">报事人</p>，
          <p class="tit tel-box">
            <span>{{ detail.reporter }}</span>
            <!-- {{ detail.phone }} -->
            <!-- <TelNum :num="detail.phone" :showTel="false" /> -->
          </p>
        </div>
        <div class="cell-item">
          <p class="label">报事时间</p>
          <p class="tit">{{ detail.createdAt }}</p>
        </div>
      </div>
      <div class="white-box page-3 form-part" style="padding-bottom: 120px">
        <div class="custom-item-tit">
          <div class="tit">
            <div style="padding-left: 15rpx;">
              处理情况
            </div>
          </div>
        </div>
        <div class="block-cell-item">
          <div class="label" style="    display: flex;
    justify-content: space-between;
    align-items: center;">
            <p>处理进展</p>
            <van-button type="warning" size="mini" @click="orderOut()">处理退回</van-button>

          </div>
          <div>
            <van-steps :active="stepActive" :active-color="'#6600FF'" :steps="processSteps">
            </van-steps>
          </div>
        </div>

        <div class="cell-item">
          <p class="label">派单人</p>
          <p class="tit">{{ dispatchUserId2 }}</p>
        </div>
        <div class="cell-item">
          <p class="label">派单时间</p>
          <p class="tit">{{ detail.dispatchTime }}</p>
        </div>

        <div class="block-cell-item">
          <p class="label">备注</p>
          <div class="tit">
            <div class="textarea">
              {{ detail.handleExplain == "null"||!detail.handleExplain || detail.handleExplain == "undefind" ? "暂无" : detail.handleExplain }}
            </div>
          </div>
        </div>

        <div class="block-cell-item">
          <p class="label">
            处理后拍照<span class="tips">（支持图片上传限20M内，最多6张）</span>
          </p>
          <div class="tit" >
            <van-uploader @delete="deleteRYXXZP"   :file-list="handleUrlList" :max-count="6" @after-read="afterRead"
              :show-upload="true">
            </van-uploader>
          </div>

        </div>
        <div class="custom-item-tit">
          <div class="tit">
            <div style="margin-left: 15rpx;">
              处理说明
            </div>
          </div>
        </div>
        <div class="custom-textarea-box">
          <uni-easyinput :disabled="detail.status !== '1'&&detail.status!=2" type="textarea" class="bgcF9F9F9 height218rpx"
            v-model="params.remark" autoHeight placeholder="请填写" show-word-limit>
          </uni-easyinput>
        </div>
        <div class="cell-item">
          <p class="label">结案人</p>
          <p class="tit">{{ handleUserId2 }}</p>
        </div>

        <div class="cell-item">
          <p class="label">结案时间</p>
          <p class="tit">{{ detail.handleTime ? detail.handleTime : "" }}</p>
        </div>
      </div>
    </div>
    <div class="repair-bottom bottom-button" v-if="detail.status == '1'||detail.status==2">
      <button class="btn" @click="onConfirm">{{detail.status==2?'编辑':'提交'}}</button>
    </div>
  </div>
</template>
<script>
import TelNum from "../../subPackages/components/tel-number";
import vanRate from "../../../wxcomponents/weapp/dist/rate";
import {
  editRepair,
  getHandleInfoById,
  getByCodes,
  getUserLocalStorageInfo,
  handleReportBack
} from "@/js_sdk/http";
import {editReportInfo} from "../../../js_sdk/http";
// import Base from '@/pages/base/base'
// import { editRepair } from '@/service/api_repair'
// import { Toast } from 'vant'
// import auth from '@/service/auth'
// import axios from 'axios'
export default {
  components: {
    TelNum,
    vanRate,
  },
  data() {
    return {
      handleUserId2: "",
      userId2: "",
      dispatchUserId2: "",
      dic_key: ["QUICK_SELECTION", "REPAIR_STATUS"],
      dic_SelectList: {},
      detailId: "", // 详情id
      handleUrlList: [],
      fileUrls: [],
      handleUrls: [],
      detailStatus: "1", // 1  待派单  2已派单
      explainAnnexList: [], // 说明附件 type image、图片 video、视频
      processedAnnexList: [], // 附件 type image、图片 video、视频
      stepActive: 0, // 当前处理到哪一步
      processSteps: [
        {
          id: 1,
          status: 1,
          text: "上报",
        },
        {
          id: 2,
          status: 1,
          text: "已受理",
        },
        {
          id: 3,
          status: 1,
          text: "已处理",
        },
        {
          id: 4,
          status: 0,
          text: "已确认",
        },
      ], // 处理流程
      evaluateVal: 0, // 评分
      id: "",
      detail: {},
      fileUrlList: [],
      params: {
        id: "",
        handleUrl: "",
        handleTime: "",
        status: "processed",
      },
    };
  },
  onLoad(option) {
    this.id = option.id;
    this.getByCodes();
  },
  methods: {
    deleteRYXXZP(e){
      console.log(e.detail.file.id)
      let index = this.handleUrlList.findIndex((row)=>{
        return row.id == e.detail.file.id;
      });
      console.log('deleteRYXXZP',index)
      let handleUrlList= JSON.parse(JSON.stringify(this.handleUrlList));
      handleUrlList.splice(index, 1);
      this.handleUrlList= handleUrlList
    },
    async orderOut() {
      let _this = this
      console.log(_this.detail.reportRepairId)
      wx.showModal({
        title: '提示',
        confirmText: '退回',
        content: '是否退回到派单阶段？',
        success: async function (e) {
          if (e.confirm) {
            let outData = {
              id: _this.id,
              reportRepairId: _this.detail.reportRepairId,
              userId: getUserLocalStorageInfo().user.id
            }
            let data = await handleReportBack(outData)
            if (data.code == 200) {
              _this.$showToast('退回成功');
              uni.navigateBack({});
            }
            // 用户点击了确定 可以调用删除方法了
          } else if (e.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    async getByCodes() {
      let data = await getByCodes(JSON.stringify(this.dic_key));
      this.dic_SelectList = this.$common.handleDicList(data);
      this.getDetailById();
    },
    onSelect(val) {
      this.value = val.text;
      this.params.handleUserId = val.value + "-" + val.text;
      this.showPicker = false;
    },
    onConfirm(value) {
      let that = this;
      uni.showModal({
        title: '提示',
        content: '是否确认提交',
        success: function (res) {
          if (res.confirm) {
            if (!that.params.remark || that.params.remark.length == 0) {
              that.$showToast("请填写处理说明");
              return;
            }
            that.params.id = that.id;
            //   handleUrlList
            that.params.handleTime = that.detail.handleTime;
            //   this.params.handleUrlList = this.params.handleUrlList.join(",");
            let handleUrlList = [];
            if (that.handleUrlList && that.handleUrlList.length > 0) {
              handleUrlList = that.handleUrlList.map((e) => {
                return e.id;
              });
            }
            // console.log(this.handleUrlList);
            // console.log(handleUrlList.join(","))
            // return;
            that.params.handleExplain = that.detail.handleExplain;
            that.params.updatedBy = getUserLocalStorageInfo().user.id;
            that.params.handleUrl = handleUrlList.join(",");
            that.params.userId = getUserLocalStorageInfo().user.id;
            if(that.detail.status==2){
              let params = {...that.params}
              delete params.status;
              editReportInfo(params).then((res) => {
                debugger
                that.$showToast("结案成功");
                uni.switchTab({
                  url: "/pages/index/index",
                });
                // this.$router.push({ path: "/repairprocessing-app" });
              });
            }else{
              let params = {...that.params}
              delete params.status;
              editRepair(params).then((res) => {
                that.$showToast("结案成功");
                uni.switchTab({
                  url: "/pages/index/index",
                });
                // this.$router.push({ path: "/repairprocessing-app" });
              });
            }
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });


    },
    getDetailById() {
      const _this = this;
      getHandleInfoById(_this.id).then((res) => {
        console.log(res.data);
        if (res.data) {
          let det = _this.getItemJson(res.data);
          this.detail = det;
          this.detail.handleExplain = det.handleExplain;
          // if (det.userId != null && det.userId !== "") {
          //   const test = det.userId.split("-");
          //   this.detail.phone = test[2];
          //   this.userId2 = test[1] + "-" + test[2];
          // }
          if (det.dispatchUserId != null && det.dispatchUserId !== "") {
            const test = det.dispatchUserId.split("-");
            console.log(test);
            this.dispatchUserId2 = test[1] + "-" + test[2];
          }
          if (det.handleUserId != null && det.handleUserId !== "") {
            // const test = det.handleUserId.split("-");
            // console.log(test);

            this.handleUserId2 = det.handleUserName;
          }
          console.log('det.handleUrlList',det.handleUrlList)
          this.handleUrlList = det.handleUrlList;
          if(det.fileUrl&&det.fileUrl.length > 0) {
            this.explainAnnexList = det.fileUrl.split(',').map(e => {
              return{
                url:this.$constant.BASE_URI + "/wx/fileController/download/" + e,
                id:e,
                isImage: true,
                deletable: false,
              }
            });
          }

          console.log("asodmqowndonq", this.explainAnnexList);

          //   this.processedAnnexList = det.handleUrlList;
          this.detailStatus = det.status;
          this.params.remark = det.remark;
        }
      });
    },
    getItemJson: function (item) {
      // const fileUrls = item.fileUrl ? item.fileUrl.split(",") : [];
      //
      // const fileUrlViews = [];
      // if (fileUrls !== null && fileUrls.length > 0) {
      //   fileUrls.forEach((item) => {
      //     item =
      //       this.$constant.BASE_URI + "/wx/fileController/download/" + item;
      //     fileUrlViews.push(item);
      //   });
      // }
      // item.fileUrlViewList = fileUrlViews;
      if (!item.handleTime) {
        item.handleTime = this.$common.transServDate(new Date());
      }

      const handleUrl = item.handleUrl ? item.handleUrl.split(",") : [];

      const handleUrlViews = [];
      if (handleUrl !== null && handleUrl.length > 0) {
        handleUrl.forEach((item) => {
          handleUrlViews.push({
            url:
              this.$constant.BASE_URI + "/wx/fileController/download/" + item,
            isImage: true,
            id:item
          });
        });
      }
      item.handleUrlList = handleUrlViews;
      console.log(item.handleUrlList);
      item.serviceType =
        this.dic_SelectList.QUICK_SELECTION[item.serviceType - 1].label;

      switch (item.status) {
        // console.log(status)
        case "0":
          this.stepActive = 0;
          break;
        case "1":
          this.stepActive = 1;
          break;
        case "2":
          this.stepActive = 2;
          break;
        case "3":
          this.stepActive = 3;
          break;
        case "4":
          this.stepActive = 0;
          break;
        case "5":
          this.stepActive = 5;
          break;
      }

      return item;
    },
    afterRead(event) {
      let that = this;
      const { file } = event.detail;

      try {
        uni.uploadFile({
          url: that.$constant.BASE_URI + "/wx/fileController/upload",
          filePath: file.url,
          name: "file",
          formData: { user: "test" },
          success(res) {
            // 上传完成需要更新 fileList
            let { data } = JSON.parse(res.data);
            console.log(data[0]);

            that.handleUrlList.push({
              id: data[0],
              url:
                that.$constant.BASE_URI + "/FileController/download/" + data[0],
              isImage: true,

            });
            that.handleUrlList = [...that.handleUrlList];
            that.$forceUpdate();
            console.log(that.fileUrlList);
          },
          fail(res) { },
        });
      } catch (error) { }
    },
    beforeDelete(file, detail) {
      // this.handleImagUrlList = []
      const vm = this;
      // name.index代表图片的索引
      vm.handleUrls.splice(detail.index, 1);
      return (file, name) => {
        const fileIndex = name.index;
        vm.handleUrls[detail.index].splice(fileIndex, 1);
      };
    },
    /**
     * 上传图片
     */
    uploadImg(file) {
      const _this = this;
      const formParam = new FormData(); // 创建form对象
      formParam.append("file", file.file); // 通过append向form对象添加数据
      console.log(formParam.get("file")); // FormData私有类对象，访问不到，可以通过get判断值是否传进去
      // upload(formParam).then((res) => {
      //
      // })
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
          "MVVM-Key": String(new Date().getTime()),
          xx: "anything",
        }, // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
      }; // 添加请求头
      return new Promise((resolve, reject) => {
        axios
          .post(
            "/smartParkH5Server/wx/fileController/upload",
            formParam,
            config
          )
          .then((response) => {
            let files = response.data.data.substring(
              1,
              response.data.data.length
            );
            files = files.substring(0, files.length - 1);
            _this.handleUrls.push(_this.$common.castEval(files));
          })
          .catch((err, x) => {
            reject(err, x);
          });
      });
    },
  },
};
</script>
<style lang="scss">
.infoUpload{
  .van-uploader__upload--disabled{
    display: none;
  }
}
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  z-index: 100;
  height: 160rpx;
  padding: 35rpx 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;

  .btn {
    height: 100%;
    line-height: 80rpx;
    width: 100%;
    color: #fff;
    background-color: #6600ff;
    font-size: 34rpx;
    border-radius: 10rpx;
  }
}

.repair-detail-box {
  .page-4 {
    .evaluate-box {
      padding: 20rpx 30rpx;
      background: $page-color-base;
      border: 1rpx solid #ebedf0;
      border-radius: 100rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
    }
  }

  width: 100%;
  height: 100%;

  .page-1 {
    .textarea {
      padding: 20rpx;
      border-radius: 10rpx;
      background: $page-color-base;
      box-sizing: border-box;
    }
  }

  .page-3 {
    padding-bottom: 100rpx;

    .input-item {
      padding: 0;
    }

    .custom-item-tit {
      height: 13.333vw;
      font-size: 4.267vw;
      color: #333;
      padding: 2.667vw 0;
      position: relative;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: justify;
      -ms-flex-pack: justify;
      justify-content: space-between;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;

      .tit {
        &::after {
          content: "";
          width: 0.8vw;
          height: 90%;
          background-color: #976dec;
          border-radius: 0.4vw;
          position: absolute;
          left: 0;
          top: 50%;
          -webkit-transform: translateY(-50%);
          transform: translateY(-50%);
        }
      }
    }

    .tit {
      // padding-left: 2.667vw;
      position: relative;
    }
  }

  .page-4 {
    .custom-item-tit {
      height: 13.333vw;
      font-size: 4.267vw;
      color: #333;
      padding: 2.667vw 0;
      position: relative;
      display: -webkit-box;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-pack: justify;
      -ms-flex-pack: justify;
      justify-content: space-between;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;

      .tit {
        &::after {
          content: "";
          width: 0.8vw;
          height: 90%;
          background-color: #976dec;
          border-radius: 0.4vw;
          position: absolute;
          left: 0;
          top: 50%;
          -webkit-transform: translateY(-50%);
          transform: translateY(-50%);
        }
      }
    }

    .tit {
      padding-left: 2.667vw;
      position: relative;
    }

    s .evaluate-box {
      padding: 20px 30px;
      background: $page-color-base;
      border: 1px solid #ebedf0;
      border-radius: 100px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
    }
  }

  .annex-list-box {
    display: flex;

     flex-wrap: wrap;
     justify-content: space-between;
    &::after {
      display: block;
      content: "";
      width: 30%;
      height: 0px;
    }

    .annex-item {
      width: 30%;
      height: 240rpx;
      border: 1px solid $text4;
      margin-bottom: 20px;
      position: relative;
      overflow: hidden;

      >img {
        width: 240rpx;
        height: 240rpx;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        display: block;
      }

      video {
        width: 100%;
        height: 100%;
      }
    }
  }

  .tel-box {
    display: flex;
    align-items: center;

    /deep/ .custom-tel-component {
      margin-left: 20px;
    }
  }
}
</style>
<style lang="scss">
.image-repairDispatch-box {
  .van-image-preview__close-icon {
    color: #fff;
    font-size: 64px;
  }
}
</style>s
