<template>
  <container-item-wrapper
    :widget="widget"
    :class="widget.options.isFullscreen ? 'full-height' : ''"
  >
    <div class="h5-header">{{ widget.options.label }}</div>
    <div class="h5-search-box">
      <el-input v-model="keyword" placeholder="请选择" class="txt">
        <i slot="suffix" class="el-input__icon el-icon-search"></i>
        <el-button slot="append" class="btn" @click="searchEvent"
          >搜索</el-button
        >
      </el-input>
      <div class="icon-screen" @click="openAdvancedSearchDialog">
        <i class="iconfont icon-chaxuntiaojianshezhi"></i>筛选
      </div>
    </div>
    <div
      v-if="widget.options.isQueryTable"
      class="h5-fixed-top-btns"
      title-width="92px"
      title-align="right"
    >
      <el-form label-position="top">
        <template v-if="!!widget.buttons && widget.buttons.length > 0">
          <template v-for="(subWidget, swIdx) in widget.buttons">
            <template v-if="'container' === subWidget.category">
              <component
                :is="subWidget.type + '-item'"
                :widget="subWidget"
                :key="swIdx"
                :parent-list="widget.buttons"
                :index-of-parent-list="swIdx"
                :parent-widget="widget"
              >
                <!-- 递归传递插槽！！！ -->
                <template
                  v-for="slot in Object.keys($scopedSlots)"
                  v-slot:[slot]="scope"
                >
                  <slot :name="slot" v-bind="scope" />
                </template>
              </component>
            </template>
            <template v-else>
              <component
                :is="subWidget.type + '-widget'"
                :field="subWidget"
                :designer="null"
                :key="swIdx"
                :parent-list="widget.buttons"
                :index-of-parent-list="swIdx"
                :parent-widget="widget"
              >
                <!-- 递归传递插槽！！！ -->
                <template
                  v-for="slot in Object.keys($scopedSlots)"
                  v-slot:[slot]="scope"
                >
                  <slot :name="slot" v-bind="scope" />
                </template>
              </component>
            </template>
          </template>
        </template>
      </el-form>
    </div>
    <div class="h5-list-box">
      <div
        v-for="(row, rowIndex) in fieldModel"
        :key="rowIndex"
        class="item"
        @click="itemCheck(row)"
        :class="{ checked: checkItemIds.includes(row.id) }"
      >
        <div
          v-if="!widget.options.isQueryTable"
          class="del-btn"
          @click.stop="deleteRow(row, rowIndex)"
        >
          <i class="el-icon-delete"></i>
        </div>
        <template v-if="vxeOption.columns.length > 0">
          <div class="t1" v-if="widget.options.isQueryTable">
            <template
              v-for="(column, columnIndex) in vxeOption.columns.filter(
                (item, index) => item.isMainFiled
              )"
            >
              <b :key="'1-' + columnIndex">{{ column.title }}：</b>
              <span :key="'2-' + columnIndex">
                <template v-if="!column.params.formatS">
                  {{ row[column.field] }}
                </template>
                <template v-else-if="column.params.formatS == 'render'">
                  {{
                    column.slots.default({
                      column: column,
                      rowIndex: rowIndex,
                      row: row,
                      items: fieldModel,
                    })
                  }}
                </template>
                <template
                  v-else-if="column.slots && column.slots.default == 'widget'"
                >
                  <component
                    :is="getColumnWidgetName(column.params.widget)"
                    :field="column.params.widget"
                    :form-model="globalModel.formModel"
                    :designer="null"
                    :key="rowIndex"
                    :parent-widget="widget"
                    :columnConfig="column.params.columnConfig"
                    :subFormRowIndex="rowIndex"
                    :formItemProp="
                      getColumnProp(widget, {
                        column: column,
                        rowIndex: rowIndex,
                        row: row,
                        items: fieldModel,
                      })
                    "
                    :tableParam="{
                      column: column,
                      rowIndex: rowIndex,
                      row: row,
                      items: fieldModel,
                    }"
                  ></component>
                </template>
                <template v-else-if="column.params.formatS == 'editDelete'">
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    @click="deleteRow(row, rowIndex)"
                  >
                    <el-tooltip
                      :enterable="false"
                      effect="dark"
                      content="删除"
                      placement="top"
                      popper-class="tooltip-skin"
                    >
                      <i class="el-icon-delete" />
                    </el-tooltip>
                  </a>
                </template>
                <template v-else-if="column.params.formatS == 'editButton'">
                  <a
                    href="javascript:void(0);"
                    class="a-link"
                    @click.stop="openEditDialog(obj.row)"
                  >
                    <el-tooltip
                      :enterable="false"
                      effect="dark"
                      content="查看"
                      placement="top"
                      popper-class="tooltip-skin"
                    >
                      <i class="el-icon-edit" />
                    </el-tooltip>
                  </a>
                </template>
                <template v-else>
                  {{
                    column.formatter({
                      cellValue: row[column.field],
                      column: column,
                      rowIndex: rowIndex,
                      row: row,
                      items: fieldModel,
                    })
                  }}
                </template>
              </span>
              <!--              <div class="status">未审核</div>-->
            </template>
          </div>
          <div class="t2">
            <template
              v-if="
                !widget.options.isQueryTable || vxeOption.columns.length > 1
              "
            >
              <template v-for="(column, columnIndex) in vxeOption.columns">
                <template
                  v-if="
                    (!widget.options.isQueryTable || !column.isMainFiled) &&
                    column.showForRow
                  "
                >
                  <dl :key="columnIndex">
                    <div>
                      <dt>{{ column.title }}：</dt>
                      <dd>
                        <template v-if="!column.params.formatS">
                          {{ row[column.field] }}
                        </template>
                        <template v-else-if="column.params.formatS == 'render'">
                          {{
                            column.slots.default({
                              column: column,
                              rowIndex: rowIndex,
                              row: row,
                              items: fieldModel,
                            })
                          }}
                        </template>

                        <template
                          v-else-if="
                            column.slots && column.slots.default == 'widget'
                          "
                        >
                          <component
                            :is="getColumnWidgetName(column.params.widget)"
                            :field="column.params.widget"
                            :form-model="globalModel.formModel"
                            :designer="null"
                            :key="rowIndex + '-' + columnIndex"
                            :parent-widget="widget"
                            :columnConfig="column.params.columnConfig"
                            :subFormRowIndex="rowIndex"
                            :formItemProp="
                              getColumnProp(widget, {
                                column: column,
                                rowIndex: rowIndex,
                                row: row,
                                items: fieldModel,
                              })
                            "
                            :tableParam="{
                              column: column,
                              rowIndex: rowIndex,
                              row: row,
                              items: fieldModel,
                            }"
                          ></component>
                        </template>
                        <template
                          v-else-if="column.params.formatS == 'editDelete'"
                        >
                          <a
                            href="javascript:void(0);"
                            class="a-link"
                            @click.stop="deleteRow(row, rowIndex)"
                          >
                            <el-tooltip
                              :enterable="false"
                              effect="dark"
                              content="删除"
                              placement="top"
                              popper-class="tooltip-skin"
                            >
                              <i class="el-icon-delete" />
                            </el-tooltip>
                          </a>
                        </template>
                        <template
                          v-else-if="column.params.formatS == 'editButton'"
                        >
                          <a
                            href="javascript:void(0);"
                            class="a-link"
                            @click.stop="openEditDialog(row)"
                          >
                            <el-tooltip
                              :enterable="false"
                              effect="dark"
                              content="查看"
                              placement="top"
                              popper-class="tooltip-skin"
                            >
                              <i class="el-icon-edit" />
                            </el-tooltip>
                          </a>
                        </template>
                        <template v-else>
                          {{
                            column.formatter({
                              cellValue: row[column.field],
                              column: column,
                              rowIndex: rowIndex,
                              row: row,
                              items: fieldModel,
                            })
                          }}
                        </template>
                      </dd>
                    </div>
                  </dl>
                </template>
              </template>
            </template>
          </div>
          <div class="btns">
            <!-- <div class="checkbox_fl">
              <el-checkbox></el-checkbox>
            </div> -->
            <!--            <a class="btn"><i class="el-icon-delete"/><span>删除</span></a>
                        <a class="btn"><i class="el-icon-edit"/><span>查看</span></a>-->
            <template
              v-if="!!widget.lineButtons && widget.lineButtons.length > 0"
            >
              <template v-for="(subWidget, swIdx) in widget.lineButtons">
                <template v-if="'container' === subWidget.category">
                  <component
                    :is="subWidget.type + '-item'"
                    :widget="subWidget"
                    :key="swIdx"
                    :parent-list="widget.lineButtons"
                    :index-of-parent-list="swIdx"
                    :parent-widget="widget"
                    :subFormRowIndex="rowIndex"
                    :tableParam="{
                      rowIndex: rowIndex,
                      row: row,
                      items: fieldModel,
                    }"
                  >
                    <!-- 递归传递插槽！！！ -->
                    <template
                      v-for="slot in Object.keys($scopedSlots)"
                      v-slot:[slot]="scope"
                    >
                      <slot :name="slot" v-bind="scope" />
                    </template>
                  </component>
                </template>
                <template v-else>
                  <component
                    :is="subWidget.type + '-widget'"
                    :field="subWidget"
                    :designer="null"
                    :key="swIdx"
                    :parent-list="widget.lineButtons"
                    :index-of-parent-list="swIdx"
                    :parent-widget="widget"
                    :subFormRowIndex="rowIndex"
                    :tableParam="{
                      rowIndex: rowIndex,
                      row: row,
                      items: fieldModel,
                    }"
                  >
                    <!-- 递归传递插槽！！！ -->
                    <template
                      v-for="slot in Object.keys($scopedSlots)"
                      v-slot:[slot]="scope"
                    >
                      <slot :name="slot" v-bind="scope" />
                    </template>
                  </component>
                </template>
              </template>
            </template>
          </div>
        </template>

        <!--        <div class="t1">
                  <b>订单号：21533666</b>
                  <div class="status">未审核</div>
                </div>
                <div class="t2">
                  <p>产地：广东佛山</p>
                  <p>产地：广东佛山</p>
                  <p>产地：广东佛山</p>
                </div>-->
      </div>
    </div>
    <div class="vxe-grid" v-if="widget.options.isQueryTable">
      <div class="vxe-grid&#45;&#45;pager-wrapper">
        <vxe-pager
          class="pages-box"
          :current-page.sync="page.current"
          :page-size.sync="page.size"
          :total="page.total"
          :layouts="['PrevPage', 'Number', 'NextPage']"
          @page-change="changePageNew"
        >
          <template #right>
            <span>
              <span>当前记录</span>
              <span class="f-red"> {{ page.records.length }} </span>
              <span>/</span>
              <span class="f-red"> {{ page.total }}</span>
            </span>
          </template>
        </vxe-pager>
      </div>
    </div>

    <advancedSearchDialog
      v-if="showAdvancedSearch"
      :visiable.sync="showAdvancedSearch"
      class="adSearchForm_all"
      :formData="advancedFormData"
      @confirm="confirmAdvancedSearchDialog"
      @clear="advancedClear"
    >
      <template #form>
        <vxe-form
          :model="formModel"
          title-width="102px"
          :inline="true"
          class="adSearchForm"
        >
          <template v-for="(searchColumn, index) in vxeOption.searchColumns">
            <vxe-form-item>
              <component
                :is="getColumnWidgetName(searchColumn.widget)"
                :field="searchColumn.widget"
                :form-model="globalModel.formModel"
                :designer="null"
                :key="index"
                :parent-widget="widget"
              ></component>
            </vxe-form-item>
          </template>
        </vxe-form>
      </template>
    </advancedSearchDialog>
    <el-dialog
      title="明细详情"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :visible.sync="showRowDetailDialog"
      :modal="false"
      custom-class="dialog-style h5view-dialog"
      width="100%"
      top="0px"
      v-el-drag-dialog
      v-el-dialog-center
      :destroy-on-close="true"
    >
      <div class="cont" style="height: calc(100vh - 73px)">
        <div class="h5-list-box">
          <div
            v-for="(row, rowIndex) in [editRow]"
            :key="rowIndex"
            class="item"
          >
            <!--            <div class="del-btn"><i class="el-icon-delete"></i></div>-->
            <template v-if="vxeOption.columns.length > 0">
              <div class="t1" v-if="widget.options.isQueryTable">
                <template
                  v-for="(column, columnIndex) in vxeOption.columns.filter(
                    (item, index) => item.isMainFiled
                  )"
                >
                  <b>{{ column.title }}：</b>
                  <span>
                    <template v-if="!column.params.formatS">
                      {{ row[column.field] }}
                    </template>
                    <template v-else-if="column.params.formatS == 'render'">
                      {{
                        column.slots.default({
                          column: column,
                          rowIndex: rowIndex,
                          row: row,
                          items: fieldModel,
                        })
                      }}
                    </template>
                    <template
                      v-else-if="
                        column.slots && column.slots.default == 'widget'
                      "
                    >
                      <component
                        :is="getColumnWidgetName(column.params.widget)"
                        :field="column.params.widget"
                        :form-model="globalModel.formModel"
                        :designer="null"
                        :key="rowIndex"
                        :parent-widget="widget"
                        :columnConfig="column.params.columnConfig"
                        :subFormRowIndex="rowIndex"
                        :formItemProp="
                          getColumnProp(widget, {
                            column: column,
                            rowIndex: rowIndex,
                            row: row,
                            items: fieldModel,
                          })
                        "
                        :tableParam="{
                          column: column,
                          rowIndex: rowIndex,
                          row: row,
                          items: fieldModel,
                        }"
                      ></component>
                    </template>
                    <template v-else-if="column.params.formatS == 'editDelete'">
                      <a
                        href="javascript:void(0);"
                        class="a-link"
                        @click.stop="deleteRow(row, rowIndex)"
                      >
                        <el-tooltip
                          :enterable="false"
                          effect="dark"
                          content="删除"
                          placement="top"
                          popper-class="tooltip-skin"
                        >
                          <i class="el-icon-delete" />
                        </el-tooltip>
                      </a>
                    </template>
                    <template v-else-if="column.params.formatS == 'editButton'">
                      <a
                        href="javascript:void(0);"
                        class="a-link"
                        @click.stop="openEditDialog(obj.row)"
                      >
                        <el-tooltip
                          :enterable="false"
                          effect="dark"
                          content="查看"
                          placement="top"
                          popper-class="tooltip-skin"
                        >
                          <i class="el-icon-edit" />
                        </el-tooltip>
                      </a>
                    </template>
                    <template v-else>
                      {{
                        column.formatter({
                          cellValue: row[column.field],
                          column: column,
                          rowIndex: rowIndex,
                          row: row,
                          items: fieldModel,
                        })
                      }}
                    </template>
                  </span>
                  <!--              <div class="status">未审核</div>-->
                </template>
              </div>
              <div class="t2">
                <template
                  v-if="
                    !widget.options.isQueryTable || vxeOption.columns.length > 1
                  "
                >
                  <template v-for="(column, columnIndex) in vxeOption.columns">
                    <template
                      v-if="!widget.options.isQueryTable || !column.isMainFiled"
                    >
                      <dl>
                        <div>
                          <dt>{{ column.title }}：</dt>
                          <dd>
                            <template v-if="!column.params.formatS">
                              {{ row[column.field] }}
                            </template>
                            <template
                              v-else-if="column.params.formatS == 'render'"
                            >
                              {{
                                column.slots.default({
                                  column: column,
                                  rowIndex: rowIndex,
                                  row: row,
                                  items: fieldModel,
                                })
                              }}
                            </template>

                            <template
                              v-else-if="
                                column.slots && column.slots.default == 'widget'
                              "
                            >
                              <component
                                :is="getColumnWidgetName(column.params.widget)"
                                :field="column.params.widget"
                                :form-model="globalModel.formModel"
                                :designer="null"
                                :key="rowIndex + '-' + columnIndex"
                                :parent-widget="widget"
                                :columnConfig="column.params.columnConfig"
                                :subFormRowIndex="rowIndex"
                                :formItemProp="
                                  getColumnProp(widget, {
                                    column: column,
                                    rowIndex: rowIndex,
                                    row: row,
                                    items: fieldModel,
                                  })
                                "
                                :tableParam="{
                                  column: column,
                                  rowIndex: rowIndex,
                                  row: row,
                                  items: fieldModel,
                                }"
                              ></component>
                            </template>
                            <template
                              v-else-if="column.params.formatS == 'editDelete'"
                            >
                              <a
                                href="javascript:void(0);"
                                class="a-link"
                                @click="deleteRow(row, rowIndex)"
                              >
                                <el-tooltip
                                  :enterable="false"
                                  effect="dark"
                                  content="删除"
                                  placement="top"
                                  popper-class="tooltip-skin"
                                >
                                  <i class="el-icon-delete" />
                                </el-tooltip>
                              </a>
                            </template>
                            <template
                              v-else-if="column.params.formatS == 'editButton'"
                            >
                              <a
                                href="javascript:void(0);"
                                class="a-link"
                                @click="openEditDialog(obj.row)"
                              >
                                <el-tooltip
                                  :enterable="false"
                                  effect="dark"
                                  content="查看"
                                  placement="top"
                                  popper-class="tooltip-skin"
                                >
                                  <i class="el-icon-edit" />
                                </el-tooltip>
                              </a>
                            </template>
                            <template v-else>
                              {{
                                column.formatter({
                                  cellValue: row[column.field],
                                  column: column,
                                  rowIndex: rowIndex,
                                  row: row,
                                  items: fieldModel,
                                })
                              }}
                            </template>
                          </dd>
                        </div>
                      </dl>
                    </template>
                  </template>
                </template>
              </div>
              <div class="btns">
                <template
                  v-if="!!widget.lineButtons && widget.lineButtons.length > 0"
                >
                  <template v-for="(subWidget, swIdx) in widget.lineButtons">
                    <template v-if="'container' === subWidget.category">
                      <component
                        :is="subWidget.type + '-item'"
                        :widget="subWidget"
                        :key="swIdx"
                        :parent-list="widget.lineButtons"
                        :index-of-parent-list="swIdx"
                        :parent-widget="widget"
                        :subFormRowIndex="rowIndex"
                        :tableParam="{
                          rowIndex: rowIndex,
                          row: row,
                          items: fieldModel,
                        }"
                      >
                        <!-- 递归传递插槽！！！ -->
                        <template
                          v-for="slot in Object.keys($scopedSlots)"
                          v-slot:[slot]="scope"
                        >
                          <slot :name="slot" v-bind="scope" />
                        </template>
                      </component>
                    </template>
                    <template v-else>
                      <component
                        :is="subWidget.type + '-widget'"
                        :field="subWidget"
                        :designer="null"
                        :key="swIdx"
                        :parent-list="widget.lineButtons"
                        :index-of-parent-list="swIdx"
                        :parent-widget="widget"
                        :subFormRowIndex="rowIndex"
                        :tableParam="{
                          rowIndex: rowIndex,
                          row: row,
                          items: fieldModel,
                        }"
                      >
                        <!-- 递归传递插槽！！！ -->
                        <template
                          v-for="slot in Object.keys($scopedSlots)"
                          v-slot:[slot]="scope"
                        >
                          <slot :name="slot" v-bind="scope" />
                        </template>
                      </component>
                    </template>
                  </template>
                </template>
              </div>
            </template>

            <!--        <div class="t1">
                      <b>订单号：21533666</b>
                      <div class="status">未审核</div>
                    </div>
                    <div class="t2">
                      <p>产地：广东佛山</p>
                      <p>产地：广东佛山</p>
                      <p>产地：广东佛山</p>
                    </div>-->
          </div>
        </div>
      </div>
    </el-dialog>
  </container-item-wrapper>
