import type { DynamicTableProps, autoColsItem } from '../dynamic-table';
import { type TablePaginationConfig } from 'ant-design-vue/es/table';
import { type orderParamaItem } from '../types/table';
import type { TableColumn } from '../types';
import { message } from 'ant-design-vue';
import { i18n } from '../../../../locales/index';
// import titleRequire from '../components/tool-bar/table-require.vue';

interface scroll {
  x?: string | number | boolean;
  y?: string | number | boolean;
}

export const changeFormat = (filterVal: Object, props: DynamicTableProps) => {
  for (const i in filterVal) {
    const val = filterVal[i];
    for (const j in props.columnFilter) {
      const item = props.columnFilter[j];
      if (typeof item == 'object') {
        if (item.prop == i) {
          //目前先仅仅处理number
          if (item.dataType == 'number') {
            if (val != null && val != undefined && val != '') filterVal[i] = parseFloat(val);
          }
          break;
        }
      }
    }
  }
  return filterVal;
};

export const queryParamAdapter = (
  queryParams: object,
  props: DynamicTableProps,
  pageOption: TablePaginationConfig | undefined | false,
  type?: String,
) => {
  switch (props.remoteQueryMode) {
    case 0:
      return hgAdapter(); //化工数据请求模式
    case 1:
      return wmsAdapter(queryParams, pageOption, type); //仓库数据请求模式1   type参数用来确定是否获取全部数据
    case 2:
      return wmsAdapter(queryParams, pageOption, type); //仓库数据请求模式2
    case 3:
      return mesAdapter(queryParams, pageOption, type); //新平台Mes数据请求格式
  }

  function hgAdapter() {
    /* 构建动态查询参数
             格式 query={"PageSize":0,"Page":0,"Conditions":[{"Key":"Code","Value":"string"}]}
    */
    const autoParams = {
      query: {
        Page: 0,
        PageSize: 10,
        Conditions: [] as any[],
        LoginUser: '',
      },
    };
    autoParams.query.Conditions = [];
    //添加分页信息
    if (!Object.is(pageOption, false)) {
      if (pageOption) {
        autoParams.query.Page = pageOption.current ? pageOption.current : 1;
        autoParams.query.PageSize = pageOption.pageSize ? pageOption.pageSize : 10;
      }
    }
    //排除掉null,undefined,''的参数
    for (const i in queryParams) {
      const paramVal = queryParams[i];
      if (i == 'undefined') continue;
      if (!paramVal) {
        if (typeof paramVal == 'function') continue;
        if (typeof paramVal == 'string' && paramVal == '') continue;
        const para = {
          Key: i,
          Value: queryParams[i],
        };
        autoParams.query.Conditions.push(para);
      }
    }
    //把query参数变为json类型
    const parama = {
      query: JSON.stringify(autoParams.query),
    };
    //返回拼接过的字符串
    return parama;
  }

  function wmsAdapter(queryParams, pageOption, type?: String) {
    const temp = {
      Page: 1,
      PageSize: type ? 0 : 10,
    };
    const autoParams = { ...temp, ...queryParams };
    //添加分页信息
    if (!Object.is(pageOption, false)) {
      if (pageOption) {
        autoParams.Page = type ? 0 : pageOption.current ? pageOption.current : 1;
        autoParams.PageSize = type ? 0 : pageOption.pageSize ? pageOption.pageSize : 10;
      }
    }
    return autoParams;
  }

  function mesAdapter(queryParams, pageOption, type?: String) {
    const temp = {
      Request: {
        Page: 1,
        PageSize: 10,
      },
    };
    const autoParams = {
      Request: { Page: 0, PageSize: 0 },
    };
    Object.assign(autoParams, queryParams);
    autoParams.Request = { ...temp.Request, ...queryParams.Request };
    //添加分页信息
    if (!Object.is(pageOption, false)) {
      if (pageOption) {
        autoParams.Request.Page = type ? 0 : pageOption.current ? pageOption.current : 1;
        autoParams.Request.PageSize = type ? 0 : pageOption.pageSize ? pageOption.pageSize : 10;
      }
    }
    return autoParams;
  }
};
//获取排序数据
export const getOrderParama = (props: DynamicTableProps) => {
  let tempArray = [] as orderParamaItem[];
  if (props.OrderParam) {
    tempArray = tempArray.concat(props.OrderParam);
  }
  return tempArray;
};

