import SearchFieldService from './SearchFieldService.js';
import CurdWindowResource from '../api/dic/CurdWindowResource.js';
import ProcessReportResource from '../api/dic/ProcessReportResource.js';
import FieldResource from '../api/dic/FieldResource.js';
import SelectFieldService from './SelectFieldService.js';
import EnumSelectFieldService from './EnumSelectFieldService.js';
import Common from '../common/Common.js';
import { Uuid } from 'pc-component-v3';
import { Notify } from 'pc-component-v3';
import dayjs from 'dayjs';
/**
 * CURD 窗口服务类
 */
export default {

  /**
     * 初始化CURD窗口编号
     * @param {CURD窗口编号} windowNo 
     */
  initCurdWindow: function (windowNo) {
    var _self = this;
    var tabIndex = 0;
    //  从后台加载CURD窗口的定义

    return new Promise((resolve, reject) => {
      CurdWindowResource.uniqueByNo(windowNo).then(response => {

        if (response.errorCode != 0) {
          reject(response.errorMessage);
          return;
        }

        const curdWindowDto = response.data;
        if (curdWindowDto != null && curdWindowDto.tabs != null) {
          _self.initGridColumns(curdWindowDto, tabIndex).then(successData => {
            successData.curdWindowDto = curdWindowDto;
            successData.tabDto = curdWindowDto.tabs[tabIndex];
            resolve(successData);
          }, errorData => {
            reject();
          });
        } else {
          reject();
        }
      }, errorData => {
        reject(errorData);
      });
    });
  },

  /**
     * 初始化表格列
     */
  initGridColumns: function (curdWindowDto, tabIndex) {
    var _self = this;
    var tab = curdWindowDto.tabs[tabIndex];
    var tabGridFields = tab.tabGridView.tabGridFields;
    var promises = [];
    // 表格列标题
    var colHeaders = [];
    // 表格列定义
    var columns = [];
    for (var columnIndex = 0; columnIndex < tabGridFields.length; columnIndex++) {
      var tabGridField = tabGridFields[columnIndex];

      // 冗余字段，用于afterChange
      tabGridField.windowNo = curdWindowDto.no;
      tabGridField.tabIndex = tabIndex;

      // 创建列名的集合
      var columName = tabGridField.displayName;
      colHeaders.push(columName);

      // 创建列定义
      var displayType = tabGridField.displayType;
      var fieldName = tabGridField.fieldName;
      var column = null;
      if (displayType == 'TextBoxEditor'
        || displayType == 'TextAreaEditor'
        || displayType == '') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'DoubleBoxEditor'
        || displayType == 'IntegerBoxEditor'
        || displayType == 'LongBoxEditor'
        || displayType == 'FloatBoxEditor'
        || displayType == 'BigDecimal') {
        column = {
          type: 'numeric',
        };
      } else if (displayType == 'PasswordTextBoxEditor') {
        column = {
          type: 'password',
        };
      } else if (displayType == 'CheckBoxEditor') {
        column = {
          type: 'checkbox',
        };
      } else if (displayType == 'DateBoxEditor') {
        column = {
          type: 'date',
          dateFormat: 'YYYY-MM-DD',
          correctFormat: true,
        };
      } else if (displayType == 'TimeBoxEditor') {
        column = {
          type: 'time',
          timeFormat: 'hh:mm:ss',
          correctFormat: true,
        };
      } else if (displayType == 'DateTimeBoxEditor') {
        column = {
          type: 'date',
          dateFormat: 'YYYY-MM-DD',
          correctFormat: true,
        };
      } else if (displayType == 'RichTextAreaEditor') {
        column = {
          type: 'html',
        };
      } else if (displayType == 'ListBoxEditor') {
        column = {
          type: 'handsontable',
          autoColumnSize: true,
          observeChanges: true,
        };
        let promise = SelectFieldService.loadSelectData(column, infoWindowNo, tabGridField);
        promises.push(promise);
      } else if (displayType == 'SearchBoxEditor') {
        column = {
          type: 'handsontable',
          autoColumnSize: true,
          observeChanges: true,
        };
        var infoWindowNo = tabGridField.infoWindowNo;
        let promise = SearchFieldService.loadInfoWindowData(column, infoWindowNo, tabGridField);
        promises.push(promise);
      } else if (displayType == 'ButtonEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'ListBoxEnumEditor') {
        column = {
          type: 'handsontable',
          autoColumnSize: true,
          observeChanges: true,
        };
        let promise = EnumSelectFieldService.loadSelectData(column, infoWindowNo, tabGridField);
        promises.push(promise);
      } else if (displayType == 'ImageEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'ImageListEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'RadioButtonGroupEditor') {
        column = {
          type: 'select',
        };
      } else if (displayType == 'Label') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'Video') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'File') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'EnumMultiSelect') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'ManyToManySetBoxEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'RedGreenEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'YearEditor') {
        column = {
          type: 'text',
        };
      } else if (displayType == 'YearMonthEditor') {
        column = {
          type: 'text',
        };
      }
      column.data = _self.curdWindowFieldValue(fieldName, tabGridField);
      column.readOnly = tabGridField.readOnly;
      column.readOnlyCellClassName = 'handsontable-cell-readonly';
      if (tabGridField.mandatory) {
        column.validator = _self.mandatoryValidator;
      }

      // bug fixed by jack，允许删除
      // column.allowInvalid = false;
      column.allowInvalid = true;

      column.required = tabGridField.mandatory;
      columns.push(column);
    }

    let data = {
      colHeaders: colHeaders,
      columns: columns,
    };

    if (promises.length > 0) {
      return new Promise((resolve, reject) => {
        Promise.all(promises).then(successData => {
          resolve(data);
        }, errorData => {
          reject();
        });
      });
    } else {
      return new Promise((resolve, reject) => {
        resolve(data);
      });
    }
  },

  /**
     * 强制字段验证
     * @param {*} value 
     * @param {*} callback 
     */
  mandatoryValidator: function (value, callback) {
    if (value == null || value.length == 0) {
      callback(false);
    } else {
      callback(true);
    }
  },

  /**
     * CURD窗口 HandsonTable 获取列的显示内容
     */
  curdWindowFieldValue: function (attr, tabGridField) {
    return function (row, value) {
      if (row == '##getColumnDef##' && value == row) {
        return tabGridField;
      }
      if (attr == 'id') {
        return row.id;
      } else {
        if (row.data == null || row.data[attr] == null) {
          return null;
        } else {
          // TODO
          if (row.data[attr].displayValue.length > tabGridField.entityFieldIndex) {
            var key = row.data[attr].displayValue[tabGridField.entityFieldIndex];
            if (tabGridField.displayType == 'ListBoxEnumEditor') {
              if (tabGridField.keyValues == null || tabGridField.keyValues.length == 0) {
                return null;
              } else {
                let value1 = null;
                tabGridField.keyValues.forEach(keyValue => {
                  if (keyValue.keyStr == key) {
                    value1 = keyValue.value;
                  }
                });
                return value1;
              }
            } else {
              return key;
            }
          } else {
            return '';
          }
        }
      }
    };
  },

  /**
     * 表格中单元格的数据发生改变
     * @param {*} changes 单元格和变化前后的数值
     * @param {*} source 数据变化的种类
     */
  afterChange: function (hot, changes, source) {
    if (source === 'loadData') {
      return; //don't save this change
    }

    if (changes == null || changes.length == 0) {
      return;
    }

    var _self = this;

    function toString(fieldValue) {
      if (fieldValue == null) {
        return null;
      } else {
        return fieldValue.id + ',' + fieldValue.displayName + ',' + fieldValue.fieldType;
      }
    }

    function isFieldValue(fieldValue) {
      if (fieldValue == null) {
        return false;
      } else {
        if (fieldValue.fieldType == 'String' || fieldValue.fieldType == 'Key' || fieldValue.fieldType == 'ManyToManyKey') {
          return true;
        } else {
          return false;
        }
      }
    }

    changes.forEach(([row, prop, oldValue, newValue]) => {
      if (oldValue == newValue) {
        return;
      }

      var tabGridField = prop('##getColumnDef##', '##getColumnDef##');

      if (tabGridField.entityFieldIndex >= 1) {
        return;
      }

      var newFieldValue = {
        id: '',
        displayValue: [],
        fieldType: 'Key',
      };

      var displayType = tabGridField.displayType;
      switch (displayType) {
      case 'ID':
      case 'TextBoxEditor':
      case 'DoubleBoxEditor':
      case 'IntegerBoxEditor':
      case 'LongBoxEditor':
      case 'FloatBoxEditor':
      case 'PasswordTextBoxEditor':
      case 'TextAreaEditor':
      case 'RichTextAreaEditor':
      case 'CheckBoxEditor':
      case 'TimeBoxEditor':
      case 'DateTimeBoxEditor':
      case 'ButtonEditor':
      case 'ImageEditor':
      case 'ImageListEditor':
      case 'Canvas':
      case 'RadioButtonGroupEditor':
      case 'Label':
      case 'Video':
      case 'File':
      case 'BigDecimalEditor':
      case 'EnumMultiSelect':
      case 'ManyToManySetBoxEditor':
      case 'RedGreenEditor':
      case 'YearEditor':
      case 'YearMonthEditor': {
        newFieldValue.fieldType = 'String';
        newFieldValue.displayValue[0] = newValue;
        break;
      }

      case 'DateBoxEditor': {
        newFieldValue.fieldType = 'String';
        var newValueFormat = dayjs(newValue).format('YYYY-MM-DD');
        if (newValueFormat == 'Invalid date') {
          Notify.error('错误', '当前时间格式不正确，请重新输入。', 3000);
          newFieldValue.displayValue[0] = newValue;
        } else {
          newFieldValue.displayValue[0] = newValueFormat;
        }
        break;
      }
      case 'ListBoxEnumEditor': {
        if (newValue == null || newValue == '') {
          newFieldValue.fieldType = 'String';
          newFieldValue.displayValue = [];
        } else {
          newFieldValue.fieldType = 'String';
          newFieldValue.displayValue = [newValue];
        }
        break;
      }
      case 'ListBoxEditor':
        if (newValue == null || newValue == '') {
          newFieldValue.fieldType = 'Key';
          newFieldValue.id = newValue;
          newFieldValue.displayValue = [];
        } else {
          newFieldValue.fieldType = 'Key';
          var newValueNumber = Number(newValue);
          newFieldValue.id = newValueNumber;
          if (tabGridField.keyValues == null || tabGridField.keyValues.length == 0) {
            newFieldValue.displayValue = [];
          } else {
            tabGridField.keyValues.forEach(keyValue => {
              if (keyValue.key == newValueNumber) {
                newFieldValue.displayValue = [keyValue.value];
              }
            });
          }
        }
        break;
      case 'SearchBoxEditor': {
        if (newValue == null || newValue == '') {
          newFieldValue.fieldType = 'Key';
          newFieldValue.id = newValue;
        } else {
          newFieldValue.fieldType = 'Key';
          newFieldValue.id = newValue;
          var requestUrl = 'FieldResource/getFieldValue1?';
          requestUrl += ('&windowNo=' + tabGridField.windowNo);
          requestUrl += ('&tabIndex=' + tabGridField.tabIndex);
          requestUrl += ('&fieldName=' + tabGridField.fieldName);
          requestUrl += ('&recordId=' + newValue);
          $.ajax({
            url: Common.getApiURL(requestUrl),
            type: 'get',
            dataType: 'json',
            async: false,   // 设置成同步
            beforeSend: function (request) {
              Common.addTokenToRequest(request);
            },
            success: function (data) {
              newFieldValue.displayValue = data;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
              console.log(XMLHttpRequest);
              // Common.processException(XMLHttpRequest);
            },
          });
        }

        break;
      }
      }

      var rowData = hot.getSourceDataAtRow(row);
      if (rowData.data == null) {
        rowData.data = {};
        rowData.id = -1;
      }
      if (row.id == null) {
        rowData.id = -1;
      }


      rowData.data[tabGridField.fieldName] = newFieldValue;

      // 执行callout
      if (tabGridField.calloutProcessReportNo != undefined && tabGridField.calloutProcessReportNo != null) {
        _self.callout(hot, tabGridField.calloutProcessReportNo, rowData);
      }
    });
  },

  /**
     * 运行Callout
     * @param {流程报表编号} calloutProcessReportNo 
     * @param {数据} modelData 
     * @param {编号} index 
     */
  callout: function (hot, calloutProcessReportNo, rowData) {
    var _self = this;

    // 查询流程和报表的定义
    ProcessReportResource.uniqueByNo(calloutProcessReportNo).then(response => {
      if (response.errorCode != 0) {
        Notify.error('流程和报表获取错误', response.errorMessage, true);
        return;
      }
      const successData = response.data;
      if (successData == null) {
        return;
      }

      var modelData = {};
      modelData.id = rowData.id;
      modelData.data = rowData.data;
      modelData.changed = true;

      // 执行服务端的脚本
      ProcessReportResource.runCallout(calloutProcessReportNo, modelData).then(successData => {
        if (successData && successData.modelData) {
          var newModelData = successData.modelData;
          var newModelDataData = newModelData.data;
          for (let [key, value] of Object.entries(newModelDataData)) {
            rowData.data[key] = value;
          }
          hot.render();
        }
      }, errorData => {
        Common.processException(errorData);
      });

    }, errorData => {
      Common.processException(errorData);
    });
  },

  /**
     * 复制之前完成
     * @param {WEB表格} hot 
     * @param {数据} data 
     * @param {位置} coords 
     */
  beforeCopy: function (hot, tabDto, data, coords) {
    // data -> [[1, 2, 3], [4, 5, 6]]
    // coords -> [{startRow: 0, startCol: 0, endRow: 1, endCol: 2}]
    var coord = coords[0];
    for (var row = coord.startRow; row <= coord.endRow; row++) {
      // 取出该行的数据
      var rowData = hot.getSourceDataAtRow(row);
      for (var col = coord.startCol; col <= coord.endCol; col++) {
        if (col < tabDto.tabGridView.tabGridFields.length) {
          var tabGridField = tabDto.tabGridView.tabGridFields[col];
          var displayType = tabGridField.displayType;
          // 对下拉框和搜索框类型的数据进行替换。
          switch (displayType) {
          //TODO
          case 'ListBoxEnumEditor': {
            let tempData = rowData.data[tabGridField.fieldName];

            if (tabGridField.keyValues != null
                && tempData != null
                && tempData.displayValue != null
                && tempData.displayValue.length > 0) {
              var value = tempData.displayValue[0];
              data[row - coord.startRow][col - coord.startCol] = value;
            } else {
              data[row - coord.startRow][col - coord.startCol] = null;
            }
            break;
          }
          case 'ListBoxEditor':
          case 'SearchBoxEditor': {
            let tempData = rowData.data[tabGridField.fieldName];
            if (tempData != null) {
              data[row - coord.startRow][col - coord.startCol] = tempData.id;
            } else {
              data[row - coord.startRow][col - coord.startCol] = null;
            }
            break;
          }
          }
        }
      }
    }
  },

  /**
     * 获取右击菜单
     */
  getContextMenu: function (hot, tabDto) {
    var contextMenu = {
      items: {
        'removeRow': {
          name: '删除行',
        },
        'openLinkWindow': {
          name: '新建数据',
        },
        'viewInLinkWindow': {
          name: '查看数据',
        },
        'editInLinkWindow': {
          name: '编辑数据',
        },
        'refreshDropDown': {
          name: '刷新',
        },
      },

      callback: function (key, options) {
        var selected = hot.getSelected();

        function sortId(a, b) {
          return a.start.row - b.start.row;//由低到高
        }

        if (selected != null && selected.length > 0) {
          var row = selected[0][0];
          var col = selected[0][1];
          // 删除行
          if (key === 'removeRow') {
            let row1 = options;
            var num = 0;
            var aa = hot.getDataAtRow(0);
            if (row1.length > 0) {
              
              //将选中的值按照行号排序
              row1.sort(sortId);
              for (var i = 0; i < row1.length; i++) {
                var item = row1[i];
                var start = item.start.row - num;
                var end = item.end.row - num - start + 1;
                hot.alter('remove_row', start, end);
                num += end;
              }
            }
          } else if (key == 'openLinkWindow') {
            // 获取列的定义
            let tabGridField = tabDto.tabGridView.tabGridFields[col];
            // 进行界面的跳转
            let linkCurdWindowNo = tabGridField.linkCurdWindowNo;
            if (linkCurdWindowNo != null) {
              window.open(Common.getRedirectUrl('#/desktop/window1/window-edit/create/'
                + linkCurdWindowNo
                + '/0?currPage=1&totalCount=4&saveClose=true&uuid='
                + Uuid.createUUID()));
            }
          } else if (key == 'viewInLinkWindow') {
            let data = hot.getSourceDataAtRow(row);
            if (data == null || data.id == null) {
              return;
            }

            // 编辑链接列
            // 获取列的定义
            let tabGridField = tabDto.tabGridView.tabGridFields[col];
            let fieldName = tabGridField.fieldName;
            if (data.data[fieldName] == null || data.data[fieldName].id == null) {
              return;
            }

            // 进行界面的跳转
            let linkCurdWindowNo = tabGridField.linkCurdWindowNo;
            if (linkCurdWindowNo != null) {
              window.open(Common.getRedirectUrl('#/desktop/window1/window-read/view/'
                + linkCurdWindowNo
                + '/0/'
                + data.data[fieldName].id
                + '?currIndex=1&totalCount=1&saveClose=true&uuid=' + Uuid.createUUID()));
            }
          } else if (key == 'editInLinkWindow') {
            let data = hot.getSourceDataAtRow(row);
            if (data == null || data.id == null) {
              return;
            }

            // 编辑链接列
            // 获取列的定义
            let tabGridField = tabDto.tabGridView.tabGridFields[col];
            let fieldName = tabGridField.fieldName;
            if (data.data[fieldName] == null || data.data[fieldName].id == null) {
              return;
            }

            // 进行界面的跳转
            var linkCurdWindowNo = tabGridField.linkCurdWindowNo;
            if (linkCurdWindowNo != null) {
              window.open(Common.getRedirectUrl('#/desktop/window1/window-edit/edit/'
                + linkCurdWindowNo
                + '/0/'
                + data.data[fieldName].id
                + '?currIndex=1&currIndex=1&totalCount=1&saveClose=true&uuid='
                + Uuid.createUUID()));
            }
          } else if (key == 'refreshDropDown') {
            let data = hot.getSourceDataAtRow(row);
            // 获取列的定义
            let tabGridField = tabDto.tabGridView.tabGridFields[col];

            if (tabGridField.displayType == 'ListBoxEditor') {
              var modelData = {};
              modelData.id = data.id;
              modelData.data = data.data;
              modelData.changed = true;
              modelData.windowNo = tabGridField.windowNo;
              modelData.tabIndex = 0;

              SelectFieldService.refreshField(tabGridField, tabGridField.windowNo, 0, modelData);
            }
          }
        }
      },
    };
    return contextMenu;
  },
};