import { mapState } from "vuex";
import axios from 'axios'
import { getTicketDetails, getSubmitAuditTicket, getResubmitTicket,getEndTicket, getDownloadFile, getRetractTicket } from "../../api/help"
export default {
  data() {
    return {
      helpLoading: false,
      imgSrc: "https://studio.glassnode.com/images/crypto-icons/btc.png",
      navLabel: "Bitcoin (BTC)",
      userName: "LX",
      from: {
        title: "",
        kinds: "",
        description: ""
      },
      kindsList: [{
        value: "购买咨询",
        label: "购买咨询",
      }, {
        value: "财务咨询",
        label: "财务咨询",
      }, {
        value: "网页问题",
        label: "网页问题",
      },
      {
        value: "账户问题",
        label: "账户问题",
      },
      {
        value: "移动端问题",
        label: "移动端问题",
      },
      {
        value: "消息订阅",
        label: "消息订阅",
      },
      {
        value: "指标数据问题",
        label: "指标数据问题",
      },
      {
        value: "其他",
        label: "其他",
      }],
      params: {
        id: ""
      },
      input: 1,
      tableData: [{
        num: 1,
        time: "2022-09-01 16:00",
        problem: "账户问题",
        questionTitle: "账户不能登录",
        state: "已解决"
      }],
      textarea: "我是提交内容",
      textarea1: "我是回复内容",
      textarea2: "",
      ticketDetails: {
        id: "",
        type: "",
        title: "",
        userName: "",
        desc: "",
        responName: "",
        respon: "",
        submitTime: "",
        status: "",
        fileIds: "",
        files: "",
        responTime: ""

      },
      paramsResubmit: {//继续提交参数
        id: "",
        desc: "",
        files: "",
      },
      //上传后的文件列表
      fileList: [],
      // 允许的文件类型
      fileType: ["rar", "doc", "txt", "png", "jpg", "jpeg",],
      // 运行上传文件大小，单位 M
      fileSize: 20,
      // 附件数量限制
      fileLimit: 3,
      //请求头
      headers: { "Content-Type": "multipart/form-data" },
      FormDatas: null,
      filesId: [],
      paramsDownload: {
        id: ""
      },
      //撤回工单参数
      paramsRetractTicket: {
        id: ""
      },
      WorkOrderDetailsLoading: false,
      detailsID: "",
      submitShow: true,// 继续提交部分是否显示
      //提交审核参数
      paramsSubmitAuditTicket: {
        id: ""
      },
      //审核信息
      auditList: {},
      downloadUrl: "",
      dialogVisible:false




    }
  },
  computed: {
    ...mapState({
      current: (state) => state.tab.currentMenu,
    }),
  },
  // created(){
  //   this.$addStorageEvent(1, "detailsID",this.$route.params.id  );


  // },
  mounted() {
    this.detailsID = localStorage.getItem("detailsID")
    window.addEventListener("setItem", () => {
      this.detailsID = localStorage.getItem("detailsID")
    });
    this.fetchTicketDetails({ id: this.detailsID })

 

  },
  methods: {
    //请求工单详情
    async fetchTicketDetails(data) {
      this.WorkOrderDetailsLoading = true
      const list = await getTicketDetails(data)
      if (list.data.code !== 200) {
        this.$message({
          message: list.data.msg,
          type: "error",
          customClass: "messageClass",
        });
        return
      }
      this.auditList = list.data.data.audit
      this.ticketDetails = list.data.data
      this.ticketDetails.submitTime = `${this.ticketDetails.submitTime.split(`T`)[0]} ${this.ticketDetails.submitTime.split(`T`)[1].split(`.`)[0]}`

      if (this.ticketDetails.status == "撤回") {
        this.submitShow = false
      }
      this.WorkOrderDetailsLoading = false
    },

    //请求继续提交工单
    async fetchResubmitTicket(data) {
      const list = await getResubmitTicket(data)
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });

        for (const key in this.paramsResubmit) {//清空工单
          this.paramsResubmit[key] = ""
        }
        //再次请求工单详情
        this.fetchTicketDetails({ id: this.detailsID })

        this.fileList = [] // 清空已上传列表

      }



    },
    //请求文件下载
    async fetchDownloadFile(ids) {
      this.WorkOrderDetailsLoading = true
      // const list = await getDownloadFile(data)
      const list = await this.$API.getDownloadFile(ids)
      this.$message({
        message: list.data.msg,
        type: "warning",
        customClass: "messageClass",
      });

      this.WorkOrderDetailsLoading = false
    },
    //请求提交审核
    async fetchSubmitAuditTicket(data) {
      
      this.WorkOrderDetailsLoading = true
      const list = await getSubmitAuditTicket(data)
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });

        for (const key in this.ticketDetails) {//清空工单
          this.ticketDetails[key] = ""
        }

      }
      this.WorkOrderDetailsLoading = false

    },
    //请求撤回工单
    async fetchRetractTicket(data) {
      this.WorkOrderDetailsLoading = true
      const list = await getRetractTicket(data)
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });

        for (const key in this.ticketDetails) {//清空工单
          this.ticketDetails[key] = ""
        }
        this.$router.back()//回到上一个页面 


      }

      this.WorkOrderDetailsLoading = false


    },
     //请求结束工单
     async fetchEndTicket(data) {
      this.WorkOrderDetailsLoading = true
      const list = await getEndTicket(data)
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });

        for (const key in this.ticketDetails) {//清空工单
          this.ticketDetails[key] = ""
        }
        this.WorkOrderDetailsLoading = false

        this.$router.back()//回到上一个页面
      }




    },
    //点击继续提交按钮
    handelResubmit() {
      if (!this.paramsResubmit.desc) {//判空
        this.$message({
          message: this.$t(`help.resubmit`),
          type: "error",
        });
        return
      }
      this.paramsResubmit.id = this.ticketDetails.id


      if (this.fileList[0]) {//有附件
        //上传文件的需要formdata类型;所以要转
        this.FormDatas = new FormData()
        this.fileList.forEach(fileItem => {
          this.FormDatas.append('file', fileItem);
        })
        // 上传选择附件     
        this.$axios({
          method: 'post',
          url: 'marketall/ticket/uploadFile',
          headers: this.headers,
          timeout: 30000,
          data: this.FormDatas
        }).then(res => {
          this.paramsResubmit.files = res.data.data.id

          if (this.paramsResubmit.files) {//成功拿到返回ID
            this.fetchResubmitTicket(this.paramsResubmit) //提交工单
          }
        })
      } else {

        this.fetchResubmitTicket(this.paramsResubmit)

      }






    },
    // 点击撤回按钮
    handelRetractTicket() {
      this.paramsRetractTicket.id = this.ticketDetails.id
      this.fetchRetractTicket(this.paramsRetractTicket)
    },
    //点击请求审核按钮
    handelSubmitAuditTicket() {
      if (this.ticketDetails.status == "待审核") { //阻止待审核状态下重复提交
        this.$message({
          message: this.$t(`help.toAudit`),
          type: "error",
        });
        return
      }
      this.paramsSubmitAuditTicket.id = this.ticketDetails.id
      this.fetchSubmitAuditTicket(this.paramsSubmitAuditTicket)


    },

    //选择问题种类
    handelKinds() {

    },
    onUpload() {

    },
    //点击下载附件
    downloadExcel(id) {

      this.downloadUrl = ` ${axios.defaults.baseURL}/marketall/ticket/downloadFile?ids=${id}`

      // this.downloadUrl = ` http://10.168.2.125:7101/marketall/ticket/downloadFile?ids=${id}`
      let a = document.createElement(`a`)
      a.href = this.downloadUrl
      a.click()
      // console.log("及附加覅附件");
      // window.location.href = "http://10.168.2.125:9300/statics/2023/04/03/image_2023_03_23T07_41_35_865Z_20230403165504A001.png";
      // this.paramsDownload.id = id

      // this.fetchDownloadFile(id)

    },
    //上传文件之前
    beforeUpload(file) {
      // 获取所有已上传的文件列表
      // const uploadedFiles = this.fileList.map((f) => f.name);
      // // 如果已上传的文件列表包含当前文件的名字，返回 false 阻止上传
      // if (uploadedFiles.includes(file.name)) {//不能上传相同名字的文件！
      //   this.$message.warning(this.$t(`help.sameName`));
      //   return false;
      // }


      // 校验文件类型和大小
      const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
      const isTypeValid = this.fileType.includes(fileType);
      const isSizeValid = file.size / 1024 / 1024 <= this.fileSize;
      if (!isTypeValid) {//不支持的文件类型
        this.$message.error(`${this.$t(`help.fileType`)}：${fileType}`);
        return false;
      }
      if (!isSizeValid) {//文件大小不能超过
        this.$message.error(`${this.$t(`help.fileSize`)} ${this.fileSize} MB.`);
        return false;
      }

      // if (file.type != "" && file.type != null && file.type != undefined) {
      //   //截取文件的后缀，判断文件类型
      //   const FileExt = file.name.replace(/.+\./, "").toLowerCase();
      //   //计算文件的大小
      //   const isLt2M = file.size / 1024 / 1024 < 20; //这里做文件大小限制
      //   //如果大于50M
      //   if (!isLt2M) {
      //     this.$message.error('上传文件大小不能超过 20MB!');
      //     return false;
      //   }
      //   //如果文件类型不在允许上传的范围内
      //   if (this.fileType.includes(FileExt)) {
      //     return true;
      //   }
      //   else {
      //     this.$message.error("上传文件格式不正确!");
      //     return false;
      //   }
      // }



    },
    handelChange(file, fileList){ //控制显示上传显示列表   
       // 校验文件类型和大小
       const fileType = file.name.slice(file.name.lastIndexOf('.') + 1).toLowerCase();
       const isTypeValid = this.fileType.includes(fileType);
       const isSizeValid = file.size / 1024 / 1024 <= this.fileSize;
       if (!isTypeValid) {//不支持的文件类型
         this.$message.error(`${this.$t(`help.fileType`)}：${fileType}`);
         this.fileList = this.fileList.filter(item => item.name != file.name);
         return false;
       }
       if (!isSizeValid) {//文件大小不能超过
         this.$message.error(`${this.$t(`help.fileSize`)} ${this.fileSize} MB.`);
         this.fileList = this.fileList.filter(item => item.name != file.name);
         return false;
       }
     
      let flag = this.fileList.some(item => item.name == file.name )     
      if (flag){
        this.$message.warning(this.$t(`help.sameName`));
        this.$refs.upload.handleRemove(file)        
        
        return false
      }     
      // this.fileName.push(file.name)    
      this.fileList.push(file.raw)

    },
    //上传了的文件给移除的事件
    handleRemove(file, fileList) {

      let index =  this.fileList.indexOf(file); // 获取第一个重复元素的索引

      if (index !== -1) {
        this.fileList.splice(index, 1); // 删除第一个重复元素
      }


    },
    //超出文件个数的回调
    handleExceed() {
      this.$message({
        type: 'warning',
        message: this.$t(`help.fileNum`)
      }); return
    },
    // //上传文件的事件
    // uploadFile(item) {
    //   // this.filesId.push(item.file.uid)
    //   // //上传文件的需要formdata类型;所以要转
    //   // this.FormDatas = new FormData()
    //   // this.FormDatas.append('file', item.file);
    //   console.log("上传文件");
    //   this.fileList.push(item.file)
    //   // this.fileName.push(item.file.name)
    // },
    //上传成功后的回调
    handleSuccess() {

    },
    handelTime(time) {

      if (time) {
        return `${time.split(`T`)[0]} ${time.split(`T`)[1].split(`.`)[0]}`
      }

    },
    //用户点击结束工单
    handelEndWorkOrder(){
   
      this.fetchEndTicket({id:this.ticketDetails.id})
    }
  


  }
}