//函数用于根据数据，对滚动位置进行计算
export const setScrollPosition = function (props: DynamicTableProps, scroolHeight?: number) {
  let scrollTemp = {
    x: 0,
  } as scroll;
  if (props.scroll) {
    scrollTemp = props.scroll;
  } else {
    scrollTemp.x = 'max-content'; //默认自适应宽度 先不计算横向滚动宽度
    if (scroolHeight) {
      scrollTemp.y = scroolHeight;
    }
  }
  // console.log('计算得到的滚动宽度为：' + scrollTemp.x);
  return scrollTemp;
};

export const GuidID = function () {
  //生成GUIID
  let guid = '';
  for (let i = 1; i <= 32; i++) {
    const n = Math.floor(Math.random() * 16.0).toString(16);
    guid += n;
    if (i == 8 || i == 12 || i == 16 || i == 20) guid += '-';
  }
  return guid;
};

export const getFixedCols = function (cols: TableColumn[] | autoColsItem[] | undefined) {
  //在丢到数据中显示之前，将列重新排序
  let target = [] as TableColumn[];
  if (typeof cols != 'undefined') {
    const fixedLeftCols = cols.filter((item) => {
      return item.fixed == 'left' || item.fixed == true;
    });
    const fixedRightCols = cols.filter((item) => {
      return item.fixed == 'right';
    });
    const commonCols = cols.filter((item) => {
      return typeof item.fixed == 'undefined' || item.fixed == false;
    });
    target = fixedLeftCols.concat(commonCols).concat(fixedRightCols);
  }
  return target;
};

