import fetch from 'dva/fetch';
import { notification } from 'antd';
import { routerRedux } from 'dva/router';
import axios from 'axios';
import store from 'store';
import querystring from 'querystring';
import store1 from '../index';
import { gup } from './utils';
// import qs from 'qs';
import $loading from './loading';
import { getHostByPath } from './config';
import $modal from '../utils/modal';
// import { data } from '../routes/Command/GIS/SearchListTab/Attendance/TypeData';
// const CancelToken = axios.CancelToken;
notification.config({
  placement: 'topLeft',
  top: 100,
  bottom: 50,
  duration: 3
});

// const pending = [];

// const removePending = config => {
//   for (const p in pending) {
//     if (pending[p].u === config.url + '&' + config.method) {
//       //当当前请求在数组中存在时执行函数体
//       pending[p].f(); //执行取消操作
//       pending.splice(p, 1); //把这条记录从数组中移除
//     }
//   }
// };

const instance = axios.create({
  timeout: 60000,
  headers: {
    Authorization: 'Basic c2Fhc3dlYjp3ZWI=',
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
});
//驻勤考点的token
const access_token = gup('access_token', window.location.href);
if (access_token) {
  const saas = store.get('saas') || {};
  store.set('saas', { ...saas, access_token });
}
const userV5Token = gup('userV5Token', window.location.href);//获取v5 5.0带过来标识符，1代表v5的token

//v5的token
let v5_access_token = gup('v5_access_token', window.location.href);
if (v5_access_token) {
  const saas = store.get('saas') || {};
  store.set('saas', { ...saas, v5_access_token });
}

let timeid;
/* instance.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8"; */

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  notification.error({
    message: `请求错误 ${response.status}: ${response.url}`,
    description: response.statusText
  });
  const error1 = new Error(response.statusText);
  error1.response = response;
  throw error1;
}


/**
 * 需要登录
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */

//  notip 为true的时候不自动提示返回内容
//  noAccessToken 为true的时候不传access_token
export function request(path, options, testUrl, notip, loading = true, noAccessToken = false) {
  let url = path;
  if (url.indexOf('http') == -1) {
    url = (testUrl || getHostByPath()) + path;
  }
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: 'v1.0' });
  }

  if (options && options.data) {
    delete newOptions.body;
    if (store.get('saas') === undefined) {
      const { dispatch } = store1;
      dispatch(routerRedux.push('/user/logOn'));
      // notification.error({
      //   message: "请登录"
      // });
      return Promise.reject('未登录');
    }
    const method = options.method.toLowerCase();
    loading && $loading.open();

    let requestData = {};
    if (Object.prototype.toString.call(options.data).slice(8, -1) == 'FormData') {
      // options.data.append('api', url);
      // options.data.append('v', 'v1.0');
      requestData = options.data;
    } else {
      requestData = querystring.stringify({
        ...options.data
        // , api: url, v: 'v1.0' 
      });
    }

    let headers = options.headers || {};
    if (!noAccessToken) {
      headers = {
        ...headers,
        access_token: store.get('saas')['access_token'],
        userV5Token: userV5Token ? 1 : 0,//1待办v5用户，0待办sass用户
      }
    }
    return instance({
      url,
      method,
      headers,
      params: method === 'get' ? {
        ...options.data
        // , api: url, v: 'v1.0' 
      } : {},
      // data:
      //   method === 'post'
      //     ? requestData
      //     : {}
      data: requestData
    })
      .then(response => {

        loading && $loading.close();
        const { status, data } = response;
        // 返回时间获取到服务器时间，用于时间插件天的管理控制
        data.date = response.headers.date;
        if (data.retType === '1') {
          store.remove();
          //防止重复提示
          clearTimeout(timeid);
          timeid = window.setTimeout(() => {
            if (!notip) {
              notification.error({
                message: data.msg
              });
            }
          }, 500);

          const { dispatch } = store1;
          store.clearAll();
          dispatch(routerRedux.push('/user/logOn'));
          return Promise.reject(data);
        }
        if (status !== 200 || data.retType !== '0') {
          if (!notip) {
            notification.error({
              message: data.msg
            });
          }
          return Promise.reject(data);
        }
        if (method === 'post' && data.msg) {
          if (!notip) {
            notification.success({
              message: data.msg
            });
          }
        }
        let newData1;
        try {
          newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
        } catch (err) {
          newData1 = data;
        }
        return newData1;
      })
      .catch(err => {
        loading && $loading.close();
        if (err.toString().indexOf('Network') !== -1) {
          notification.error({
            message: '网络出错了'
          });
          const { dispatch } = store1;
          // dispatch(routerRedux.push('/user/logOn'));
        }
        return Promise.reject(err);
      });
  } else {
    return fetch(url, {
      ...newOptions
      // , api: url, v: 'v1.0' 
    })
      .then(checkStatus)
      .then(response => {
        loading && $loading.close();
        return response.json()
      })
      .catch(error => {
        loading && $loading.close();
        if (error.code) {
          notification.error({
            message: error.name,
            description: error.message
          });
        }
        if ('stack' in error && 'message' in error) {
          notification.error({
            message: `请求错误: ${url}`,
            description: error.message
          });
        }
        return error;
      });
  }
}

