/**
 * 查询方案、查询面板、工具条、网格，标准查询页面
 * @param {*} queryDataset 保存数据集，命名规范 ds_[数组下标]_[对话框id]
 * @param {*} conf 组件定义配置项
 * @returns 
 */
import { StringUtil } from "@birt/funclib/StringUtil.js";
import { $CONST } from "@birt/funclib/ConstUtil.js";
import axios from "@birt/funclib/AxiosUtil.js";
import {baseURL,projectName,requestUrl} from '@birt/config'
var pn = projectName || 'birt'
export function TabTableSave(conf) {
    debugger
    const dlgId = StringUtil.randomString(6);
    const hcTabsId = "HcTabs_" + dlgId;
    const hcTabDetailId = "detail_" + dlgId;
    // 设置数据集id，分页
    var queryDataset = conf.mainDataset;
    queryDataset.controlId += "_" + dlgId;
    var addDataset = conf.addDataset;
    addDataset.controlId += "_" + dlgId;
    queryDataset._infcPagging = {
        _isPagging: true,
        returnCount: true
    }
    addDataset._editState = true;
    // 查询面板
    let hcQueryPanel = false;
    if (conf.hcQueryPanel) {
        hcQueryPanel = {
            controlName: "HcQueryPanel",
            controlId: "HcQueryPanel_" + dlgId,
            dataset: queryDataset.controlId,
            children: []
        }
        // 应用查询面板个性化配置
        Object.assign(hcQueryPanel, conf.hcQueryPanel || {});
    }

    // 操作工具条
    let hcFormToolbar = false;
    if (conf.hcFormToolbar) {
        hcFormToolbar = {
            controlName: "HcFormToolbar",
            controlId: "HcFormToolbar_" + dlgId,
            dataset: queryDataset.controlId,
            children: []
        }
        // 应用表单个性化配置
        Object.assign(hcFormToolbar, conf.hcFormToolbar || {});
    }
    const hcTableId = "HcTable_" + dlgId
    const hcTableAddId = "HcTableAdd_" + dlgId
    // 网格明细
    var hcTable = {
        controlName: "HcTable",
        controlId: "HcTable_" + dlgId,
        dataset: queryDataset.controlId,
        border: true,
        showAddBtn: false,
        // showSummary:true,
        height: function (parentHeight) {
            return parentHeight - 170;
        },
        events: {
            // 双击跳转至详情页
            rowDblclick: function (row, column, event) {
                let curtTabs = this.getRefCompt(hcTabsId);
                let pushParam = Object.assign({ url: "/data/querys" }, row);
                let eleNumber = this.store && this.store._getEleNumber();
                if (eleNumber) {
                    pushParam[$CONST.FLOWNUMBER] = row[eleNumber.field];
                }
                curtTabs.setActiveTabName(hcTabDetailId, pushParam);
            },
        },
        children: [],
    };
    // 网格新增
  var hcTableAdd = {
    isEdit: true,
    controlName: "HcTable",
    controlId: hcTableAddId,
    dataset: addDataset.controlId,
    highlightCurrentRow: true,
    height: function (parentHeight) {
      return parentHeight - 180;
    },
    size: "small",
    // showSummary:true,
    children: [],
    events: {
      currentChange: function (row) {
        debugger
        this.store.setCurtRecord(row);
        if (this.store.data.length > 0) {
          this.getRefCompt('HcButton_save').conf.disabled = false
        } else {
          this.getRefCompt('HcButton_save').conf.disabled = true
        }
      }
    },
    style: "margin:auto;"
  };
  // 应用网格个性化配置
  Object.assign(hcTable, conf.hcTable || {});
  Object.assign(hcTableAdd, conf.hcTableAdd || {});
  // 操作列 
  let operateColumn = {
    controlName: "HcTableColumnScope",
    controlId: "HcTableColumn_operate",
    label: "操作",
    width: 100,
    headerAlign: "center",
    fixed: "right",
    slot: "scope",
    children: [{
      controlName: "HcButton",
      controlId: "HcButton_add",
      type: "primary",
      circle: true,
      icon: "el-icon-plus",
      disabled: function () {
        return this.store && this.store.allowAdd && !this.store.allowAdd();
      },
      events: {
        click() {
          let newRecd = this.store.newRecord();
          this.store.add(newRecd);
        },
      },
    },
    {
      controlName: "HcButton",
      controlId: "HcButton_del",
      type: "danger",
      circle: true,
      icon: "el-icon-delete",
      disabled: function () {
        return this.store && this.store.allowRemove && !this.store.allowRemove();
      },
      events: {
        click() {
          this.store.remove(this.scope.row);
        },
      },
    },
    ],
  }
  hcTableAdd.children.push(operateColumn);
  
    // 详情表单 
    var hcDetailForm = false;
    if (conf.hcDetailForm) {
        hcDetailForm = Object.assign(
            conf.hcDetailForm,
            {
                height: function (parentHeight) {
                    return parentHeight - 170;
                },
            })
    }

    // 分页工具条
    var hcPagination = {
        controlName: "HcPagination",
        controlId: "HcPagination_" + dlgId,
        pageSizes: [10, 20, 50, 100],
        layout: "total, prev, pager, next, sizes, jumper",
        dataset: queryDataset.controlId,
    };
    var extraBtn = {
    controlName: 'HcRow',
    controlId: 'ElRow_extra',
    style: 'position: absolute;z-index:99;right:30px;height: 40px;line-height: 40px;display:flex',
    children: [{
      controlName: "HcButton",
      controlId: "HcButton_set",
      title: "列设置",
      icon: "el-icon-setting",
      size: 'small',
      disabled: function () {
        return false
      },
      events: {
        click: function () {
          var tabs = this.getRefCompt(hcTabsId).activeTabName
          if (tabs.indexOf('list') > -1) {
            this.getRefCompt(hcTableId).$children[0].showMenu('70%', 0)
          } else {
            this.getRefCompt(hcTableAddId).$children[0].showMenu('70%', 0)
          }
        }
      }
    },
    {
      controlName: "HcButton",
      controlId: "HcButton_save",
      title: "保存",
      icon: "el-icon-s-claim",
      disabled: true,
      size: 'small',
      events: {
        click: function () {
          var data = {}, __body = []
          var tabs = this.getRefCompt(hcTabsId).activeTabName
          if (tabs.indexOf('add') > -1) {
            data = this.getWorkBook().dataset[addDataset.controlId]
            var addData = data.getData()
            addData.forEach(tem => {
              tem.$state = 'rsInsert';
            })
            __body = [{
              modelFilePath: data.modelFilePath,
              data: addData
            }]
          } else {
            data = this.getWorkBook().dataset[queryDataset.controlId]
            __body = [{
              modelFilePath: data.modelFilePath,
              data: data.getDirtyData()
            }]
          }
          if (__body && __body.length > 0) {
            this.axios.post(data.saveUrl, {
              __body: JSON.stringify(__body)
            }).then((res) => {
              if (res.status == 200) {
                this.$message.success('保存成功')
              } else {
                this.$message.error(res.msg)
              }
            });
          } else {
            this.$message.warning('请添加数据')
          }
        }
      },
      mounted() {
        let data = this.getWorkBook().dataset[queryDataset.controlId]
        let me = this;
        data.on("dirtyChange", (isDirty) => {
          me.conf.disabled = !isDirty;
        });
      },
    },
    {
      controlName: "HcButton",
      controlId: "HcButton_cancel",
      title: "取消",
      disabled: true,
      icon: 'el-icon-close',
      size: 'small',
      events: {
        click: function () {
          let data = this.getWorkBook().dataset[queryDataset.controlId]
          data.cancel();
        }
      },
      mounted() {
        let data = this.getWorkBook().dataset[queryDataset.controlId]
        let me = this;
        data.on("dirtyChange", (isDirty) => {
          me.conf.disabled = !isDirty;
        });
      },
    },
    {
      controlName: "HcButton",
      controlId: "HcButton_del",
      title: "删除",
      icon: 'el-icon-delete',
      size: 'small',
      events: {
        click: function () {
          let data = this.getWorkBook().dataset[queryDataset.controlId]
          let removeData = this.getRefCompt(hcTableId).$children[0].elTable().selection;
          if (removeData.length == 0) {
            this.$message.warning('未勾选要删除的选项')
          } else {
            this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              removeData.forEach(tem => {
                tem.$state = 'rsDelete';
              })
              var __body = [{
                modelFilePath: data.modelFilePath,
                data: removeData
              }]
              this.axios.post(data.saveUrl, {
                __body: JSON.stringify(__body)
              }).then((res) => {
                if (res.status == 200) {
                  this.$message.success('删除成功')
                  data.remove(removeData)
                } else {
                  this.$message.error(res.msg)
                }
              });
            })
          }
        },
      },
    }
    ]
  }
    var hcTabs = {
    controlName: "HcTabs",
    controlId: hcTabsId,
    tabPosition: "top",
    activeTabName: "list_" + dlgId,
    events: {
      click: function () {
        var tabs = this.getRefCompt(hcTabsId).activeTabName
        if (tabs.indexOf('detail') > -1) {
          this.getRefCompt('HcButton_set').$parent.$parent.$el.style.display = 'none'
        } else {
          this.getRefCompt('HcButton_set').$parent.$parent.$el.style.display = 'flex'
        }
      }
    },
    children: [{
      controlName: "HcTabPane",
      controlId: "HcTabPane_list_" + dlgId,
      label: "列表",
      name: "list_" + dlgId,
      children: []
        .concat(hcFormToolbar ? hcFormToolbar : [])
        .concat(hcTable)
        .concat(hcPagination)
    },
    {
      controlName: "HcTabPane",
      controlId: "HcTabPane_add" + dlgId,
      label: "批量新增",
      name: "add_" + dlgId,
      children: []
        .concat(hcFormToolbar ? hcFormToolbar : [])
        .concat(hcTableAdd)
    },
    {
      controlName: "HcTabPane",
      controlId: "HcTabPane_detail_" + dlgId,
      label: "详情",
      name: hcTabDetailId,
      children: []
        .concat(hcDetailForm ? hcDetailForm : [])
    },
    ],
    slot: [].concat(extraBtn)
  }

    // 应用报表模型
    var birtWorkBook = Object.assign({
        controlName: "BirtWorkBook",
        controlId: "BirtWorkBook_" + dlgId,
        showToolBar: false,
        totalPage: 1,
        renderType: "pages",
        height: function (parentHeight) {

            return parentHeight - 1;
        },
    }, conf.birtWorkBook || {})
    // 添加布局结构
    birtWorkBook.children = [{
    controlName: "BirtSheet",
    controlId: "BirtSheet_" + dlgId,
    name: "sheet_" + dlgId,
    pageIndex: 0,
    dataSets: [queryDataset, addDataset],
    saveUrl: "/data/save?pn = " + pn,
    children: [{
      controlName: "BirtFormSheet",
      controlId: "BirtFormSheet_" + dlgId,
      children: []
        .concat(hcQueryPanel ? hcQueryPanel : [])
        .concat(hcTabs)
      // .concat(extraBtn)
    }]
  }]
    return birtWorkBook
}