<template>
<div id="app" style="margin-top:30px;font-size: 14px; color: #606266;">
 <el-form :inline="true" :model="listQuery" class="form-listQuery">
      <div style="transform:translateY(-70%);">
         <span style="padding-right:0%;font-weight:bold;font-size:12px;">工单详情</span>
     </div>
     <div>
       <table>
         <tr>
          <td width="21.3%" style="padding-left:0.8%;"  nowrap>工单号：&nbsp;{{listQuery.id}}</td>
          <td width="22%" nowrap>工单类型：&nbsp;
              <span v-if="listQuery.type==='1'">{{'投诉'}}</span>
              <span v-if="listQuery.type==='2'">报修
              <span v-if="listQuery.repairType==='0'">{{'(公共区域)'}}</span>
              <span v-if="listQuery.repairType==='1'">{{'(房屋质量)'}}</span>
              <span v-if="listQuery.repairType==='2'">{{'(户内设施)'}}</span>
              </span>
              <span v-if="listQuery.type==='3'">{{'联系物业'}}</span>
          </td>
          <td width="22%" nowrap>发起时间：&nbsp;{{ formatDate(listQuery.createDate) }}</td>
          <td width="23%" nowrap>发起人：&nbsp;{{listQuery.createUserNmae}}</td>
          <td nowrap>发起人联系方式：&nbsp;{{listQuery.loginName}}</td>
        </tr>
      </table>
    </div>
    <!-- <div class="sizeWhits">
      <el-form-item style="padding-left:1%;" label="工单号:">
        <span>{{listQuery.id}}</span>
      </el-form-item>
      <el-form-item style='margin-left:330px' label="工单类型:">
        <span v-if="listQuery.type==='1'">{{'投诉'}}</span>
        <span v-if="listQuery.type==='2'">报修
          <span v-if="listQuery.repairType==='0'">{{'(公共区域)'}}</span>
          <span v-if="listQuery.repairType==='1'">{{'(房屋质量)'}}</span>
          <span v-if="listQuery.repairType==='2'">{{'(户内设施)'}}</span>
        </span>
        <span v-if="listQuery.type==='3'">{{'联系物业'}}</span>
      </el-form-item>
      <el-form-item style='margin-left:330px' label="发起时间:">
        <span>{{ formatDate(listQuery.createDate) }}</span>
      </el-form-item>
      <el-form-item style='margin-left:330px' label="发起人:">
        <span>{{listQuery.createUserNmae}}</span>
      </el-form-item>
      <el-form-item style='margin-left:300px' label="发起人联系方式:">
        <span>{{listQuery.loginName}}</span>
      </el-form-item>
      </div> -->

      <div style="transform:translateY(20%);">
        <el-form-item style="padding-left:1%;" class="filter-item" label="工单标题:" >
         <span>{{listQuery.ticketTitle}}</span>
        </el-form-item>
        <el-form-item  label="当前负责人:" class="size-left">
         <span>{{listQuery.tpUserNmae}}</span>
      </el-form-item>
      </div>
      <div>
        <el-form-item style='padding-left:20px'>
        <div>内容：<span style="text-align:left;margin-left:-100px;padding:100px">{{listQuery.ticketContent}}</span></div>
      </el-form-item>
       <!-- <table >
          <tr><td><span>内容</span></td>
          <td><div>
                <span >{{listQuery.ticketContent}}</span>
              </div>
          </td>  
        </tr>
      </table>  -->
      </div>

      <div style="padding-left:200px;">
    <template >
      <img v-for="sr in listQuery.contentImageUrl" :src="sr" preview  width="200" height="200"  style="margin:5px;">
       <!-- <img v-for="sr in listQuery.contentImageUrl" :src="sr" preview="ss" preview-text="ss" width="200" height="200"> -->
    </template>
    </div>

        <hr width="101%"/>