/* 不需要登录 */
export function noLoginRequest(path, options, testUrl) {
  const url = testUrl || getHostByPath() + path;
  // const url = getHostByPath(path) + path;
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
    newOptions.body = JSON.stringify({ ...newOptions.body, v: 'v1.0' });
    // newOptions.body = {...newOptions.body, v: "v1.0"};
  }

  const method = options.method.toLowerCase();
  return axios({
    url,
    method,
    params: method === 'get' ? {
      ...options.data
      // , api: url, v: 'v1.0'
    } : {},
    data:
      method === 'post'
        ? querystring.stringify({
          ...options.data
          // , api: url, v: 'v1.0'
        })
        : {}
  })
    .then(response => {
      const { status, data } = response;
      // 返回时间获取到服务器时间，用于时间插件的管理控制
      data.date = response.headers.date;
      if (data.retType === '1') {
        notification.error({
          message: data.msg
        });
        const { dispatch } = store1;
        dispatch(routerRedux.push('/user/logOn'));
        return Promise.reject(data);
      }
      if (status !== 200 || data.retType !== '0') {
        notification.error({
          message: data.msg
        });
        return Promise.reject(data);
      }
      if (method === 'post' && data.msg) {
        notification.success({
          message: data.msg
        });
      }

      let newData1;
      try {
        newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
      } catch (err) {
        newData1 = data;
      }

      return newData1;
    })
    .catch(err => {
      console.log(err, 'err');
      if (err.toString().indexOf('Network') !== -1) {
        // notification.error({
        //   message: "网络出错了"
        // });
        const { dispatch } = store1;
        dispatch({ type: 'global/netError' });
      }
      return Promise.reject(err);
    });
}

/* 登录请求
注意：本应该是post请求提交的参数确要用get提交参数后期要后端整改
---------------------------------------------------*/
export function loginRequest(path, options, testUrl) {
  const url = testUrl || getHostByPath() + path;
  // const url = getHostByPath(path) + path;
  return instance
    .post(url, {
      ...options.data,
      // api: url,
      // v: 'v1.0',
      grant_type: 'password'
    })
    .then(response => {
      const { status, data } = response;
      if (status === 200 && data.retType === '0') {
        store.set('saas', {
          access_token: data.data.access_token,
          sessionId: encodeURIComponent(data.data.sessionId), //嵌入百课堂和百保盾页面，直接使用接口数据，iframe不用拼接
          thirdSessionId: data.data.thirdSessionId,  //薪酬管理页面
        });
      } else {
        notification.error({
          message: data.msg
        });
      }
      return data;
    })
    .catch(err => {
      if (err.toString().indexOf('Network') !== -1) {
        notification.error({
          message: '网络出错了'
        });
      }
      return { status: 600, data: { retType: '-1' } };
    });
}

/**
 * v5的公共服务的测试环境
 */
