/**
 * 通用工具类
 */
import {param as configparam} from "../option/config";
import * as report from "@/api/report/report";
export default class func {
  /**
   * 不为空
   * @param val
   * @returns {boolean}
   */
  static notEmpty(val) {
    return !this.isEmpty(val);
  }
  static onJsClea(apiJsFunction,originJson){
    try {
      let handle = eval(`(${apiJsFunction})`);
      return handle(originJson);

    } catch (e) {
      this.$message.warning("请检查语法");
    }
  }
  /**
   * 是否为定义
   * @param val
   * @returns {boolean}
   */
  static isUndefined(val) {
    return val === null || typeof val === 'undefined';
  }
  static hasPercent(str){
    var reg=/%+/;
    if(reg.test(str)){
      return true
    }else{
      return false
    }
  }
  /**
   * 为空
   * @param val
   * @returns {boolean}
   */
  static isEmpty(val) {
    if (
      val === null ||
      typeof val === 'undefined' ||
      (typeof val === 'string' && val === '' && val !== 'undefined')
    ) {
      return true;
    }
    return false;
  }

  /**
   * 强转int型
   * @param val
   * @param defaultValue
   * @returns {number}
   */
  static toInt(val, defaultValue) {
    if (this.isEmpty(val)) {
      return defaultValue === undefined ? -1 : defaultValue;
    }
    const num = parseInt(val, 0);
    return Number.isNaN(num) ? (defaultValue === undefined ? -1 : defaultValue) : num;
  }

  /**
   * Json强转为Form类型
   * @param obj
   * @returns {FormData}
   */
  static toFormData(obj) {
    const data = new FormData();
    Object.keys(obj).forEach(key => {
      data.append(key, Array.isArray(obj[key]) ? obj[key].join(',') : obj[key]);
    });
    return data;
  }

  /**
   * date类转为字符串格式
   * @param date
   * @param format
   * @returns {null}
   */
  static format(date, format = 'YYYY-MM-DD HH:mm:ss') {
    return date ? date.format(format) : null;
  }

  /**
   * 根据逗号联合
   * @param arr
   * @returns {string}
   */
  static join(arr) {
    return arr ? arr.join(',') : '';
  }

  /**
   * 根据逗号分隔
   * @param str
   * @returns {string}
   */
  static split(str) {
    return str ? String(str).split(',') : '';
  }

  /**
   * 根据逗号分隔
   * @param str
   * @returns {string}
   */
  static dataQuerydoing(activeObj) {
    console.log(activeObj)
    let param = {
      'componentId':activeObj.index,
      'dataSourceId':activeObj.tableid,
      'filterConditions':[],
      'groupBys':[],
      'limit':[],
      'orderBys':[],
      'selectTargets':[],
    };
    return param;
  }


  static onFieldAdd(field) {
    console.log(field)
    if (field.select) return;
    let activeKey = Object.keys(this.fieldSet).find((k) => this.fieldSet[k]);
    if (!activeKey) return;
    let set = this.modalSet.find((i) => i.key == activeKey);
    if (set && this.config[activeKey].length >= set.length) return;
    let nowField = { ...field };
    nowField.cubeColumnId = field.id;
    delete nowField.id;
    if (activeKey === "filter") {
      nowField.connectTime = "where"; // 过滤时机 where having
      nowField.connectType = "and"; // 连接方式 or and
      nowField.conditions = [{ function: "eq", values: ["", ""] }]; // 条件列表
      nowField.asFilter = true;
      nowField.options = []; // 枚举值列表
      if (nowField.viewDataType === "DATETIME") {
        nowField.dateType = this.dateTypeMap[field.timeDataFormat];
        nowField.dateFormat = this.fieldDateFormats.find(
          (i) => i.value === field.timeDataFormat
        ).label;
      }
    } else {
      field.select = true;
    }
    if (activeKey == "sort") {
      nowField.cubeColumnId = field.cubeColumnId;
      nowField.orderType = "ASC";
    }
    this.config[activeKey].push(nowField);
  }