<div class="stepComponent" >
    <div class="stepsTitle">
      <div style="float:left;width:2px;height:20px; background:#219AFF;"></div> 
        <span>&nbsp;&nbsp;沟通记录</span>
    </div>
    <!-- 一下状态是数据库的所有状态，如需要加状态，页面得加相同状态的div -->
    <div class="approvalProcess">
        <el-steps :active="7" finish-status="success" direction="vertical">
          <el-step :title="item.statusName+'_________'+formatDate(item.createDate)" v-for="item in approvalProcessProject">
            <template slot="description">
             <div class="step-row" >
               <tr v-if="item.status - 0 === 5"><td>评价：</td><td><el-rate
                v-model="listQuery.score"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}">
              </el-rate></td></tr>
              <tr v-if="item.status - 0 === 5" ><td>评语：</td><td>{{listQuery.comment}}</td></tr>
             <div style="margin-top:8px;"> <tr v-if="item.status - 0 === 5"><td>{{formatDate(item.createDate)}}</td></tr></div>
               <table width="100%" border="0" cellspacing="0" cellpadding="0" class="processing_content"  v-for="itemContent in item.statusContent" >
                         <tr> 
                           <td>                        
                            	<div class="processing_content_detail" style="float:left;width:70%">
                                    <span>{{itemContent.userName}}:{{itemContent.content}}                               
                                    <span style="color:#219AFF"></span>
                                    </span>
                                    </div>                    
                            </td>
                          </tr>
                          <tr>
                            <td>
                            	<div class="processing_content_detail" style="float:left;width:90%">
                                <div style="float:left;width: 2px;height: 20px; background:#C7D4E9;margin-left:10px;margin-right:10px"></div> 
                                <!-- <img :src="contentImgURL.imageUrl"  v-for="contentImgURL in itemContent.imgURL" preview preview-text="描述"  width="200" style="margin:5px;"> -->
                                        <img v-for="contentImgURL in itemContent.imgURL" :src="contentImgURL.imageUrl" preview width="100" height="100"  style="margin:5px;">
                                          <div><span ><i class="el-icon-time"></i>{{formatDate(itemContent.createDate)}}</span> </div>
                                          <div> <hr style="height:1px;border:none;border-top:1px solid #FF8888;"  width="200%"/></div>                                          
                                </div>                                                       
                            </td>
                          </tr>
                </table>                       
           </div>
         </template>
           </el-step>
        </el-steps>
  </div>
        <div v-if="listQuery.status==='0'||listQuery.status==='3'">
        <div>
        <span>参与沟通</span>
        </div>
        <br>
          <div>   
          <textarea v-model="listQuery.textContent" placeholder="回复TA或向TA提问" class="textarea-inherit" id="message_textarea" rows="4"></textarea> 
        </div>
        <div>
        <el-form-item label="图片附件">
        <el-upload
          :limit="8"
          :before-upload="handleCompressReply"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccessContentImg"
          action=""
          :file-list="listQuery.img"
          :show-file-list="Ass"
          list-type="picture-card">
          <i class="el-icon-plus"/>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt="">
        </el-dialog>
      </el-form-item>
        <el-button type="primary" @click="submitContent" style="margin-left: 90%;transform:translateY(-340%);">提交</el-button>
        </div>
        </div>
        <div v-if="listQuery.status==='3'">
        <div>
        <span>流程操作</span>
        </div>
        <br>
          <div>   
          <textarea v-model="listQuery.relationContent" placeholder="处理完了?在此填写处理结果，发送给户主让TA给好评~" class="textarea-inherit" id="message_textarea" rows="4"></textarea>
        </div>
        <div>
        <el-form-item label="图片附件">
        <el-upload
          :limit="8"
          :before-upload="handleCompress"
          :on-preview="handlePictureCardPreviewIO"
          :on-remove="handleRemoveIO"
          :on-success="handleSuccessContentImgIO"
          :file-list="listQuery.imgIO"
          :show-file-list="Ass"
           action=""
          list-type="picture-card">
          <i class="el-icon-plus"/>
          </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" width="100%" alt="">
          </el-dialog>
        </el-form-item>
        <el-button type="primary" @click="succeedClick" style="margin-left: 90%;transform:translateY(-340%);">发送处理结果</el-button>
        </div>
        </div>
        
        <div  v-if="listQuery.status==='0'">
        <el-form-item style="width:1000  px" >
         <el-select v-model="listQuery.selectVale" placeholder="请选择工单由谁负责,然后点击受理分配"  >
          <el-option label="请选择工单由谁负责,然后点击受理分配" value="-1" />
          <el-option label="我自己" :value="listQuery.currentUserName"/>
          <el-option  v-for="user in listQuery.userList" :label="user.userName" :value="user.id"/>
        </el-select>
      </el-form-item>
       <el-button type="primary" @click="addRecord">受理分配</el-button>
       <a><span style="margin-left: 600px;color: #009FCC"  @click="noAccept">{{'拒绝受理?'}}&nbsp;&nbsp;&nbsp;&nbsp;</span></a><span>{{'拒绝受理即关闭此工单，不再进行后续任何流程，请谨慎'}}</span>
        </div>