export function v5comRequest(path, options, notip, loading = true) {
  let url = path;
  if (url.indexOf('http') == -1) {
    url = getHostByPath('v5common') + path;
  }
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
  }

  if (options && options.data) {
    const method = options.method.toLowerCase();
    loading && $loading.open();

    let requestData = {};
    if (Object.prototype.toString.call(options.data).slice(8, -1) == 'FormData') {
      requestData = options.data;
    } else {
      requestData = querystring.stringify({
        ...options.data
      });
    }

    let headers = options.headers || {};
    return instance({
      url,
      method,
      headers,
      params: method === 'get' ? {
        ...options.data
      } : {},
      data: requestData
    })
      .then(response => {

        loading && $loading.close();
        const { status, data } = response;
        // 返回时间获取到服务器时间，用于时间插件天的管理控制
        if (data.retType === '1') {
          store.remove();
          //防止重复提示
          clearTimeout(timeid);
          timeid = window.setTimeout(() => {
            if (!notip) {
              notification.error({
                message: data.msg
              });
            }
          }, 500);

          store.clearAll();
          return Promise.reject(data);
        }
        if (status !== 200 || data.retType !== '0') {
          if (!notip) {
            notification.error({
              message: data.msg
            });
          }
          return Promise.reject(data);
        }
        if (method === 'post' && data.msg) {
          if (!notip) {
            notification.success({
              message: data.msg
            });
          }
        }
        let newData1;
        try {
          newData1 = JSON.parse(JSON.stringify(data).replace(/null/g, '""'));
        } catch (err) {
          newData1 = data;
        }
        return newData1;
      })
      .catch(err => {
        loading && $loading.close();
        if (err.toString().indexOf('Network') !== -1) {
          notification.error({
            message: '网络出错了'
          });
        }
        return Promise.reject(err);
      });
  } else {
    return fetch(url, {
      ...newOptions
    })
      .then(checkStatus)
      .then(response => {
        loading && $loading.close();
        return response.json()
      })
      .catch(error => {
        loading && $loading.close();
        if (error.code) {
          notification.error({
            message: error.name,
            description: error.message
          });
        }
        if ('stack' in error && 'message' in error) {
          notification.error({
            message: `请求错误: ${url}`,
            description: error.message
          });
        }
        return error;
      });
  }
}

/**
 * v5的数据接口
 */
export function v5baseRequest(path, options, notip, loading = true) {
  let url = path;
  if (url.indexOf('http') == -1) {
    url = getHostByPath('v5base') + path;
  }
  if (options.urlData) {
    for (var i in options.urlData) {
      if (url.indexOf("?") > -1) {
        url += "&" + i + '=' + options.urlData[i]
      } else {
        url += "?" + i + '=' + options.urlData[i]
      }
    }
  }
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
    // newOptions.body = JSON.stringify({ ...newOptions.body, v: 'v1.0' });
  }
  // const prefix = window.location.hostname.split('.')[0]; 
  //本地自己调试的
  // if(prefix=='localhost'){
  //   v5_access_token='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsImV4cCI6MTYyMzMwNTAxOCwidXNlcm5hbWUiOiJfXzVuaHhDdVVlRXd2bmtBaG1EUlUifQ.hv0NcXKXyDUyMFlww77rmXggLICGqWJdBVTrHaSlGzg'
  // }
  if (!v5_access_token) {
    //链接中没有给token
    notification.error({
      message: '请检查参数'
    });
  }
  // if (options && options.data) {
  // delete newOptions.body;
  // if (store.get('saas') === undefined) {
  //   const { dispatch } = store1;
  //   dispatch(routerRedux.push('/user/logOn'));
  //   // notification.error({
  //   //   message: "请登录"
  //   // });
  //   return Promise.reject('未登录');
  // }
  const method = options.method.toLowerCase();
  loading && $loading.open();

  return instance({
    url,
    data: options.data || {},
    method: method,
    headers: {
      accessToken: v5_access_token,
      ...options.headers,
      'Content-Type': 'application/json;charset=UTF-8'
    },
  })
    .then(response => {
      loading && $loading.close();
      const { status, data } = response;
      let result
      let newData
      if(Array.isArray(data)){
        return Promise.resolve(data)
      }
      if(data.type==0){
        return Promise.resolve({data:data.data})
      }
      if (data.data) {
        if (data.data.data) {
          let resData = data.data.data
          result = resData.map((item) => {
            let detail = {};
            let { items } = item;
            for (let key in resData[0].items) {
              if (items[key].name) {
                detail[items[key].name] = items[key].value;
              } else if (items[key].columnName) {
                detail[items[key].columnName] = items[key].value;
              }
            }
            return {
              id: item.id,
              formId: item.formId,
              ...detail,
            };
          })
          newData = {
            data: {
              data: result,
              pageNumber: data.data.page,//当前第几页
              pageSize: data.data.page_lines,//每页大小
              total: data.data.row_count,//总条数
              // totalPage:data.data.row_count/data.data.page_lines///总页数
            }
          }
        } else if (data.data.datas) {
          result = data.data.datas
          newData = {
            data: {
              data: result,
            }
          }
        } else if (data.data) {
          if (!data.data.msg) {
            result = data.data
            newData = data
          } else {
            notification.error({
              message: data.data.msg
            });
            Promise.reject(data.data.msg)
          }
        }
        return Promise.resolve(newData)
      } else {
        return Promise.reject()
      }
    })
    .catch(err => {
      console.log(err)
      loading && $loading.close();
      if (err) {
        if (err.response && err.response.status === 401) {
          $modal(
            <span style={{ color: 'orange' }}>因您长时间未操作，请重新登录企业后台重新进入</span>,
            '',
            [],
          );
        }
        if (err.toString().indexOf('Network') !== -1) {
          notification.error({
            message: '网络出错了'
          });
          // const { dispatch } = store1;
          // dispatch(routerRedux.push('/user/logOn'));
        }
      }
      return Promise.reject(err);
    });
}