  static async weekk(date) {
    let weekOfDay = moment(date).format("E") // 指定日期的周的第几天
    let lastMonday = moment(date).subtract(weekOfDay-1, 'days').format('YYYYMMDD');//周一日期
    let lastSunday = moment(date).add(7-weekOfDay, 'days').format('YYYYMMDD');//周日日期
    let data = await report.openurl('weekweek', {STARTDAY:lastMonday,ENDDAY:lastSunday})
    return data.data.data[0]
  }

  static parammonth(paramsList,form,param,commonParam,options) {
    paramsList = paramsList.filter(function(item){
      if (item.screeningtype){
        return item;
      }
    });
    var sql = ''
    XEUtils.arrayEach(paramsList, (item) => {
      if (item.screeningtype){
        var month = XEUtils.locat().hashQuery.month
        if (item.screeningtype == 'DatePicker' && XEUtils.isEmpty(form[item.columnName])) {
          if (item.screeningsetting == 'month') {
            if (item.commonDateTime){
              if(XEUtils.startsWith(item.commonDateTime , '+')){
                if (item.commonDateTime == '+1'){
                  param.endTime = moment().format('YYYYMM')
                }else{
                  param.endTime = moment().add(item.commonDateTime, 'months').format('YYYYMM')
                }
              }
            }
            sql += ` ${item.columnName} = ${param.endTime} AND`
          } else if (item.screeningsetting == 'date') {
            if (item.commonDateTime){
              commonParam.day.last30 = moment(month).subtract('days', item.commonDateTime).format('YYYYMMDD')
            }
            sql += ` ${item.columnName} = ${commonParam.day.last30} AND`
          } else if (item.screeningsetting == 'quarter') {
            sql += ` ${item.columnName} = ${param.quarter} AND`
          } else if (item.screeningsetting == 'daterange') {
            if (item.commonDateTime){
              commonParam.day.last30 = moment(month).subtract('days', item.commonDateTime).format('YYYYMMDD')
            }
            if (item.commonDateEndTime){
              commonParam.day.today = moment(month).add('days', item.commonDateEndTime).format('YYYYMMDD')
            }
            sql += ` ${item.columnName} >= ${commonParam.day.last30} AND ${item.columnName} <= ${commonParam.day.today} AND`
          }else if (item.screeningsetting == 'week') {
            sql += ` ${item.columnName} = ${param.week} AND`
          } else {
            let startTime = param.startTime;
            if (item.commonDateTime){
              startTime = moment(param.endTime).subtract(item.commonDateTime, 'months').format('YYYYMM')
            }
            sql += ` ${item.columnName} >= ${startTime} AND ${item.columnName} <= ${param.endTime} AND`
          }
        }
        if (item.screeningtype == 'commonDate' && XEUtils.isEmpty(form[item.columnName])) {
          if (!commonParam.datetimeChange) {
            if(!XEUtils.isUndefined(month)){
              commonParam.date.startTime = moment(month).add(-12, 'months').format('YYYYMM')
              commonParam.date.endTime = moment(month).format('YYYYMM')
              commonParam.day.today = moment(month).endOf('month').format("YYYYMMDD");
              commonParam.day.last30 = moment(month).startOf("month").format("YYYYMMDD");
            } else {
              month = moment(month).format('YYYY-MM-DD');
            }
            if (item.commonDateDefault == 1){
              if (item.commonDateTime){
                if(XEUtils.startsWith(item.commonDateTime , '+')){
                  if (item.commonDateTime == '+1'){
                    commonParam.date.endTime = moment(month).format('YYYYMM')
                  }else{
                    commonParam.date.endTime = moment(month).add(item.commonDateTime, 'months').format('YYYYMM')
                  }
                }else{
                  commonParam.date.endTime = moment(month).subtract(item.commonDateTime, 'months').format('YYYYMM')
                }
              }
              if(moment().startOf('month').format("D") == moment().format('D') && item.commonDateTime == 0){
                commonParam.date.endTime = moment().subtract(1, 'months').format('YYYYMM')
              }
              sql += ` DTYPE = '${commonParam.date.type}' AND THEDVALUE >= ${commonParam.date.endTime} AND THEDVALUE <= ${commonParam.date.endTime} AND`
            } else if (item.commonDateDefault == 2){
              if (item.commonDateTime){
                commonParam.day.last30 = moment(month).subtract('days', item.commonDateTime).format('YYYYMMDD')
              }
              sql += ` DTYPE = 'DAY' AND THEDVALUE >= ${commonParam.day.last30} AND THEDVALUE <= ${commonParam.day.today} AND`
            } else if (item.commonDateDefault == 3){
              sql += ` DTYPE = 'QUARTER' AND THEDVALUE >= ${param.quarter} AND THEDVALUE <= ${param.quarter} AND`
            }else{
              if (item.commonDateTime){
                  commonParam.date.startTime = moment(month).add(-item.commonDateTime, 'months').format('YYYYMM')
              }
              if (item.commonDateTimeRadio && item.commonDateTimeRadio == 1){
                commonParam.date.endTime = moment(month).format('YYYYMM')
              }else{
                commonParam.date.endTime = configparam.endTime
              }
              sql += ` DTYPE = '${commonParam.date.type}' AND THEDVALUE >= ${commonParam.date.startTime} AND THEDVALUE <= ${commonParam.date.endTime} AND`
            }
          } else {
            if (commonParam.day.length > 0 && item.commonDateDefault == 2){
              sql += ` DTYPE = 'DAY' AND THEDVALUE >= ${commonParam.day.last30} AND THEDVALUE <= ${commonParam.day.today} AND`
            }else{
              sql += ` DTYPE = '${commonParam.date.type}' AND THEDVALUE >= ${commonParam.date.startTime} AND THEDVALUE <= ${commonParam.date.endTime} AND`
            }
          }
        }
        if (item.screeningtype == 'area' && XEUtils.isEmpty(form[item.columnName])) {
          if (XEUtils.has(commonParam, 'AREA') && commonParam.AREA.length > 0){
            let join = ` ${item.columnName} in (`
            XEUtils.arrayEach(commonParam.AREA, (itemmm) => {
              join += `'${itemmm}',`
            })
            join = join.substr(0, join.length - 1)
            sql += ` ${join}) AND`
          }else if(item.areadefault && item.areadefault.length > 0){
            let join = ` ${item.columnName} in (`
            XEUtils.arrayEach(item.areadefault, (itemmm) => {
              join += `'${itemmm}',`
            })
            join = join.substr(0, join.length - 1)
            sql += ` ${join}) AND`
          }
        }
        if (item.screeningtype == 'important_prod' && XEUtils.isEmpty(form[item.columnName])) {
          if (item.important_proddefault.length > 0) {
            let join = ` SPID in (`
            XEUtils.arrayEach(item.important_proddefault, (itemmm) => {
              join += `'${itemmm}',`
            })
            join = join.substr(0, join.length - 1)
            sql += ` ${join}) AND`
          }
        }
        if (item.screeningtype == 'input' && item.inputfault && XEUtils.isEmpty(form[item.columnName])) {
          sql += ` ${item.columnName} like '%${item.inputfault}%' AND`
        }
        if (item.screeningtype == 'income' && item.incomedefault && XEUtils.isEmpty(form[item.columnName])) {
          sql += ` ${item.columnName} = '${item.incomedefault}' AND`
        }
        if (item.screeningtype == 'select' && item.selectdefault && XEUtils.isEmpty(form[item.columnName])) {
          if (item.screeningsetting == 1){
            sql += ` ${item.columnName} = '${item.selectdefault}' AND`
          } else if(item.selectdefault.length > 0){
            let join = ` ${item.columnName} in (`
            XEUtils.arrayEach(item.selectdefault, (itemmm) => {
              join += `'${itemmm}',`
            })
            join = join.substr(0, join.length - 1)
            sql += ` ${join}) AND`
          }
        }
        if (item.catdefault && item.screeningtype == 'cat' && XEUtils.isEmpty(form[item.columnName]) && item.catdefault.length > 0) {
          var itemdefault = item.catdefault
          if (commonParam.CATEGORYNAME) {
            form[item.columnName] = commonParam.CATEGORYNAME
            itemdefault = commonParam.CATEGORYNAME
          } else {
            form[item.columnName] = item.catdefault
          }
          var categoryname = '', cpid = '', spid = '', oldcategoryname
          XEUtils.arrayEach(itemdefault, (itemmm) => {
            if (itemmm.length == 1) {
              var it = XEUtils.findTree(options, item => item.CID === itemmm[0])
              if (it && oldcategoryname != it.item.CNAME) {
                categoryname += `'${it.item.CNAME}',`
              }
              oldcategoryname = it && it.item  ?  it.item.CNAME : '';
            }
            if (itemmm.length == 3) {
              spid += `'${itemmm[2]}',`
            } else if (itemmm.length == 2) {
              cpid += `'${itemmm[1].replace(itemmm[0], "")}',`
              let it = XEUtils.findTree(options, item => item.CID === itemmm[0])
              if (oldcategoryname != it.item.CNAME) {
                categoryname += `'${it.item.CNAME}',`
              }
              oldcategoryname = it.item.CNAME;
            }
          })
          if (categoryname) {
            categoryname = categoryname.substr(0, categoryname.length - 1)
            sql += ` CATEGORYNAME in (${categoryname}) AND`
          }
          if (cpid) {
            cpid = cpid.substr(0, cpid.length - 1)
            if (spid) {
              sql += ` (cpid in (${cpid}) OR`
            }else{
              sql += ` cpid in (${cpid}) AND`
            }
          }
          if (spid) {
            spid = spid.substr(0, spid.length - 1)
            if (cpid) {
              sql += ` spid in (${spid})) AND`
            }else{
              sql += ` spid in (${spid}) AND`
            }
          }
        }
      }
    })
    return sql
  }