export const formatAutoCols = (props, emit) => {
  const innerCols = [] as TableColumn[];
  let targetCols = props.autoClumns?.filter((item) => {
    return item.Visible == true;
  });

  debugger

  targetCols = getFixedCols(targetCols);
  if (targetCols?.length == 0) {
    return innerCols;
  }

  if (targetCols?.length && targetCols.length > 0) {
    for (let i = 0; i < targetCols.length; i++) {
      const tempItem = {} as TableColumn;
      tempItem.title = targetCols[i].title;
      tempItem.dataIndex = targetCols[i].dataIndex;
      tempItem.width = targetCols[i].width;
      tempItem.ellipsis = true;
      tempItem.resizable =
        typeof targetCols[i].resizable == 'undefined' || targetCols[i].resizable == true
          ? true
          : false;
      tempItem.fixed = targetCols[i].fixed ? targetCols[i].fixed : false;

      tempItem.hideInSearch = targetCols[i].ifshowInQueryForm ? false : true;
      tempItem.sorter = targetCols[i].sorter ? targetCols[i].sorter : false;
      tempItem.Style = targetCols[i].Style;
      tempItem.customRender = ({ record }) => {
        return <span>{record[targetCols[i].dataIndex]}</span>;
      };
      if (targetCols[i].Style.toLowerCase() == 'textbox') {
        //文本框
        tempItem.formItemProps = {
          required: targetCols[i].required ? targetCols[i].required : false,
        };
        tempItem.customRender = ({ record }) => {
          return _getComTextLabel(props, record, targetCols[i], emit);
        };
        // if (targetCols[i].required) {
        //   // @ts-ignore
        //   tempItem.customHeaderCell = () => {
        //     return setRequireHeader(targetCols[i]);
        //   };
        // }
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else if (targetCols[i].Style.toLowerCase() == 'combox') {
        //下拉选项
        if (targetCols[i].ifshowInQueryForm) {
          tempItem.formItemProps = {
            component: 'Select',
            required: targetCols[i].required ? targetCols[i].required : false,
            componentProps: ({ tableInstance }) => ({
              options: targetCols[i].Option,
              allowClear: true,
              size: 'small', //默认显示控件类型是small
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          };
        }
        tempItem.customRender = ({ record }) => {
          return _getComBoxlabel(props, record, targetCols[i]);
        };
        // if (targetCols[i].required) {
        //   // @ts-ignore
        //   tempItem.customHeaderCell = () => {
        //     return setRequireHeader(targetCols[i]);
        //   };
        // }
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else if (targetCols[i].Style.toLowerCase() == 'checkbox') {
        //单选
        if (targetCols[i].ifshowInQueryForm) {
          tempItem.formItemProps = {
            component: 'Select',
            required: targetCols[i].required ? targetCols[i].required : false,
            componentProps: ({ tableInstance }) => ({
              size: 'small',
              options: [
                {
                  label: '是',
                  value: "true",
                },
                {
                  label: '否',
                  value: "false",
                },
                {
                  label: '全部',
                  value: "null",
                },
              ],
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          };
        }
        tempItem.customRender = ({ record }) => {
          return getCheckBox(props, record, targetCols[i]);
        };
        // if (targetCols[i].required) {
        //   // @ts-ignore
        //   tempItem.customHeaderCell = () => {
        //     return setRequireHeader(targetCols[i]);
        //   };
        // }
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else if (targetCols[i].Style.toLowerCase() == 'datetime') {
        //日期控件
        if (targetCols[i].ifshowInQueryForm) {
          // @ts-ignore
          tempItem.formItemProps = {
            component: 'DatePicker',
            required: targetCols[i].required ? targetCols[i].required : false,
            componentProps: ({ tableInstance }) => ({
              valueFormat: targetCols[i].valueFormat ? targetCols[i].valueFormat : 'YYYY-MM-DD',
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          };
        }
        tempItem.customRender = ({ record }) => {
          return _getDateLabel(props, record, targetCols[i]);
        };
        // if (targetCols[i].required) {
        //   // @ts-ignore
        //   tempItem.customHeaderCell = () => {
        //     return setRequireHeader(targetCols[i]);
        //   };
        // }
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else if (targetCols[i].Style.toLowerCase() == 'tree') {
        //树形控件
        if (targetCols[i].ifshowInQueryForm) {
          // @ts-ignore
          tempItem.formItemProps = {
            component: 'Select',
            required: targetCols[i].required ? targetCols[i].required : false,
            componentProps: ({ tableInstance }) => ({
              fieldNames: { label: 'name', value: 'id', options: 'children' },
              mode: targetCols[i].Mode ? targetCols[i].Mode : 'combobox',
              options: targetCols[i].treeOption ? targetCols[i].treeOption : [],
              allowClear: true,
              size: 'small',
              onChange() {
                console.log('tableInstance', tableInstance?.reload());
              },
            }),
          };
        }
        tempItem.customRender = ({ record }) => {
          return _getTreeLabel(props, record, targetCols[i]);
        };
        // if (targetCols[i].required) {
        //   // @ts-ignore
        //   tempItem.customHeaderCell = () => {
        //     return setRequireHeader(targetCols[i]);
        //   };
        // }
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else if (targetCols[i].Style.toLowerCase() == 'action') {
        tempItem.customRender = ({ record }) => {
          return setOperatrBtn(record, targetCols[i], emit);
        };
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      } else {
        //预留其他情况，应对外部处理情况(预留用于外部自定义控件)
        const copy = {} as TableColumn;
        Object.assign(copy, tempItem);
        innerCols.push(copy);
      }
    }
  }

  return innerCols;
};

const setOperatrBtn = (record, col, emit) => {
  const btnClick = (key) => {
    //key的作用是用来识别是哪个按钮事件
    emit('on-btn-click', record, col, key);
  };

  return (
    <span>
      {col.btnOption.map((items) => {
        //生成下拉选项
        return (
          <a-button
            size="small"
            type={items.type}
            title={items.tooltip}
            label={items.label}
            style={'color:' + items.color}
            onClick={btnClick.bind(this, items.btnKey)}
          >
            {items.icon ? <em class={items.icon}></em> : ''}
            {items.label ? <label>{items.label}</label> : ''}
          </a-button>
        );
      })}
    </span>
  );
};

// const setRequireHeader = (cols) => {
//   return (createVNode(<span>
//     <span style="color:red">*</span>
//     <span>{cols.dataIndex}</span>
//   </span>)
//   );
// };

const getCheckBox = (props, record, col) => {
  if (!props.isAutoEditable) {
    return <a-checkbox checked={record[col.dataIndex]} disabled={true}></a-checkbox>;
  } else {
    if (!col.isEdit) {
      return <a-checkbox checked={record[col.dataIndex]} disabled={true}></a-checkbox>;
    } else {
      return editCheckBox(record, col);
    }
  }
};

const editCheckBox = (record, col) => {
  const key = col.dataIndex;
  return <a-checkbox v-model:checked={record[key]} />;
};

const getReadOnlyData = (data) => {
  return <span>{data}</span>;
};

const getEditByCondition = (record, col) => {
  let bRet = true;
  if (typeof col.ifCondition == 'undefined' || typeof col.editCondition == 'undefined') {
    //只要有一个字段没配置，则认为不需要限制
    return bRet;
  }
  if (col.ifCondition == record[col.editCondition]) {
    //如果限制条件满足，则不允许编辑
    bRet = false;
  }
  //返回魏true的话，则是允许编辑
  return bRet;
};

const _getComTextLabel = (props, record, item, emit) => {
  const editByCondition = getEditByCondition(record, item); //
  if (!props.isAutoEditable) {
    return getReadOnlyData(record[item.dataIndex]);
  } else {
    if (!item.isEdit) {
      //不可编辑的时候，生成固定文本
      return getReadOnlyData(record[item.dataIndex]);
    } else {
      if (editByCondition) {
        //如果可编辑，但是readonly为true ,说明需要生成带图标控件，需要弹窗
        if (!item.readonly) {
          return editTextBox(record, item, emit);
        } else {
          return TextBoxPop(record, item, emit);
        }
      } else {
        return getReadOnlyData(record[item.dataIndex]);
      }
    }
  }
};

const editTextBox = (record, col, emit) => {
  const key = col.dataIndex;
  const EditTextChange = () => {
    const bRet = checkInputIfValid(record, col, record[key]);
    if (bRet) {
      emit('check-data', record, true, key); //之所以要带true和false两个参数往外抛出，是为了方便二次开发人员做有效性的判断
    } else {
      emit('check-data', record, false, key); //
    }
  };
  return (
    <a-input
      allowClear
      size="small"
      autofocus={true}
      v-model:value={record[key]}
      maxlength={col.maxlength == undefined ? 500 : col.maxlength}
      onInput={EditTextChange}
      onblur={EditTextBlur(record, emit)}
    >
      <template prefix="icon-search icon green">
        <user-outlined type="user" />
      </template>
    </a-input>
  );
};
//向外抛出click事件
const TextBoxPop = (record, col, emit) => {
  const EditTextClick = () => {
    emit('text-click', record, col);
  };
  return (
    <span onClick={EditTextClick}>
      <em style="float: right;color:green" class={col.icon ? col.icon : 'icon-search green'}></em>
    </span>
  );
};

const EditTextBlur = (record, emit) => {
  emit('edit-row-data-change', record);
};

const _getComBoxlabel = (props, record, col) => {
  const editByCondition = getEditByCondition(record, col); //
  if (typeof col.Option == 'undefined') {
    return <span>{record[col.dataIndex]}</span>;
  } else if (props.isAutoEditable == false || !col.isEdit || editByCondition == false) {
    let showLabel = '';
    const targetItem = col.Option.filter((item) => {
      return item.value == record[col.dataIndex];
    });
    if (targetItem.length > 0) {
      showLabel = targetItem[0].label;
    }
    return <span>{showLabel}</span>;
  } else {
    return editComBox(record, col);
  }
};

const editComBox = (record, col) => {
  const key = col.dataIndex;

  return (
    <a-select
      style="width:100%"
      size="small"
      placeholder=""
      mode={col.Mode}
      allowClear
      show-search
      v-model:value={record[key]}
      filterOption={filterOption}
    >
      {colGetComboxOptions(col, col.Option)}
    </a-select>
  );
};

const colGetComboxOptions = (col, Option) => {
  return Option.map((item) => {
    return (
      <a-select-option value={item.value} >
        {item.label}
      </a-select-option>
    );
  });
};

const _getDateLabel = (props, record, col) => {
  const editByCondition = getEditByCondition(record, col); //
  if (!props.isAutoEditable) {
    return getReadOnlyData(record[col.dataIndex]);
  } else {
    if (!col.isEdit || editByCondition == false) {
      //不可编辑的时候，生成固定文本
      return getReadOnlyData(record[col.dataIndex]);
    } else {
      return editDateTime(record, col);
    }
  }
};

const filterOption = (input: string, option: any) => {
  if (option.label) {
    return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  } else {
    return option.label.indexOf(input) >= 0;
  }
};

const editDateTime = (record, col) => {
  const key = col.dataIndex;
  return (
    <a-date-picker
      style="width:100%"
      size="small"
      placeholder=""
      allowClear
      valueFormat={col.valueFormat ? col.valueFormat : 'YYYY-MM-DD'}
      v-model:value={record[key]}
    ></a-date-picker>
  );
};

const _getTreeLabel = (props, record, col) => {
  const editByCondition = getEditByCondition(record, col); //
  if (typeof col.treeOption == 'undefined') {
    //如果选项不配置，则后台返回什么数据，前端显示什么
    return getReadOnlyData(record[col.dataIndex]);
  } else if (props.isAutoEditable == false || !col.isEdit || editByCondition == false) {
    const showLabel = getShowName(record, col);
    return getReadOnlyData(showLabel);
  } else {
    return editTree(record, col);
  }
};

const editTree = (record, col) => {
  const key = col.dataIndex;
  const fieldNames = {
    label: 'name',
    value: 'id',
    options: 'children',
  };
  return (
    <a-select
      style="width:100%"
      size="small"
      placeholder
      mode={col.Mode}
      allowClear
      v-model:value={record[key]}
      options={col.treeOption}
      fieldNames={fieldNames}
      show-search
      filterOption={filterOption}
    >
      {colGetComboxOptions(col, col.treeOption)}
    </a-select>
  );
};

const getShowName = (record, col) => {
  let label = '';
  let option = [...col.treeOption];
  while (option.length) {
    const target = option.shift();
    if (target.children) {
      if (target.children.length > 0) {
        option = [...option, ...target.children];
      }
    }
    if (target.id == record[col.dataIndex]) {
      label = target.name;
      break;
    }
  }
  return label;
};

const checkInputIfValid = (row, col, value) => {
  const { t } = i18n.global;
  //验证input输入的数据是否合格
  if (col.type == undefined || col.type == '' || col.type == null) {
    //如果不配置类型，则默认不进行验证
    return true;
  }
  switch (col.type) {
    case 'int':
      {
        if (value == null || value == undefined || value == '') {
          return true; //允许输入为空
        }
        const bRetT = /^[0-9]*[1-9][0-9]*$/.test(value);
        const bRetL = checkIfLengthValid(col, value);
        if (bRetT == false) {
          message.warning(t('component.table.IntWarning', [col.Name]));
          return false;
        }
        if (bRetL == false) {
          message.warning(t('component.table.LengthWarning', [col.Name]));
          return false;
        }
        if (bRetT == true && bRetL == true) {
          return true;
        }
      }
      break;
    case 'float':
      {
        //验证是否是正确的浮点数
        if (value == null || value == undefined || value == '') {
          return true; //允许输入为空
        }
        const bRetT = /^\d+(\.\d+)?$/.test(value);
        const bRetL = checkIfLengthValid(col, value);
        if (bRetT == false) {
          message.warning(t('component.table.FloatWarning', [col.Name]));
          return false;
        }
        if (bRetL == false) {
          message.warning(t('component.table.LengthWarning', [col.Name]));
          return false;
        }
        if (bRetT == true && bRetL == true) {
          return true;
        }
      }
      break;
    default: {
      const bRetL = checkIfLengthValid(col, value);
      if (bRetL == false) {
        message.warning(t('component.table.LengthWarning', [col.Name]));
        return false;
      }
    }
  }
};

const checkIfLengthValid = (col, value) => {
  //检查长度是否超长
  let sValue = '';
  if (typeof value == 'number') {
    //如果是数字，则先转换成字符串
    sValue = value.toString();
  } else {
    sValue = value;
  }
  if (col.maxlength == undefined || col.maxlength == null || col.maxlength == '') {
    //不配置的情况下，则不判断长度是否超长
    return true;
  }
  if (col.maxlength >= sValue.length) {
    return true;
  } else {
    return false;
  }
};
//冒泡排序法，用于数字类型排序
export const bubbleSort = function (arr: Array<number>): Array<number> {
  const final: Array<number> = new Array(...arr);
  for (let i = 0; i < final.length; i++) {
    let no_swap = true;
    for (let j = 0; j < final.length - i - 1; j++) {
      // 如果前一个更大，则和后面的交换
      if (final[j] > final[j + 1]) {
        const temp = final[j + 1];
        final[j + 1] = final[j];
        final[j] = temp;
        no_swap = false;
      }
    }
    // 如果未冒泡，则已经排序完毕
    if (no_swap) {
      break;
    }
  }
  return final;
};

export const getVisiCols = function (Cols?: autoColsItem[]) {
  if (Cols) {
    return Cols.filter((item) => {
      return item.Visible == true;
    });
  } else {
    return [];
  }
};