/**
 * v5后台的数据接口
 */
export function v5adminRequest(path, options, notip, loading = true) {
  let url = path;
  if (url.indexOf('http') == -1) {
    url = getHostByPath('v5base') + path;
  }
  if (options.urlData) {
    for (var i in options.urlData) {
      if (url.indexOf("?") > -1) {
        url += "&" + i + '=' + options.urlData[i]
      } else {
        url += "?" + i + '=' + options.urlData[i]
      }
    }
  }
  const defaultOptions = {
    credentials: 'include'
  };
  const newOptions = {
    ...defaultOptions,
    ...options
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      ...newOptions.headers
    };
  }
  const method = options.method.toLowerCase();
  loading && $loading.open();
  let time = new Date().getTime()
  return instance({
    url,
    data: options.data || {},
    method: method,
    headers: {
      "x-g-app-token": "02C524E758DDC1C4F041F0A5953AB7803ACF01A6BEA5B4E50A2239979AA3FB409FFF0353A0E9CDA37DA4DEE3E1CBD066960EC8EE91B577A16D6B6D67A16CF300",
      "x-g-app-time": time,
      'Content-Type': 'application/json;charset=UTF-8'
    },
  })
    .then(response => {
      loading && $loading.close();
      const { status, data } = response;
      let result
      let newData
      if (data.data) {
        if (data.data.data) {
          let resData = data.data.data
          result = resData.map((item) => {
            let detail = {};
            let { items } = item;
            for (let key in resData[0].items) {
              if (items[key].name) {
                detail[items[key].name] = items[key].value;
              } else if (items[key].columnName) {
                detail[items[key].columnName] = items[key].value;
              }
            }
            return {
              id: item.id,
              formId: item.formId,
              ...detail,
            };
          })
          newData = {
            data: {
              data: result,
              pageNumber: data.data.page,//当前第几页
              pageSize: data.data.page_lines,//每页大小
              total: data.data.row_count,//总条数
              // totalPage:data.data.row_count/data.data.page_lines///总页数
            }
          }
        } else if (data.data.datas) {
          result = data.data.datas
          newData = {
            data: {
              data: result,
            }
          }
        } else if (data.data) {
          if (!data.data.msg) {
            result = data.data
            newData = data
          } else {
            notification.error({
              message: data.data.msg
            });
            Promise.reject(data.data.msg)
          }
        }
        return Promise.resolve(newData)
      } else {
        return Promise.reject()
      }
    })
    .catch(err => {
      console.log(err)
      loading && $loading.close();
      if (err) {
        if (err.response && err.response.status === 401) {
          $modal(
            <span style={{ color: 'orange' }}>因您长时间未操作，请重新登录企业后台重新进入</span>,
            '',
            [],
          );
        }
        if (err.toString().indexOf('Network') !== -1) {
          notification.error({
            message: '网络出错了'
          });
          // const { dispatch } = store1;
          // dispatch(routerRedux.push('/user/logOn'));
        }
      }
      return Promise.reject(err);
    });
}

//文件导出下载
export function saasDownloadBlob(url, params = {}) {
  url = url.replace(/^\//, '');
  let queryStr = '';
  Object.keys(params).forEach(key => {
    queryStr += `${key}=${params[key]}&`;
  });
  queryStr = queryStr.slice(0, -1);
  return axios({
    method: 'get',
    url:
      `${getHostByPath()}/${url}?${queryStr}`, //后台请求地址
    responseType: 'blob',
    headers: {
      access_token: store.get('saas')['access_token']
    }
  });
}