  static updatesql(paramsList,form,options,commonParam) {
    let sql = ''
    var text = ''
    if (!XEUtils.isUndefined(paramsList)){
      paramsList = paramsList.filter(function (item) {
        if (item.screeningtype){
          return item;
        }
      })
    }
    XEUtils.objectEach(form, (item, key) => {
      var itemm = XEUtils.find(paramsList, item => item.columnName === key)
      if (itemm.screeningtype == 'area' && item.length > 0) {
        let join = ` ${key} in (`
        XEUtils.arrayEach(item, (itemmm) => {
          join += `'${itemmm}',`
          text += `${itemmm},`
        })
        join = join.substr(0, join.length - 1)
        sql += ` ${join}) AND`
      }
      if (itemm.screeningtype == 'important_prod' && item.length > 0) {
        let join = ` SPID in (`
        XEUtils.arrayEach(item, (itemmm) => {join += `'${itemmm}',`})
        join = join.substr(0, join.length - 1)
        sql += ` ${join}) AND`
      }
      if (itemm.screeningtype == 'DatePicker' && item && item.length > 0) {
        if (itemm.screeningsetting == 'month') {
          sql += ` ${key} = ${item} AND`
        } else if (itemm.screeningsetting == 'quarter') {
          sql += ` ${key} = ${item} AND`
        } else if (itemm.screeningsetting == 'daterange') {
          sql += ` ${key} >= ${item[0]} AND ${key} <= ${item[1]} AND`
          text = `${moment(item[0]).format('YYYY.MM.DD')} - ${moment(item[1]).format('YYYY.MM.DD')}; `
        } else if (itemm.screeningsetting == 'week') {
          sql += ` ${key} = ${item} AND`
        } else if (itemm.screeningsetting == 'date') {
          sql += ` ${key} = ${item} AND`
          text = `${moment(item).format('YYYY.MM.DD')}; `
        } else {
          sql += ` ${key} >= ${item[0]} AND ${key} <= ${item[1]} AND`
        }
      }
      if (itemm.screeningtype == 'commonDate' && item.type) {
        if (item.type == 'DAY'){
          sql += ` DTYPE = '${item.type}' AND THEDVALUE >= ${item.last30} AND THEDVALUE <= ${item.today} AND`
          text += `${moment(item.last30).format('YYYY.MM.DD')} - ${moment(item.today).format('YYYY.MM.DD')}; `
        }else{
          sql += ` DTYPE = '${item.type}' AND THEDVALUE >= ${item.startTime} AND THEDVALUE <= ${item.endTime} AND`
          if (item.type == 'MONTH'){
            text = `${moment(item.startTime).format('YYYY.MM')} - ${moment(item.endTime).format('YYYY.MM')}; `
          }else{
            text = `${moment(item.startTime).format('YYYY')}季度 - ${moment(item.endTime).format('YYYY')}季度; `
          }
        }
      }
      if (itemm.screeningtype == 'input' && item && item.length > 0) {
        sql += ` ${key} like '%${item}%' AND`
        text += item
      }
      if (itemm.screeningtype == 'select') {

        if (itemm.screeningsetting == 1){
          sql += ` ${key} = '${item}' AND`
        }else{
          let join = ` ${key} in (`
          XEUtils.arrayEach(item, (itemmm) => {
            join += `'${itemmm}',`
          })
          join = join.substr(0, join.length - 1)
          sql += ` ${join}) AND`
        }
      }
      if (itemm.screeningtype == 'income' && item && item.length > 0) {
        sql += ` ${key} = '${item}' AND`
      }
      if (itemm.screeningtype == 'cat' && item.length > 0) {
        //if (itemm.screeningtype == 'cat') {
        var categoryname = '', cpid = '', spid = '', oldcategoryname
        if(commonParam.CATEGORYNAME){
          item = commonParam.CATEGORYNAME
        }

        if (item){
          let a = ''
          XEUtils.arrayEach(XEUtils.uniq(XEUtils.flatten(item)), (item, key) => {
            let txtt = XEUtils.find(XEUtils.toTreeArray(options), itemm => itemm.CID === item)
            a += `${txtt.CNAME},`
          })
          text += `${a}; `
        }

        XEUtils.arrayEach(item, (itemmm) => {
          if (itemmm.length == 1) {
            var it = XEUtils.findTree(options, item => item.CID === itemmm[0])
            if (oldcategoryname != it.item.CNAME) {
              categoryname += `'${it.item.CNAME}',`
            }
            oldcategoryname = it.item.CNAME;
          }
          if (itemmm.length == 3) {
            spid += `'${itemmm[2]}',`
          } else if (itemmm.length == 2) {
            cpid += `'${itemmm[1].replace(itemmm[0], "")}',`
            let it = XEUtils.findTree(options, item => item.CID === itemmm[0])
            if (oldcategoryname != it.item.CNAME) {
              categoryname += `'${it.item.CNAME}',`
            }
            oldcategoryname = it.item.CNAME;
          }
        })
        if (categoryname) {
          categoryname = categoryname.substr(0, categoryname.length - 1)
          sql += ` categoryname in (${categoryname}) AND`
        }

        if (cpid) {
          cpid = cpid.substr(0, cpid.length - 1)
          if (spid) {
            sql += ` (cpid in (${cpid}) OR`
          }else{
            sql += ` cpid in (${cpid}) AND`
          }
        }
        if (spid) {
          spid = spid.substr(0, spid.length - 1)
          if (cpid) {
            sql += ` spid in (${spid})) AND`
          }else{
            sql += ` spid in (${spid}) AND`
          }
        }
      }
    })
    return {sql:sql,text:text}
  }
}
