import Request from '@/utils/request'
import {
  ElMessage,
  ElLoading
} from 'element-plus'
import router from '../router'
import axios from 'axios'
// 提示内容框换行
// const router = useRouter()
// 项目任务基础数据
export async function getProjectTasks_list(value) {
  let tasksist = []
  await new Request().get('project/data/base_task_data', {
    init_data: value
  }).then(res => {
    if (res.data) {
      res.data.forEach(it => {
        tasksist.push({
          label: it.name,
          value: it.basetask_id
        })
      })
    }
  })
  return tasksist
}
// 日志下拉数据
export async function getProjectLog_list(value) {
  let tasksist = []
  await new Request().get('project/log/type').then(res => {
    if (res.data) {
      tasksist = res.data
    }
  })
  return tasksist
}
// 用户列表
export async function getUsers(userSet) {
  let userdata = []
  /* userSet: { page: 1, size: 5, nickname: '' } */
  await new Request().showLoading(false).get('project/data/user', userSet).then(res => {
    userdata = res.data
  })
  return userdata
}
// 分类列表
export async function getCate(cateSet) {
  let cateArry = []
  await new Request().showLoading(false).get('project/data/cate', cateSet).then(res => {
    cateArry = res.data
  })
  return cateArry
}
// 品牌列表
export async function getBrand() {
  let brandArry = []
  await new Request().showLoading(false).get('project/data/brand').then(res => {
    brandArry = res.data.data
  })
  return brandArry
}
// 项目任务基础数据
export async function getTaskdata() {
  let Taskdata = []
  await new Request().showLoading(false).get('project/data/base_task_data').then(res => {
    Taskdata = res.data
  })
  return Taskdata
}
// 项目资料(弹框)
export async function getProjectfile(data) {
  //data = {project_id:8,title:'',task_id:''}
  let Projectfiledata = []
  await new Request().showLoading(false).get('project/project/file', data).then(res => {
    Projectfiledata = res.data
  })
  return Projectfiledata
}
// 新增编辑项目——保存
export async function handleSaveProject(data, type) {
  if (type !== 'edit') {
    data.id = 0
  }
  await new Request().showLoading(false).post('project/project/edit', data).then(res => {
    if (res.errno == 200) {
      ElMessage({
        type: 'success',
        message: '保存成功'
      })
      if (type == 'add') {
        router.push({
          path: '/lcProject/projectMange/edit',
          query: {
            id: res.data.info.id,
            math: Math.random()
          }
        })
      }
    } else {
      ElMessage({
        type: 'error',
        message: res.errmsg
      })
    }
  })
}
// 公共 - 基础信息 - 输出文件
export function getBaseInfo(ori, rlist) {
  const userlist = []
  getUsers({
    page: 1,
    size: 9999999,
    nickname: ''
  }).then(res => {
    if (res.errno == 200) {
      res.data.forEach(it => {
        userlist.push({
          id: it.id,
          name: it.nickname
        })
      })
    } else {
      ElMessage({
        type: error,
        message: res.errmsg
      })
    }
  })
  let newlist = JSON.parse(JSON.stringify(ori))
  newlist.forEach(el => {
    if (el.label == '任务负责人' || el.label == '任务审核人') {
      el.lsit = userlist
    }
    for (const key in el) {
      if (key == 'field' && rlist[el[key]]) {
        el.value = rlist[el[key]]
      }
    }
  });
  return newlist
}
// 导出 -下载
export function exportlist(sku_ids, project_id, type, exportTag, projectName, selfquery) {
  var loadingInstance = ElLoading.service({
    lock: true,
    text: '此操作需要一段时间请耐心等待！',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
  //导出添加搜索条件拼字段
  var pathtest = ''
  if (!exportTag) {
    // 关于skubom的导出
    pathtest = process.env.VUE_APP_API_BASEURL + apiVersion + '/project/sku/export_bom?sku_ids=' + sku_ids + '&project_id=' + project_id + '&type=' + type
  } else {
    //关于项目列表导出规格定义表
    pathtest = process.env.VUE_APP_API_BASEURL + apiVersion + '/project/project/export_sku?project_ids=' + project_id + (project_id && project_id != '' && project_id != undefined && project_id.split(',').length > 1 ? '&type=zip' : '&type=excel')
  }
  if (!project_id) {
    pathtest = process.env.VUE_APP_API_BASEURL + apiVersion + selfquery.path + '?page=' + selfquery.page + '&type=' + (selfquery.type ? selfquery.type : -1) + '&sku=' + selfquery.sku + '&name=' + selfquery.name + '&cate_id=' + selfquery.cate_id + '&status=' + (selfquery.status ? selfquery.status : -1) + '&ids=' + selfquery.ids
  }
  axios.get(pathtest, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      withCredentials: true
    })
    .then(res => {
      if (res.data.type == 'application/json') {
        const reader = new FileReader();
        reader.readAsText(res.data, 'utf-8');
        reader.onload = function () {
          const msg = JSON.parse(reader.result);
          //reader.result里面含报错信息
          if (msg.errno == 400 || msg.errno == 201) {
            ElMessage({
              type: 'error',
              message: msg.errmsg
            })
          }
        }
      } else {
        const stream = res.data // 后端用stream返回zip文件
        let blob = ''

        if (!exportTag || exportTag == 'sku') {
          if (exportTag == 'sku') {
            blob = (project_id && project_id != '' && project_id != undefined && project_id.split(',').length > 1 ? new Blob([stream], {
              type: "application/zip"
            }) : new Blob([stream]))
          } else {
            blob = new Blob([stream])
          }
        } else {
          blob = new Blob([stream], {
            type: "application/zip"
          })
        }
        // 前端获取业务码，成功执行正常业务
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        if (!exportTag || exportTag == 'sku') {
          const nameStr = (project_id && project_id != '' && project_id != undefined && project_id.split(',').length > 1 ? projectName : decodeURI(escape(JSON.parse(res.headers['content-disposition'].split(';')[1].split('=')[1]))))
          downloadElement.download = nameStr
        } else {
          downloadElement.download = projectName
        }
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象 
      }
      loadingInstance.close()
    })
}
// 导出 -下载
export function exportlistlog(searchdata, projectName) {
  const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
  //导出添加搜索条件拼字段
  var pathtest = ''
  pathtest = process.env.VUE_APP_API_BASEURL + apiVersion + '/project/log/export?keywords=' + searchdata.keywords +
    '&user_name=' + searchdata.user_name + '&type=' + searchdata.type + '&module=' + searchdata.module + '&start_time=' + searchdata.start_time +
    '&end_time=' + searchdata.end_time + '&project_id=' + searchdata.project_id + '&task_id=' + searchdata.task_id
  axios
    .get(pathtest, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      withCredentials: true
    })
    .then(res => {
      if (res.data.type == 'application/json') {
        const reader = new FileReader();
        reader.readAsText(res.data, 'utf-8');
        reader.onload = function () {
          const msg = JSON.parse(reader.result);
          //reader.result里面含报错信息
          if (msg.errno == 400 || msg.errno == 201) {
            ElMessage({
              type: 'error',
              message: msg.errmsg
            })
          }
        }
      } else {
        const stream = res.data // 后端用stream返回zip文件
        const blob = new Blob([stream], {
          type: "application/vnd.ms-excel;charset=utf-8"
        })
        // 前端获取业务码，成功执行正常业务
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = projectName
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象 
      }
    })
}
// 项目资料
export async function xmzldownload(URL, fileName) {
  if (URL) {
    let url = URL
    const a = document.createElement('a')
    a.href = url
    a.download = fileName // 下载后文件名
    a.style.display = 'none'
    document.body.appendChild(a)
    a.click() // 点击下载
    document.body.removeChild(a) // 下载完成移除元素
  }
}
// 下载模板model
export function downloadMod(task_id, fileName) {
  const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
  //导出添加搜索条件拼字段
  var pathtest = ''
  pathtest = process.env.VUE_APP_API_BASEURL + apiVersion + '/project/filetemp/download?task_id=' + task_id
  axios.get(pathtest, {
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json;charset=utf-8'
    },
    withCredentials: true
  }).then(res => {
    if (res.data.type == 'application/json') {
      const reader = new FileReader();
      reader.readAsText(res.data, 'utf-8');
      reader.onload = function () {
        const msg = JSON.parse(reader.result);
        //reader.result里面含报错信息
        if (msg.errno == 400 || msg.errno == 201) {
          ElMessage({
            type: 'error',
            message: msg.errmsg
          })
        }
      }
    } else {
      const stream = res.data // 后端用stream返回zip文件
      let blob = ''
      blob = new Blob([stream], {
        type: "application/zip"
      })
      // 前端获取业务码，成功执行正常业务
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      downloadElement.download = fileName
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象 
    }
  })
}
// 结构和包装bom的跳转查看
export function goBomPage(rowInfo, val) {
  let item = JSON.parse(JSON.stringify(rowInfo))
  if (val == 'links_qd_bom_text') {
    router.push({
      path: '/lcProject/structureBom/index',
      query: {
        id: item.id,
        project_id: item.project_id,
        type: 'structure'
      }
    })
  }
  if (val == 'links_bz_bom_text') {
    router.push({
      path: '/lcProject/structureBom/index',
      query: {
        id: item.id,
        project_id: item.project_id,
        type: 'packing'
      }
    })
  }
}
// 复制
export function copystr(txt) {
  if (txt) {
    var input = document.createElement("input"); // 直接构建input
    input.value = txt; // 设置内容
    document.body.appendChild(input); // 添加临时实例
    input.select(); // 选择实例内容
    document.execCommand("Copy"); // 执行复制
    document.body.removeChild(input); // 删除临时实例
    ElMessage({
      type: 'success',
      message: '已复制'
    })
  }
}
// 公共 - 添加序号
export function addOrderNumber(iArr) {
  if (iArr && iArr.length > 0) {
    let newArr = JSON.parse(JSON.stringify(iArr))
    let num = 1
    newArr.forEach(el => {
      el.index = num++
    });
    return newArr
  }
}

function getBlob(url, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.responseType = "blob";
  xhr.onload = function () {
    if (xhr.status === 200) {
      cb(xhr.response);
    }
  };
  xhr.send();
}

function saveAs(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    var link = document.createElement("a");
    var body = document.querySelector("body");

    link.href = window.URL.createObjectURL(blob);
    link.download = filename;

    // fix Firefox
    link.style.display = "none";
    body.appendChild(link);

    link.click();
    body.removeChild(link);

    window.URL.revokeObjectURL(link.href);
  }
}
export function downloadzl(url, filename) {
  getBlob(url, function (blob) {
    saveAs(blob, filename);
  })
}