</div>
</el-form>
</div>
</template>
<script>
import { mapActions } from 'vuex'
import Qs from 'qs'
export default {
  data() {
    return {
      listQuery: {
        id: '',
        userName: '',
        comment:'',
        communityId: '',
        contentImageUrl:[],
        createDate: '',
        createUser: '',
        createUserNmae: '',
        currentUserName: '',
        loginName: '',
        recordList: [],
        repairType: '',
        score:'',
        status: '',
        taUserId: '',
        ticketContent: '',
        ticketRecordCommentImagesUrl: [],
        ticketTitle: '',
        tpTicketRecordCommentList: '',
        tpUserId: '',
        tpUserNmae: '',
        type: '',
        img: [],
        imgIO: [],
        updateDate: '',
        updateUser: '',
        statusList: [],
        userList:[],
        textContent: '',
        selectVale : '-1',
        noAcceptContent : '',//拒绝的对话内容
        relationContent : '',//流程操作内容
        relationImg : []//流程操作的图片

      },
      //  timeId :'',
       active:2,
       dialogVisible: false, // 内容配图,
       dialogImageUrl:'',
       dialogImageUrlIO :'',
       approvalProcessProject:[     
       ],
       imgURL:[],
       content:[],
       contentImgAA: [],
       contentImgIO: [],
       contentImgList: [],//图片集合
       contents:[],
       Ass: true,
       value5: 5
    }
  },
  mounted() {
    // console.log(this.$route.query.id)
    this.listQuery.id=this.$route.query.id
      this.dataQuery(this.listQuery.id)
  },
  methods: {
     dataQuery() { // 查询数据
    //  this.listQuery.id=this.$route.params.id
      this.$store.dispatch('TicketEdit', this.listQuery).then((res) => {
        const resDate=res.data
        this.listQuery=resDate
        this.approvalProcessProject = resDate.recordList
      }).catch(() => {
        console.log('error TicketEdit')
      })
    },
    //对话的图片控件
    handlePictureCardPreview(file) { // 配图文件列表中已上传的文件时的钩子
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //对话的图片控件
    handleRemove(file, fileList) { // 配图移除时
      this.contentImgAA = []
      for (let i = 0; i < fileList.length; i++) {
      this.contentImgAA.push(fileList[i].response.data[0])
      }
      // console.log('file',file, fileList)
    },
    //对话的图片控件
    handleSuccessContentImg(response, file, fileList) { // 配图上传成功时回调
      const resImg = response.data[0]
      // console.log('resImg',resImg)
      this.contentImgAA.push(resImg)
    },
    //流程的图片
    handlePictureCardPreviewIO(file) {
      this.dialogImageUrlIO = file.url
      this.dialogVisible = true
    },
     //流程的图片
    handleRemoveIO(file, fileList) { // 流程配图移除时
      this.contentImgIO = []
      for (let i = 0; i < fileList.length; i++) {
      this.contentImgIO.push(fileList[i].response.data[0])
      }
      // console.log('file',file, fileList)
    },
    //流程的图片
    handleSuccessContentImgIO(response, file, fileList) { // 流程配图上传成功时回调
      const resImg = response.data[0]
      this.contentImgIO.push(resImg)
    },
    //回复压缩
    handleCompressReply(file) {  // 图片压缩
      let self = this;
      return new Promise((resolve, reject) => {
        var reader = new FileReader()
        reader.onload = function (e) {
          var data = e.target.result
          // 加载图片获取图片真实宽度和高度
            var image = new Image()
            image.onload = function () {
            let newdata = self.compress(image);
            let blob = self.dataURItoBlob(newdata);
            var formData = new FormData();
            formData.append("file", blob);
            formData.append("newdata", newdata);
            // console.log("********将blob对象转成formData对象********");
            // console.log(formData.get("file"));
            // console.log('formData',formData) 

            // console.log(formData)
            let data = {"uploadFiles": newdata }
              self.$store.dispatch('ImgAdd', Qs.stringify(data)).then((res) => {
               self.contentImgAA.push(res.data[0])
              //  console.log('this.contentImgIO',res.data[0])
              //  console.log('this.listQuery.contentImgIO',self.contentImgIO)      
             })
          }
          image.src = data
        }
        reader.readAsDataURL(file)
      })
    },
    //流程压缩
    handleCompress(file) {  // 图片压缩
      let self = this;
      return new Promise((resolve, reject) => {
        var reader = new FileReader()
        reader.onload = function (e) {
          var data = e.target.result
          // 加载图片获取图片真实宽度和高度
            var image = new Image()
            image.onload = function () {
            let newdata = self.compress(image);
            let blob = self.dataURItoBlob(newdata);
            var formData = new FormData();
            formData.append("file", blob);
            formData.append("newdata", newdata);
            // console.log("********将blob对象转成formData对象********");
            // console.log(formData.get("file"));
            // console.log('formData',formData) 

            // console.log(formData)
            let data = {"uploadFiles": newdata }
              self.$store.dispatch('ImgAdd', Qs.stringify(data)).then((res) => {
               self.contentImgIO.push(res.data[0])
              //  console.log('this.contentImgIO',res.data[0])
              //  console.log('this.listQuery.contentImgIO',self.contentImgIO)      
             })
          }
          image.src = data
        }
        reader.readAsDataURL(file)
      })
    },
    // 压缩图片
    compress(img) {
      let canvas = document.createElement("canvas");
      let ctx = canvas.getContext("2d");
      let initSize = img.src.length;
      let width = img.width;
      let height = img.height;
      canvas.width = width;
      canvas.height = height;
      // 铺底色
      ctx.fillStyle = "#fff";
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);

      //进行最小压缩
      let ndata = canvas.toDataURL("image/jpeg", 0.8);
      // console.log("*******压缩后的图片大小*******");
      // window.atob(ndata);
      // console.log(' window.atob(ndata);', window.atob(ndata))
      // console.log(ndata)
      // console.log(ndata.length);
      return ndata;
    },
    // base64转成bolb对象
    dataURItoBlob(base64Data) {
      var byteString;
      if (base64Data.split(",")[0].indexOf("base64") >= 0)
        byteString = atob(base64Data.split(",")[1]);
      else byteString = unescape(base64Data.split(",")[1]);
      var mimeString = base64Data
        .split(",")[0]
        .split(":")[1]
        .split(";")[0];
      var ia = new Uint8Array(byteString.length);
      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
      }
      return new Blob([ia], { type: mimeString });
    },
    // 时间处理
    formatDate(val) {
      var value = new Date(val)
      var year = value.getFullYear()
      var month = value.getMonth() + 1
      var day = value.getDate()
      var hour = value.getHours()
      var minutes = value.getMinutes()
      var seconds = value.getSeconds()
      // var minut=minutes<10?minutes:'0'+minutes

      return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
      // return year + '-' + month + '-' + day
    },
    // 回复
    submitContent(){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      if(this.listQuery.textContent===undefined||this.listQuery.textContent===''){
         this.$message.error('请输入内容')
         loading.close()
         return
      }
         this.listQuery.img=this.contentImgAA
         this.$store.dispatch('AddRecordComment', this.listQuery,).then((res) => {
         this.Ass=false
         this.contentImgAA=[]
         this.dataQuery()
         this.Ass=true
         loading.close()
      }).catch(() => {
        console.log('error addRecordComment')
      })
    },
        //受理人添加
        addRecord(){
          console.log('(this.listQuery.selectVale',this.listQuery.selectVale)
          if(this.listQuery.selectVale==='-1'||this.listQuery.selectVale===undefined){
            this.$message({
            showClose: true,
            message: '请您选择正确的受理人'
            });
            return
          }
          
        const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })  
        this.$store.dispatch('AddRecord', this.listQuery).then((res) => {
          this.dataQuery()
           loading.close()
           this.$message({
          message: '分配成功',
          type: 'success'
        })    
      }).catch(() => {
        console.log('error AddRecord')
      })
    },
    //拒绝处理
    noAccept() {
        this.$prompt('请输入拒绝原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(({value}) => {
           if(value===null){
          this.$message.error('请填写拒绝原因')
          return this.repetition();
          }
        const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      }) 
          this.listQuery.noAcceptContent = value 
        this.$store.dispatch('UpdateTicketStatus', this.listQuery).then((res) => {
          this.dataQuery()
          loading.close()
      }).catch(() => {
        console.log('error AddRecord')
      })   
          this.$message({
            message: '成功',
            type: 'success',
          });
        })
      },
      repetition(){
          this.noAccept()
      },
      // 流程提交
    succeedClick(){
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)' 
        })

        if(this.listQuery.relationContent===undefined||this.listQuery.relationContent===''){
         this.$message.error('请填写内容')
         loading.close()
         return
      }    
         this.listQuery.imgIO = this.contentImgIO
        this.$store.dispatch('UpdateTicket', this.listQuery).then((res) => {
          this.Ass=false
          this.contentImgIO = []
          this.dataQuery()
          this.Ass=true
          this.$message({
          message: '发送成功，等待评价',
          type: 'success',
        })
          loading.close()
      }).catch(() => {
        console.log('error UpdateTicket')
      })
        this.contentImgIO = []
    },
     next() {
        if (this.active++ > 2) this.active = 0;
      },
  }
};
</script>
<style scoped>
  .stepComponent{
      width: 100%-20px;
      padding: 10px 10px 10px 10px;
      margin: 10px 10px 10px 10px;
  }
  .stepsTitle{
      margin: 10px 0px  10px  10px ;
  }
  .approvalProcess{
      color: #9EADC4;
      font-size: 14px;
      width: 100%;
      margin-left:20px;
      margin-right:0px;
      margin-top:10px;
  }
  /* .processing_content{
    background-color: #D9E5F9;
  } */
  .processing_content_detail{
     margin-left: 10px;
     margin-top: 3.5px;
     margin-bottom: 3.5px;
	   width:200px;
     display:inline-block;
  }
  .step-row{
     min-width:400px;
     margin-bottom:12px;
     margin-top:12px;
  }
  .filter{
  margin-top: 10px;
  float:right
  }
 .size-left{
  float:right;width:12.5%;
}
.textarea-inherit {
        width: 100%;
        overflow: auto;
        word-break: break-all; 
    }
    .select-inherit {
        width: 100%;
        
    }
    .table-finally{
    padding-right: 10%;
    }
</style>