</template>

<script>
import emitter from "../../../../components/xform/utils/emitter";
import i18n from "../../../../components/xform/utils/i18n";
import refMixin from "../../../../components/xform/form-render/refMixin";
import containerItemMixin from "./containerItemMixin";
import FieldComponents from "../../../../components/xform/form-designer/form-widget/field-widget/index";
import {
  assembleAxiosConfig,
  generateId,
  getReportGlobalMap,
} from "../../../../components/xform/utils/util";
import * as formatUtil from "../../../../components/xform/utils/format";
import { extendDeeply } from "../../../../utils/index.js";
import render from "../../../../views/user/bill_setting/render.vue";

const baseRefUtil = {
  emitter,
  i18n,
  refMixin,
  containerItemMixin,
  formatUtil,
  assembleAxiosConfig,
  getReportGlobalMap,
};

const defaultPageSize = 2;
export default {
  name: "list-h5-item",
  components: {
    ...FieldComponents,
  },
  mixins: [emitter, i18n, refMixin, containerItemMixin],
  componentName: "ContainerItem",
  props: {
    widget: Object,
    parentWidget: Object,
    parentList: Array,
    indexOfParentList: Number,
    subFormRowIndex: {
      type: Number,
      default: -1,
    },
    subFormColIndex: {
      type: Number,
      default: -1,
    },
    subFormRowId: {
      type: String,
      default: "",
    },
  },
  inject: [
    "refList",
    "sfRefList",
    "globalModel",
    "getFormConfig",
    "getGlobalDsv",
  ],
  data: function () {
    let that = this;
    let pageSize = defaultPageSize;
    return {
      showAdvancedSearch: false,
      showRowDetailDialog: false,
      editRow: {},
      fieldModel: [],
      selectedIndices: [],
      /*pageSize: this.widget.options.pagination.pageSize,
      pageSizes: this.widget.options.pagination.pageSizes,
      currentPage: this.widget.options.pagination.currentPage,
      total: this.widget.options.pagination.total,*/
      formData: {
        saleOrgName: "",
        loginAccount: "",
        mobile: "",
        enabled: 1,
      },
      vxeOption: { columns: [] },
      requestAccess: null,
      columnFormatMap: {
        editInput: "input",
        editNumber: "number",
        editDate: "date",
        editSelect: "select",
        editSearch: "vabsearch",
        button: "button",
      },
      dataTableConfig: {},
      advancedFormData: {},

      pageSize: pageSize,
      page: {
        current: 1,
        size: pageSize,
        total: 0,
        records: [],
      },
      keyword: null,

      checkItemIds: [],
    };
  },
  watch: {
    fieldModel(val) {
      this.formModel[this.fieldKeyName] = val || [];
    },
  },
  computed: {
    formConfig: function () {
      return this.getFormConfig();
    },
    paginationLayout: function () {
      return this.widget.options.smallPagination
        ? "prev, pager, next"
        : "total, sizes, prev, pager, next, jumper";
    },
    customClass: function () {
      return this.widget.options.customClass || "";
    },
    singleRowSelectFlag: function () {
      return !this.widget.options.showCheckBox;
    },
    buttonsColumnFixed: function () {
      return void 0 === this.widget.options.buttonsColumnFixed
        ? "right"
        : !!this.widget.options.buttonsColumnFixed &&
            this.widget.options.buttonsColumnFixed;
    },
    columns() {
      let tableColumns = this.widget.options.tableColumns;
      let newColumns = [];
      /*newColumns.push({
        type: 'checkbox',
        width: 48,
        resizable: false,
        fixed: 'left'
      });*/

      let firstColumn = tableColumns.find((column) => {
        return !!column.prop && !!column.showForRow;
      });
      let mainFiled = firstColumn?.prop;

      let formRef = this.getFormRef();
      let dateConfig = this.$baseLodash.cloneDeep(
        formRef.getFieldWidgetByType("date").options
      );
      tableColumns.forEach((t) => {
        let columnOption;
        let widget;
        let columnWidgetConfig = this.getColumnWidgetConfig(t);
        let { columnSelectedWidget, columnEditFields } = columnWidgetConfig;
        if (columnSelectedWidget) {
          widget = columnSelectedWidget;
          columnOption = widget.options;
        } else {
          columnOption = {};
        }

        let col = {
          fixed: !!t.fixed && t.fixed,
          field: t.prop,
          title: t.label,
          witdh: t.width,
          sortable: t.sortable,
          align: t.align ? t.align : "center",
          formatter: this.formatterValue,
          isMainFiled: mainFiled == t.prop,
          showForRow: t.showForRow,
          params: {
            ...columnOption,
            widget: widget,
            formatS: t.formatS,
            required: t.required || false,
            columnConfig: t,
            utcTransformEnabled: widget
              ? !!columnOption.utcTransformEnabled
              : !t.formatS ||
                  [
                    "d1",
                    "d2",
                    "d3",
                    "d4",
                    "d5",
                    "render",
                    "create_date",
                    "modify_date",
                  ].includes(t.formatS)
                ? !!t.utcTransformEnabled
                : false,
          },
          visible: t.show,
        };

        if (t.formatS == "render") {
          let r = t.render ? new Function("params", "h", t.render) : null;
          col.slots = {
            default: (params, h) => {
              return r ? r.call(this, params, h) : "";
            },
          };
        } else if (columnSelectedWidget) {
          col.slots = {
            default: "widget",
          };
        } else if (["editDelete", "editButton"].includes(t.formatS)) {
          col.slots = {
            default: t.formatS,
          };
        }

        newColumns.push(col);
      });

      /*if (baseRefUtil.tableConfig && baseRefUtil.tableConfig.className == "list-table") {
        if (tableColumns.length) {
          let tableColumn = [tableColumns.length - 1];
          if (tableColumn.fixed != "right") {
            newColumns.push({
              width: 47,
              title: '',
              fixed: 'right',
              sortable: false,
            });
          }
        }
      }*/
      return newColumns;
    },
    formModel: {
      cache: !1,
      get: function () {
        return this.globalModel.formModel;
      },
    },
    formDataId() {
      let formRef = this.getFormRef();
      return formRef.dataId;
    },
  },
  created: function () {
    if (!this.formModel[this.fieldKeyName])
      this.formModel[this.fieldKeyName] = [];
    this.initRefList();
    this.handleOnCreated();
  },
  mounted: async function () {
    this.handleOnMounted();
    this.initTableList();
  },
  beforeDestroy: function () {
    this.unregisterFromRefList();
  },
  methods: {
    openAdvancedSearchDialog() {
      /*let formData = this.formModel;
      let advancedFormData = {};
      this.vxeOption.searchColumns.forEach(form1Field => {
          let value = formData[form1Field.field];
          if (value !== null && value !== undefined) {
            advancedFormData[form1Field.field] = value
          } else {
            advancedFormData[form1Field.field] = null
          }
      });
      this.advancedFormData = advancedFormData;*/
      this.showAdvancedSearch = true;
    },
    confirmAdvancedSearchDialog() {
      let formModel = this.formModel;
      let advancedFormData = this.advancedFormData;
      this.vxeOption.searchColumns.forEach((form1Field) => {
        let value = formModel[form1Field.field];
        if (value !== null && value !== undefined) {
          advancedFormData[form1Field.field] = value;
        } else {
          advancedFormData[form1Field.field] = null;
        }
      });
      this.searchEvent();
    },
    advancedClear() {
      this.vxeOption.searchColumns.forEach((form1Field) => {
        let widgetRef = this.getWidgetRef(form1Field.widget.options.name);
        if (widgetRef && widgetRef.setValue) widgetRef.setValue(null);
      });
    },
    setValue(val) {
      let rows = val || [];
      this.formModel[this.fieldKeyName] = rows;
      this.fieldModel = rows;
    },
    getValue() {
      return this.formModel[this.fieldKeyName];
    },
    getFieldKeyName(widget) {
      let o = widget.options.name;
      return (widget.options.keyNameEnabled && widget.options.keyName) || o;
    },
    formatterValue: function ({ cellValue, row, column }) {
      if (cellValue === null || cellValue === undefined) return cellValue;
      if (!column.params) return cellValue;

      let value = cellValue;
      const formatS = column.params.formatS;
      const dateFormats = [
        "d1",
        "d2",
        "d3",
        "d4",
        "d5",
        "render",
        "create_date",
        "modify_date",
      ];
      const isColumnLevelUtc =
        !formatS || dateFormats.includes(formatS);
      const utcTransformEnabled = isColumnLevelUtc
        ? !!(
            column.params.utcTransformEnabled ||
            column.params.columnConfig?.utcTransformEnabled
          )
        : false;

      if (utcTransformEnabled && value != null && value !== "") {
        value = this.$utcToLocal(value);
      }

      if (!formatS) {
        return value;
      }

      switch (formatS) {
        case "d1":
          return baseRefUtil.formatUtil.formatDate1(value);
        case "d2":
          return baseRefUtil.formatUtil.formatDate2(value);
        case "d3":
          return baseRefUtil.formatUtil.formatDate3(value);
        case "d4":
          return baseRefUtil.formatUtil.formatDate4(value);
        case "d5":
          return baseRefUtil.formatUtil.formatDate4(value);
        case "n1":
          return baseRefUtil.formatUtil.formatNumber1(value);
        case "n2":
          return baseRefUtil.formatUtil.formatNumber2(value);
        case "n3":
          return baseRefUtil.formatUtil.formatNumber3(value);
        case "n4":
          return baseRefUtil.formatUtil.formatNumber4(value);
        case "n5":
          return baseRefUtil.formatUtil.formatNumber5(value);
        case "n6":
          return baseRefUtil.formatUtil.formatNumber6(value);
        case "n7":
          return baseRefUtil.formatUtil.formatNumber7(value);
      }
      return value;
    },
    searchEvent() {
      // this.getGridTable().commitProxy('reload');
      this.loadAccessData();
    },
    async resetEvent() {
      let formData = this.formModel;
      this.keyword = null;
      this.widget.widgetList &&
        this.widget.widgetList.forEach((subWidget) => {
          let widgetRef = this.getWidgetRef(subWidget.options.name);
          let fieldKeyName = this.getFieldKeyName(subWidget);
          formData[fieldKeyName] = null;
          this.advancedFormData[fieldKeyName] = null;
          if (widgetRef && widgetRef.setValue) widgetRef.setValue(null);
        });
      // this.getGridTable().commitProxy('reload');
      this.loadAccessData();
    },
    openEditDialog(row) {
      let formRef = this.getFormRef();
      let parentTarget = formRef.$attrs["parent-target"];
      parentTarget &&
        parentTarget.$attrs.openEditDialog &&
        parentTarget.$attrs.openEditDialog(row);
    },
    initTableList() {
      let that = this;
      let path = null;
      let paramFun = null;
      let tableRef = this.getTableRef();
      let isQueryTable = this.widget.options.isQueryTable || false;
      let isDataPage = this.widget.options.accessReturnType === "2";
      let isQueryAllPage = !this.widget.options.isNotQueryAllPage;
      let searchColumns = null;
      if (isQueryTable) {
        path = "#";
        paramFun = () => {
          let conditions = this.getSearchCondition();
          if (this.widget.options.showPagination) {
            let searchCount = true;
            if (isQueryAllPage === false) {
              searchCount = false;
            }
            conditions.current = this.page.current;
            conditions.size = this.page.size;
            conditions.searchCount = searchCount;
          }
          return conditions;
        };

        searchColumns = [];
        let widgetList = this.widget.widgetList;
        let typeMap = {
          input: "input",
          number: "number",
          inputBatch: "inputBatch",
          date: "date",
        };

        widgetList.forEach((widget) => {
          if ("container" !== widget.category) {
            let options = widget.options;
            let type = typeMap[widget.type] || null;
            searchColumns.push({
              title: options.label,
              field: this.getFieldKeyName(widget),
              type: type,
              common: true,
              disabled: options.disabled,
              defaultValueEnabled: !!type,
              slot: options.name,
              widget: widget,
              formItem: false,
            });
          }
        });
      }

      let formRef = this.getFormRef();
      let dataTableConfig = formRef.$attrs.dataTableOption || {};
      this.dataTableConfig = dataTableConfig;

      let tableOption = {
        vue: this,
        tableRef: tableRef,
        tableName: this.widget.options.name,
        param: paramFun,
        columns: this.columns,
        searchColumns: searchColumns,
        vform: true,
        config: {
          height: isQueryTable ? "550px" : this.widget.options.tableHeight,
          /*pagerConfig: {
            autoHidden: !this.widget.options.showPagination
          },*/
          ...dataTableConfig.config,
        },
        exportAjax: (param) => {
          let $grid = this.getGridTable();
          let pageSize = param.size;
          let currentPage = param.current;
          let page = { pageSize, currentPage };
          return this.vxeOption.config.proxyConfig.ajax.query.call(this, {
            page,
            param,
          });
        },
      };

      if (isQueryTable) {
        tableOption.path = path;
        tableOption.config.proxyConfig = {
          props: {
            result: isDataPage ? "objx.records" : "objx", // 配置响应结果列表字段
            total: isDataPage ? "objx.total" : "objx.length", // 配置响应结果总页数字段
          },
          ajax: {
            // 接收 Promise 对象
            query: ({ page, sorts, filters, form, param }) => {
              let scriptCode = this.getScriptCode();
              let formData = tableOption.param ? tableOption.param() || {} : {};
              const queryParams = Object.assign({}, formData);

              if (filters) {
                filters.forEach(({ property, values }) => {
                  queryParams[property] = values.join(",");
                });
              }

              if (page.pageSize !== undefined) {
                queryParams.size = page.pageSize;
                queryParams.current = page.currentPage;
              }

              queryParams.searchCount = isQueryAllPage !== false;
              Object.assign(queryParams, param);

              if (that.dataTableConfig.queryParam) {
                Object.assign(queryParams, that.dataTableConfig.queryParam);
              }

              return new Promise((resolve, reject) => {
                let reqData = {
                  ...queryParams,
                };
                if (scriptCode) {
                  let done = (res) => {
                    resolve(res);
                    if (res.type === "success") {
                      let rows = res.objx
                        ? res.objx.records || res.objx || []
                        : [];
                      this.setValue(rows);
                      if (res.objx && res.objx.records !== undefined) {
                        this.page = {
                          current: res.objx.current ?? this.page.current,
                          size: res.objx.size ?? this.page.size,
                          total: res.objx.total ?? 0,
                          records: rows,
                        };
                      }
                      that.$nextTick(() => {
                        setTimeout(function () {
                          dataTableConfig.callback &&
                            dataTableConfig.callback(rows);
                          tableOption.callback && tableOption.callback(rows);
                          that.handleCustomEvent(
                            that.widget.options.formScriptCallback,
                            ["rows"],
                            [rows]
                          );
                        }, 0);
                      });
                    } else {
                      this.page = {
                        current: 1,
                        size: this.pageSize,
                        total: 0,
                        records: [],
                      };
                      this.setValue([]);
                    }
                  };
                  this.loadDefaultQueryList(reqData, done).catch((error) => {
                    reject(error);
                  });
                } else {
                  resolve();
                }
              });
            },
          },
        };
        tableOption.callback = (rows) => {
          // this.fieldModel = rows;
          this.formModel[this.fieldKeyName] = rows;
        };
      }
      this.vxeOption = tableOption;
      this.loadAccessData();

      /*this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
        /!*if (!isQueryTable) {
          this.$nextTick(() => {
            this.loadAccessData();
          });
        }*!/
      });
      if (!isQueryTable) {
        this.loadAccessData();
      }*/
    },
    getTableCondition() {
      if (this.widget.options.tableCondition) {
        let e = new Function(this.widget.options.tableCondition);
        return e.call(this);
      }
    },
    getSearchCondition() {
      // let extraAccessData = this.extraAccessData || {};
      let searchFormData = this.getSearchFormData();
      let conditions = {
        // ...this.getTableCondition(),
        ...searchFormData,
        // ...this.advancedFormData,
        // ...extraAccessData,
      };
      if (this.keyword) {
        conditions.keyword = this.keyword;
      }
      return conditions;
    },
    getSearchFormData() {
      let map = { condition: [] };
      let formData = this.globalModel.formModel;
      let widgetList = this.widget.widgetList;
      if (!!widgetList && widgetList.length > 0) {
        let loop = (wItem) => {
          if (wItem.category === "container") {
            loop(wItem);
          } else {
            let formField = this.getFieldKeyName(wItem);
            let vaule = formData[formField];
            if (vaule !== null && vaule !== undefined && vaule !== "") {
              if (!Array.isArray(vaule) || vaule.length > 0) {
                let item = {
                  value: vaule,
                  field: formField,
                  filter: null,
                };
                let wType = wItem.type;
                if (["date-range", "time-range"].includes(wType)) {
                  item.filter = "between";
                } else if (
                  ["input-batch", "checkbox"].includes(wType) ||
                  (wType === "select" && wItem.options.multiple)
                ) {
                  item.filter = "in";
                } else if (
                  ["radio", "time", "date"].includes(wType) ||
                  (wType === "select" && !wItem.options.multiple)
                ) {
                  item.filter = "eq";
                } else {
                  item.filter = "like";
                }
                map.condition.push(item);
              }
            }
          }
        };
        widgetList.forEach((wItem) => {
          loop(wItem);
        });
      }
      return map;
    },
    loadTableData(param) {
      if (this.dataTableConfig?.queryFormDialog !== true) {
        this.checkItemIds = [];
      }
      param = param || {};
      let pageSize = param.size || this.pageSize;
      let currentPage = param.current || 1;
      let page = { pageSize, currentPage };
      return this.vxeOption.config.proxyConfig.ajax.query.call(this, {
        page,
        param,
      });
    },
    loadAccessData() {
      let isQueryTable = this.widget.options.isQueryTable || false;
      if (isQueryTable) {
        this.loadTableData({});
        return;
      }
      if (!isQueryTable && !this.formDataId) return;

      let scriptCode = this.getScriptCode();
      if (scriptCode) {
        this.loadDefaultViewList();
      }
    },
    getAccessParam() {
      if (!this.widget.options.formScriptParam) return;
      return this.handleCustomEvent(this.widget.options.formScriptParam);
    },
    getScriptCode() {
      let accessReturnType = this.widget.options.accessReturnType;
      let defaultScriptCode = "getList";
      if (accessReturnType === "1") {
        defaultScriptCode = "getList";
      } else if (accessReturnType === "2") {
        defaultScriptCode = "getPage";
      }
      return this.widget.options.formScriptCode || defaultScriptCode;
    },
    getAttachmentType() {
      let result = [];
      let tableColumns = this.widget.options.tableColumns || [];
      tableColumns.forEach((item) => {
        if (item.prop && item.label && item.formatS === "editAttachment") {
          result.push(item.prop);
        }
      });
      return result;
    },
    getHttpConfigForUser() {
      return {
        addCreateInfo: true,
        queryCreateInfo: window.$vueRoot.$store.getters.queryCreateInfo || "0",
      };
    },
    loadDefaultQueryList(reqData, done) {
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let scriptCode = this.getScriptCode();
      let accessParam = this.getAccessParam() || {};
      let otherParam = {};
      let attachmentType = this.getAttachmentType();
      if (attachmentType.length) {
        otherParam.attachmentType = attachmentType;
      }
      let defaultOption = this.getHttpConfigForUser();
      let requestData = {
        ...reqData,
        ...otherParam,
      };
      requestData = extendDeeply(requestData, accessParam);
      return this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          taBm: this.fieldKeyName,
          data: requestData,
        },
        isLoading: false,
        ...defaultOption,
        callback: (res) => {
          done(res);
        },
      });
    },
    loadDefaultViewList() {
      let dataId = this.formDataId;
      let reportTemplate = this.getFormRef().reportTemplate;
      let formCode = reportTemplate.formCode;
      let accessParam = this.getAccessParam() || {};
      let otherParam = {};
      let attachmentType = this.getAttachmentType();
      if (attachmentType.length) {
        otherParam.attachmentType = attachmentType;
      }
      let scriptCode = this.getScriptCode();
      return this.formHttp({
        scriptCode: scriptCode,
        data: {
          formCode: formCode,
          formVersion: reportTemplate.formVersion,
          taBm: this.fieldKeyName,
          data: {
            id: dataId,
            ...otherParam,
            ...accessParam,
          },
        },
        callback: (res) => {
          let rows = res.objx ? res.objx.records || res.objx || [] : [];
          this.setValue(rows);
          this.handleCustomEvent(
            this.widget.options.formScriptCallback,
            ["rows"],
            [rows]
          );
        },
      });
    },
    getReqParam(item, dataId, billData) {
      let param = {};
      if (item.accessParam) {
        if (typeof item.accessParam === "string") {
          let n = new Function("billData", item.accessParam);
          param = n.call(this, billData);
        } else {
          param = item.accessParam;
        }
      } else {
        param = { id: dataId };
      }
      return param;
    },
    async deleteRow(row, rowIndex) {
      this.fieldModel.splice(rowIndex, 1);
    },
    createNewTableData() {
      let vailColumns = this.widget.options.tableColumns.filter(
        (item) => item.prop && item.label
      );
      let newData = {};
      vailColumns.forEach((item) => {
        if (item.formatS == "editSearch") {
          newData[item.prop] = null;
          let vabSearchName = item?.columnOption?.vabSearchName;
          if (vabSearchName) newData[vabSearchName] = null;
        } else {
          newData[item.prop] = null;
        }
      });
      return newData;
    },
    addTableData(rows, field) {
      let formDataModel = this.formModel;
      let tableRows = this.fieldModel;
      let fullData = this.fieldModel;
      let items;
      if (field) {
        let keys = fullData.map((item) => {
          return item[field] + "";
        });
        items = rows.filter((item) => {
          let value = item[field] + "";
          return !keys.includes(value);
        });
      } else {
        items = rows;
      }
      if (items) {
        if (items.length) {
          items.forEach((row) => {
            let newData = this.createNewTableData();
            Object.assign(newData, row);

            tableRows.push(newData);
          });
        }
      } else {
        let newData = this.createNewTableData();
        tableRows.push(newData);
      }
      // this.formModel[this.fieldKeyName] = this.$baseLodash(this.fieldModel)
      // this.fieldModel = tableRows
      // $grid.loadData(tableRows);
    },
    getColumnWidgetConfig(row) {
      let formRef = this.getFormRef();
      let formatS = row.formatS;
      let columnSelectedWidget = null;
      let columnEditFields = null;

      let type = this.columnFormatMap[row.formatS];

      if (type) {
        columnSelectedWidget = this.$baseLodash.cloneDeep(
          formRef.getFieldWidgetByType(type)
        );
        let tmpId = generateId();
        let idVal = row.prop ? row.prop : type + tmpId;
        columnSelectedWidget.id = idVal;
        columnSelectedWidget.options.name = idVal;
        if (row.columnOption && Object.keys(row.columnOption).length) {
          row.columnOption.required = row.required || false;
          columnSelectedWidget.options = row.columnOption;
        } else {
          columnSelectedWidget.options.required = row.required || false;
          row.columnOption = columnSelectedWidget.options;
        }
        columnSelectedWidget.options.name = row.prop;
        columnSelectedWidget.options.label = row.label;
        columnSelectedWidget.options.labelHidden = true;
      }
      return { columnSelectedWidget, columnEditFields };
    },
    getColumnProp(widget, obj) {
      let isQueryTable = this.widget.options.isQueryTable || false;
      if (isQueryTable) {
        return "false";
      } else {
        let propName =
          this.getFieldKeyName(widget) +
          "." +
          obj.rowIndex +
          "." +
          obj.column.field;
        if (this.isVabsearchFlagWidget(widget)) {
          let vabSearchName = obj.column.params.widget.options.vabSearchName;
          propName =
            this.getFieldKeyName(widget) +
            "." +
            obj.rowIndex +
            "." +
            vabSearchName;
        }
        return propName;
      }
    },
    isVabsearchFlagWidget(widget) {
      let type = widget?.type;
      return (
        type === "vabsearch" ||
        type === "singerSearch" ||
        type === "multiSearch"
      );
    },
    getColumnWidgetName(e) {
      if (e && e.type) {
        return e.type + "-widget";
      }
    },
    getGridTable() {
      let $grid = this.$refs[this.getTableRef()];
      return $grid;
    },
    getTableRef() {
      let tableRef = this.widget.id;
      return tableRef;
    },
    getUrl() {
      let accessUrl = this.widget.options.accessUrl;
      return accessUrl || USER_PREFIX + `/form_ins/getFormInsData`;
    },
    openRowDetailDialog(row) {
      /*let isQueryTable = this.widget.options.isQueryTable || false;
      if(isQueryTable)return;*/
      this.editRow = row;
      this.showRowDetailDialog = true;
    },
    changePageNew({ type, currentPage, pageSize, $event }) {
      this.loadTableData({
        size: pageSize + "",
        current: currentPage + "",
      });
    },
    exportData(option) {
      let tableRef = this.getTableRef();
      let serverName = this.getFormRef().reportTemplate.serverName;
      option.prefix = option.prefix || serverName;
      this.$excelExport({ targetRef: tableRef, ...option });
    },
    itemCheck(row) {
      let dataTableConfig = this.dataTableConfig;
      if (dataTableConfig) {
        let checkItemIds = this.checkItemIds;
        let checked;
        if (checkItemIds.includes(row.id)) {
          checked = false;
          checkItemIds.splice(checkItemIds.indexOf(row.id), 1);
        } else {
          checked = true;
          checkItemIds.push(row.id);
        }
        let param = { row, checked };
        dataTableConfig.onCheckboxChange &&
          dataTableConfig.onCheckboxChange(param);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
