import { mapState } from "vuex";
import { getQuestionType, getSubmitTicket, getPrivateTicket } 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: "",
        desc: "",
        type: "",
        files: ""
      },
      kindsList: [{
        id: "购买咨询",
        type: "购买咨询",
      }, {
        id: "财务咨询",
        type: "财务咨询",
      }, {
        id: "网页问题",
        type: "网页问题",
      },
      {
        id: "账户问题",
        type: "账户问题",
      },
      {
        id: "移动端问题",
        type: "移动端问题",
      },
      {
        id: "消息订阅",
        type: "消息订阅",
      },
      {
        id: "指标数据问题",
        type: "指标数据问题",
      },
      {
        id: "其他",
        type: "其他",
      }],
      tableData: [{
        id: 1,
        time: "2022-09-01 16:00",
        type: "账户问题",
        title: "账户不能登录",
        status: "已解决",
        userName: "",//用户名
        date: "",//提交时间戳

      }],
      //上传后的文件列表
      fileList: [],
      // 允许的文件类型
      fileType: ["rar", "doc", "txt", "png", "jpg", "jpeg",],
      // 运行上传文件大小，单位 M
      fileSize: 20,
      // 附件数量限制
      fileLimit: 3,
      //请求头
      headers: { "Content-Type": "multipart/form-data" },
      FormDatas: null,
      helpDialogVisible: false,
      fileName: [],
      filesId: [],
      statusList: [{
        value: "4",
        label: "已处理",
      }, {
        value: "5",
        label: "已回复",
      }, {
        value: "2",
        label: "撤回",
      }, {
        value: "3",
        label: "正在处理/待处理",
      }, {
        value: "7",
        label: "超时",
      }, {
        value: "8",
        label: "待审核",
      }, {
        value: "11",
        label: "审核完成",
      },],
      fileItem: "",
      uploadedFiles: [],
      inputLimit:160,



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

    this.userName = localStorage.getItem("username")
    window.addEventListener("setItem", () => {
      this.userName = localStorage.getItem("username")
      this.filesId = []
    })

  },
  methods: {

    //获取问题分类
    async fetchQuestionType() {
      const { data } = await getQuestionType()
      this.kindsList = data.data
    },
    //请求提交工单
    async fetchSubmitTicket(data) {
      const list = await getSubmitTicket(data)
   
      if (list.data.code == 200) {
        this.$message({
          message: list.data.msg,
          type: "success",
          customClass: "messageClass",
        });
        //清空数据
        for (const key in this.from) {
          this.from[key] = ""
        }

        this.fetchPrivateTicket()//刷新历史工单
        this.fileList = []//上传成功清空附件


      }

    },
    //请求个人工单列表（历史）
    async fetchPrivateTicket(data) {
      const list = await getPrivateTicket(data)
      this.tableData = list.data.data
      this.tableData.forEach(item => {
        item.date = `${item.date.split(`T`)[0]} ${item.date.split(`T`)[1].split(`.`)[0]}`
      })
      // console.log(list, "请求个人工单列表（历史）");
    },

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

    },
    //点击历史工单详情 "/WorkOrderDetails"
    handelDetails(row) {//跳转时将该行参数带过去     
      this.$addStorageEvent(1, "detailsID", row.id);
      this.$router.push({
        path: "/WorkOrderDetails",
        name: "WorkOrderDetails",
        params: row
      })


    },
    //上传文件之前
    beforeUpload(file) {
      // 校验文件类型和大小
      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;
      }

    },
    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 )     
      console.log();
      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)
      console.log( this.fileName,"name" ,this.fileList);
    },

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

      let nameIndex = this.fileName.indexOf(file.name); // 获取第一个重复元素的索引
      if (nameIndex !== -1) {
        this.fileName.splice(nameIndex, 1); // 删除第一个重复元素
      }




      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.fileItem = item   
     
      this.fileList.push(item.file);
      this.fileName.push(item.file.name)
  
    },
    //上传成功后的回调
    handleSuccess() {

    },
    //点击提交按钮
    handelSubmit() {

      for (const key in this.from) { //判空
        if (key !== `files` && this.from[key] == "") {
          switch (key) {
            case "title":
                this.$message({
                message: this.$t(`help.problemTitle1`),
                type: "error",
              });
              break;
         
            case "type":
              this.$message({
                message: this.$t(`help.problem2`),
                type: "error",
              });
              break;
              case "desc":
                this.$message({
                  message: this.$t(`help.describe`),
                  type: "error",
                });
                break;
            default:
              break;
          }
    
          return
        }
      }
      
      this.helpDialogVisible = true

    },
    //点击弹窗确认提交按钮
    handelConfirm() {

      if (this.fileList[0]) { //附件有值就走上传附件成功 提交工单
      
        //上传文件的需要formdata类型;所以要转
        this.FormDatas = new FormData()
        this.fileList.forEach(fileItem => {
        
          this.FormDatas.append('file', fileItem);

         
        })

        console.log(this.FormDatas,"文件");
        // 上传选择附件     
        this.$axios({
          method: 'post',
          url: 'marketall/ticket/uploadFile',
          headers: this.headers,
          timeout: 30000,
          data: this.FormDatas
        }).then(res => {
          console.log(res,"上传附件");
          this.from.files = res.data.data.id

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

        })


      } else {

        this.fetchSubmitTicket(this.from) //没有附件提交工单
      }











      // this.fetchSubmitTicket(this.from)
      this.helpDialogVisible = false
    },
    //处理时间格式
    handelTime(date) {
      return `${date.split(`T`)[0]} ${date.split(`T`)[1].split(`.`)[0]}`
    },
    //选择问题种类
    handelType(id) {

      if (id) {
        return this.kindsList.find(item => item.id == id).type
      }

    },
    
















  }
}