import { mapState } from "vuex";
import axios from 'axios'
import { getTicketDetails, getDownloadFile, getResponTicket, getAuditTicket, getSubmitAuditTicket } from "../../api/help"
export default {
  data() {
    return {
      helpDetailsLoading: 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: [],
      input: 1,
      tableData: [{
        num: 1,
        time: "2022-09-01 16:00",
        problem: "账户问题",
        questionTitle: "账户不能登录",
        state: "已解决"
      }],
      textarea: "我是提交内容",
      textarea1: "我是回复内容",
      textarea2: "",
      replyInput: true,
      ticketDetails: {
        id: "",
        type: "",
        title: "",
        userName: "",
        desc: "",
        responName: "",
        respon: "",
        submitTime: "",
        status: "",
        fileIds: "",
        files: "",
        responTime: ""

      },
      //上传后的文件列表
      fileList: [],
      // 允许的文件类型
      fileType: ["rar", "doc", "txt", "png", "jpg", "jpeg",],
      // 运行上传文件大小，单位 M
      fileSize: 20,
      // 附件数量限制
      fileLimit: 3,
      //请求头
      headers: { "Content-Type": "multipart/form-data" },
      FormDatas: null,
      filesId: [],
      paramsDownload: {
        id: ""
      },
      //回复工单参数
      paramsResponTicket: {
        id: "",
        files: "",
        respon: "",

      },
      //审核工单参数
      paramsAuditTicket: {
        id: "",
        msg: ""
      },
      //提交审核参数
      paramsSubmitAuditTicket: {
        id: ""
      },
      identity: {},
      detailsID: "",
      auditList: {},//审核信息
      downloadUrl:""




    }
  },
  computed: {
    ...mapState({
      current: (state) => state.tab.currentMenu,
    }),
  },
  mounted() {


    if (localStorage.getItem("identity")) {
      this.identity = JSON.parse(localStorage.getItem("identity"));
    }
   
    this.detailsID = localStorage.getItem("detailsID")
    window.addEventListener("setItem", () => {
      if (localStorage.getItem("identity")) {
        this.identity = JSON.parse(localStorage.getItem("identity"));
      }
      this.detailsID = localStorage.getItem("detailsID")
    });

    this.fetchTicketDetails({ id: this.detailsID })
  },
  methods: {
    //请求工单详情
    async fetchTicketDetails(data) {
      // this.helpDetailsLoading =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
      console.log(this.ticketDetails,6666);
      this.ticketDetails.submitTime = `${this.ticketDetails.submitTime.split("T")[0]} ${this.ticketDetails.submitTime.split("T")[1].split(".")[0]}`
      this.helpDetailsLoading = false
    },
    //请求文件下载
    async fetchDownloadFile(ids) {
      // const list = await getDownloadFile(data)
      const list = await this.$API.getDownloadFile(ids)
      this.$message({
        message: list.data.msg,
        type: "warning",
        customClass: "messageClass",
      });

    },
    //请求回复工单
    async fetchResponTicket(data) {
      const list = await getResponTicket(data)
    
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });
        for (const key in this.paramsResponTicket) {//清空工单
          this.paramsResponTicket[key] = ""
        }
        //回复成功刷新工单
        this.fetchTicketDetails({  id: this.detailsID })
        this.fileList =[] // 清空已上传列表
      }



    },
    //请求审核人员审核工单
    async fetchAuditTicket(data) {
      const list = await getAuditTicket(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()//回到上一级页面 


      }



    },
    //请求提交审核
    async fetchSubmitAuditTicket(data) {
      // this.helpDetailsLoading =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.$router.push(`/HelpBackstage`)
     

      }
      this.helpDetailsLoading = false

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

    },
    //点击编辑回复内容
    handelEdit() {
      //输入框可编辑
      this.replyInput = false
    },
    //点击下载附件
    downloadExcel(id) {
      
      this.downloadUrl = ` ${axios.defaults.baseURL}/marketall/ticket/downloadFile?ids=${id}`
      let a= document.createElement(`a`)
      a.href =  this.downloadUrl
      a.click()




      // this.paramsDownload.id = id

      // this.fetchDownloadFile(id)
    
    },
    //点击提交回复按钮
    handelResponTicket() {
      if (!this.paramsResponTicket.respon) {//判空
        this.$message({
          message: this.$t(`help.resubmit`),
          type: "error",
        });
        return
      }
      this.paramsResponTicket.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.paramsResponTicket.files = res.data.data.id
             
            if (this.paramsResponTicket.files) {//成功拿到返回ID
              this.fetchResponTicket(this.paramsResponTicket) //提交工单
            }
        })
      } else {
        this.fetchResponTicket(this.paramsResponTicket)
      }









    },
    //点击请求审核按钮
    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)


    },
    //审核人员 点击审核按钮
    handelAuditTicket() {
      if (!this.paramsAuditTicket.msg) {//判空
        this.$message({
          message: this.$t(`help.resubmit`),
          type: "error",
        });
        return
      }
      this.paramsAuditTicket.id = this.ticketDetails.id
      this.fetchAuditTicket(this.paramsAuditTicket)

    },




    //上传文件之前
    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) {
     // this.fileList = this.fileList.filter(item => item.name !== file.name)
      // this.fileName = this.fileName.filter(item => item !== file.name)
      
      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
    },
  
    //上传成功后的回调
    handleSuccess() {

    },

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

    },
  }
}