import BooleanTd from './tds/booleanTd';
import DateTd from './tds/dateTd';
import DictTd from './tds/dictTd';
import NumberTd from './tds/numberTd';
import SplitTd from './tds/splitTd';
import BtnInTable from './btnInTable';
import DivideLine from './divideLine';
import ColumnSorter from './column.sorter'
import QrcodeVue from 'qrcode.vue';
export default (columns, dicts, asyncDicts, sortObj, clickEvent, vue) => {
  let newColumns = [];
  let flag = false;
  for (let column of columns) {
    //该列可排序
    column.sortable = (column.sortable !== undefined && column.sortable !== null) ?column.sortable:vue.$HqComponents.hongqiTable.allSortAble;
    flag |= (column.fixed ? true : false);

    //如果没有票排列，先生成排列对象
    if (Object.keys(sortObj).length === 0) {
      for (let i in columns) {
        sortObj[columns[i].title] = {
          show: true,
          sortIndex: i
        };
      }
    }
    //列之间排列
    if (sortObj[column.title]) {
      column.sortIndex = sortObj[column.title].sortIndex;
      //显示与隐藏
      if (sortObj[column.title].show) {
        column.show = true;
      } else {
        column.show = false;
      }
    } else {
      column.sortIndex = 0;
      column.show = true;
    }
    if (column.show) {
      newColumns.push(column);
    }
  }
  newColumns = newColumns.sort(function (a, b) {
    return a.sortIndex - b.sortIndex;
  })
  let baseColumns = [];
  if (vue.index) {
    baseColumns.push({
      title: ' ',
      key: 'index',
      type: 'index',
      fixed: flag ? 'left' : null,
      minWidth: 50,
      className: 'index-cell',
      renderHeader: (h) => {
        if (vue.headerTool) {
          return h(ColumnSorter, {
            props: {
              columns: columns
            },
            on: {
              setSortObj: vue.setSortObj
            }
          })
        }
      }
    })
  }
  if (vue.selection) {
    baseColumns.push({
      title: ' ',
      type: 'selection',
      width: 50,
      fixed: flag ? 'left' : null,
      align: 'center'
    })
  }


  //克隆原列定义
  newColumns = baseColumns.concat(newColumns);
  newColumns = newColumns.filter(item=>!item.hide)

  for (let column of newColumns) {
    column.type = column.type ? column.type : 'string';
    column.export = column.export === false ? false : true;
    //如果有render属性，无视其他配置，执行render函数
    if (column.renderFcn) {
      column.render = column.renderFcn;
      continue;
    }
    //根据type不同，渲染不同的内容
    switch (column.type) {
      //字符串
      case 'string':
        //异步翻译
        if (column.asyncTranslate) {
          let dict = asyncDicts[column.key];
          if (!dict) {
            vue.$set(asyncDicts, column.key, {})
            column.codeTable = asyncDicts[column.key];
          } else {
            column.codeTable = dict;
          }
          column.render = (h, params) => {
            return h(DictTd, {
              props: {
                value: params.row[column.key],
                dict: column.key,
                dicts: asyncDicts,
                toggle: column.toggle
              }
            });
          };
        }
        //拆分换行
        else if (column.splitRow) {
          let dict = dicts[column.dict];
          column.codeTable = dict;
          column.render = (h, params) => {
            return h(SplitTd, {
              props: {
                value: params.row[column.key],
                split: column.split,
                dict: column.dict,
                dicts: dicts,
                link: column.link
              },
              on: {
                onclick: function () {
                  clickEvent.onBtnClick(column.key, params);
                }
              }
            });
          };
        }
        //字典翻译
        else if (column.dict) {
          let dict = dicts[column.dict];
          column.codeTable = dict;
          column.render = (h, params) => {
            return h(DictTd, {
              props: {
                value: params.row[column.key],
                dict: column.dict,
                dicts: dicts,
                toggle: column.toggle,
                split: column.split,
              }
            });
          };
        }
        break;
        //数字型
      case 'number':
        column.render = (h, params) => {
          return h(NumberTd, {
            props: {
              value: params.row[column.key],
              format: column.format
            }
          });
        };
        break;
        //布尔型
      case 'boolean':
        column.render = (h, params) => {
          return h(BooleanTd, {
            props: {
              value: params.row[column.key]
            }
          });
        };
        break;
        //日期与时间
      case 'date':
        column.render = (h, params) => {
          return h(DateTd, {
            props: {
              value: params.row[column.key],
              format: column.format ? column.format : 'yyyy-MM-dd'
            }
          });
        };
        break;
        //图片
      case 'img':
        column.render = (h, params) => {
          return h('div', {
            style: {
              whiteSpace: 'nowrap'
            },
            on: {
              click() {
                clickEvent.showPhoto(params);
              }
            }
          }, [
            h('img', {
              style: {
                'width': '60px',
                cursor: 'pointer'
              },
              attrs: {
                src: params.row[column.key]
              }
            })
          ]);
        };
        break;
        //二维码
      case 'qrcode':
        column.render = (h, params) => {
          if (params.row[column.key]) {
            return h('div', {
              style: {
                whiteSpace: 'nowrap'
              },
              on: {
                click() {
                  clickEvent.showQRCode(params.row[column.key]);
                }
              }
            }, [
              h(QrcodeVue, {
                style: {
                  cursor: 'pointer'
                },
                props: {
                  value: params.row[column.key],
                  size: 60
                },
                attrs: {
                  src: params.row[column.key]
                }
              })
            ]);
          }
        };
        break;
        //按钮
      case 'button':
        column.render = (h, params) => {
          return h('div', {
            style: {
              whiteSpace: 'nowrap'
            },
          }, getBtns(column, h, params, vue));
        };
        break;
      default:
        break;
    }
  }
  //分组存放，用于两级表头
  let arr = [];
  for (let column of newColumns) {
    if (column.group) {
      let group = inArray(column)
      if (!group) {
        arr.push({
          key: column.group,
          title: column.group,
          align: 'center',
          children: [column]
        })
      } else {
        group.children.push(column);
        group.fixed = column.fixed;
      }
    } else {
      arr.push(column);
    }
  }

  function inArray(column) {
    for (let item of arr) {
      if (column.group == item.title) {
        return item;
        break;
      }
    }
    return null;
  }
  return arr;
}
// 获取渲染按钮的render函数数列
function getBtns(column, h, params, vue) {
  if (!column.btnOptions) {
    return [];
  }

  let arr = [];
  //如果按钮设置不是数组，转化成数组
  if (Object.prototype.toString.call(column.btnOptions) !== '[object Array]') {
    column.btnOptions = [column.btnOptions];
  }
  column.btnOptions.map((option, index) => {
    if (option.hide &&
      function () {
        params.origin = vue.pager.exhibitDatas[params.index];
        params.origin = params.origin ? params.origin : {}
        return option.hide(params);
      }()
    ) {
      return;
    }
    arr.push(
      h(BtnInTable, {
        props: getBtnStyle(option),
        style: option.style,
        nativeOn: {
          click: function () {
            vue.btnOnClick(option.name, params);
          }
        }
      }, getBtnText(option))
    );
    if (column.btnlength > (index + 1)) {
      arr.push(
        h(DivideLine)
      );
    }
  })
  return arr;
}
//获取按钮的text
function getBtnText(option) {
  if (!option) {
    return '按钮';
  }
  return option.text ? option.text : '按钮';
}
//获取按钮的样式
function getBtnStyle(option) {
  if (!option) {
    return {};
  }
  return {
    type: option.type ? option.type : 'default',
    size: option.size ? option.size : 'small',
    icon: option.icon ? option.icon : null,
    text: getBtnText(option)
  };
}
//是否有展开项
function hasExpand(columns) {
  for (let column of columns) {
    if (column.expand) {
      return true;
    }
  }
  return false;
}
