<template>
  <el-dialog
    :visible.sync="showDialog"
    v-el-drag-dialog
    v-el-dialog-center
    v-bind="dialogConfig"
    @close="close"
  >
    <div class="cont" style="height: 450px" v-bind="bodyConfig">
      <v-form-render
        :form-json.sync="formJson"
        :form-data="formData"
        :option-data="optionData"
        ref="vFormRef"
        :reportTemplate.sync="formTemplate"
        :conditionParam.sync="conditionParam"
        :formInsData.sync="formInsData"
        v-if="showRender"
        visible-key="showRender"
        :parent-target="_self"
        @reload="reload"
        :dataTableOption="dataTableOption"
        v-bind="formConfig"
        :param="dialogParam"
        class="data-table_height labMargin"
      />
    </div>
    <label id="labBtn" class="transverse">
      <div class="icon">
        <i class="el-icon-more"></i>
        <i class="el-icon-more"></i>
      </div>
    </label>
    <div class="multipleChoice">
      <el-tooltip
        :enterable="false"
        effect="dark"
        :content="$t1('全部删除')"
        placement="top"
        ><a class="allDel icon-quanbushanchu" @click="clearChecked()"></a>
      </el-tooltip>
      <div class="list">
        <template v-if="showRender">
          <div class="item" v-for="(checkRow, index) in checkRows" :key="'c' + index">
            <p>{{ checkRow[showFormField] }}</p>
            <a class="el-icon-close" @click="clearTable1Select(index)"></a>
          </div>
        </template>
      </div>
    </div>
    <span
      slot="footer"
      class="dialog-footer"
      v-if="option.showFooter !== false"
      v-bind="option.footerConfig"
    >
      <span class="fl tips" v-if="!selectMulti">{{
        $t1("注：双击确认选择（单选）")
      }}</span>
      <el-button type="primary" plain class="button-sty" @click="close">
        <i class="el-icon-close el-icon"></i>
        {{ $t1("取 消") }}
      </el-button>
      <el-button type="primary" @click="dialogSubmit" class="button-sty">
        <i class="el-icon-check el-icon"></i>
        {{ $t1("确 定") }}
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import { selectDialogMixins } from "../../../../../mixins/selectDialog/index.js";
import VFormRender from "../../../../../components/xform/form-render/index.vue";
import { traverseAllWidgetsNew } from "../../../../../components/xform/utils/util";

export default {
  // name: "vabSearchDialog",
  components: { VFormRender },
  props: ["visiable", "multi", "rows", "param", "widget", "option"],
  mixins: [selectDialogMixins],
  inject: ["getFormConfig"],
  mounted() {},
  data() {
    var that = this;
    return {
      showFormField: "_tt",
      showDialog: true,
      falseValue: false,
      selectMulti: true,

      formJson: {},
      formData: {},
      optionData: {},
      showRender: false,
      formTemplate: {},
      /*      formCode: null,*/
      layoutType: null,
      conditionParam: null,
      formInsData: null,
      dataTableOption: {
        class: "is-pointer",
        queryFormDialog: true,
        onCheckboxChange: (param) => {
          if (this.currentLayoutType == "H5") {
            this.changeH5Checkbox(param);
          } else {
            this.addDataTable(param);
          }
        },
        onCheckboxAll: (param) => {
          this.checkAll(param);
        },
        onCellDblclick: (param) => {
          this.checkWithSubmit(param);
        },
        callback: () => {
          if (this.checkRows.length) {
            let $grid = this.getGrid();
            let datas = $grid.getTableData().tableData;
            let fieldKey = this.fieldKey;
            this.checkRows.forEach((checkRow) => {
              let row = datas.find(
                (row) => row[fieldKey] == checkRow[fieldKey]
              );
              if (row) {
                $grid.setCheckboxRow(row, true);
              }
            });
          }
        },
        otherConfig: {
          onFilter: () => {
            this.checkRows = [];
          },
        },
        config: {
          checkboxConfig: {
            checkStrictly: true,
            showHeader: true,
            trigger: "row",
          },
        },
      },
      $grid: null,
      currentLayoutType: null,
    };
  },
  computed: {
    formCode() {
      return this.option.formCode;
    },
    dialogParam() {
      return this.option?.param;
    },
    formConfig() {
      return this.option?.formConfig;
    },
    dialogConfig() {
      let customClass = "dialog-style list-dialog dialog-checkbox pd_0";
      if (this.option.dialogConfig?.customClass) {
        customClass = customClass + " " + this.option.dialogConfig.customClass;
      }
      let config = {
        title: this.formTemplate.formName,
        appendToBody: true,
        modalAppendToBody: true,
        closeOnClickModal: false,
        modal: false,
        width: "1200px",
        fullscreen: this.option.fullscreen,
      };
      config = Object.assign({}, config, this.option.dialogConfig, {
        customClass,
      });
      config.title = this.$t1(config.title);
      return config;
    },
    bodyConfig() {
      let config = {};
      let classStr = this.currentLayoutType;
      if (this.option.bodyConfig?.class) {
        classStr = classStr + " " + this.option.bodyConfig.class;
      }
      if (this.option.showFooter == false) {
        classStr = classStr + " nfootBtn";
      }
      config = Object.assign({}, config, this.option.bodyConfig, {
        class: classStr,
      });
      return config;
    },
  },
  created() {
    let currentFormConfig = this.getFormConfig();
    this.currentLayoutType = currentFormConfig.layoutType;
    this.initSetting();

    if (this.option.rows?.length) {
      this.checkRows.push(...this.$baseLodash.cloneDeep(this.option.rows));
    }

    this.selectMulti = this.option.multiple ?? true;
    this.dataTableOption.config.checkboxConfig.showHeader = this.selectMulti;
    if (this.option.queryParam) {
      this.dataTableOption.queryParam = this.option.queryParam;
    }
    this.getReportTemplate();
  },
  methods: {
    reload() {
      this.showRender = false;
      this.getReportTemplate();
    },
    async getReportTemplate() {
      let param = {
        objTypeCode: this.$attrs.objTypeCode,
        objId: this.$attrs.objId,
        taskId: this.$attrs.taskId,
      };
      this.conditionParam = param;
      let url, data;
      url = USER_PREFIX + `/formTemplate/getByFormCode`;
      data = { stringOne: this.formCode };

      let that = this;
      this.$http({
        url: url,
        method: `post`,
        data: data,
        isLoading: true,
        loadingTarget: document.body,
        modalStrictly: true,
        success: (res) => {
          let formTemplate = res.objx || {};
          this.formTemplate = formTemplate;
          this.formJson = formTemplate.formViewContent
            ? JSON.parse(formTemplate.formViewContent)
            : {};
          this.layoutType = this.formJson.formConfig.layoutType;
          let formConfig = this.formJson.formConfig;
          if (this.option.fieldKey) {
            this.fieldKey = this.option.fieldKey;
          } else if (formConfig.searchDialogUniqueField) {
            this.fieldKey = formConfig.searchDialogUniqueField;
          }
          /*this.$nextTick(() => {
            let widgetList = this.formJson.widgetList;
            setTimeout(()=>{
              this.$grid = this.$refs.vFormRef.getWidgetRef(widgetList[0].options.name).getGridTable();
            },200)
          })*/
          this.initShowFormField();
          this.showRender = true;
        },
      });
    },
    getDataTableWidget() {
      let result = null;
      traverseAllWidgetsNew(this.formJson.widgetList, (widget) => {
        //修复data-table旧数据表格列widget与editWidget为空的问题
        if (!result && widget.type == "data-table") {
          result = widget;
        }
      });
      return result;
    },
    getGrid() {
      if (!this.$grid) {
        // let widgetList = this.formJson.widgetList;
        let dataTableWidget = this.getDataTableWidget();
        this.$grid = this.$refs.vFormRef
          .getWidgetRef(dataTableWidget.options.name)
          .getGridTable();
      }
      return this.$grid;
    },
    initShowFormField() {
      let showFormField =
        this.formJson.formConfig.searchDialogNameField || null;
      if (!showFormField) {
        // let widgetList = this.formJson.widgetList;
        let dataTableWidget = this.getDataTableWidget();
        let tableColumns = dataTableWidget.options.tableColumns;
        let column = tableColumns.find((column) => !!column.prop);
        this.showFormField = column.prop;
      } else {
        this.showFormField = showFormField;
      }
    },
    async getFormInsData() {
      let formTemplate = this.formTemplate;
      let insUuid = formTemplate.insUuid;
      let formConfig = this.formJson.formConfig;
      let isSystemBill = formConfig.formType == 1;
      return this.$http({
        url: USER_PREFIX + `/form_ins/getFormInsData`,
        method: `post`,
        data: {
          insUuid: insUuid,
          tableAlias: this.formCode,
        },
        isLoading: true,
        loadingTarget: document.body,
        modalStrictly: true,
        success: (res) => {
          let formData = res.objx && res.objx.data ? res.objx.data : {};
          this.formData = formData;
          this.formInsData = res.objx;
          // this.formInsData = formData;
        },
      });
    },
    changeH5Checkbox(obj) {
      let fieldKey = this.fieldKey;
      let selectMulti = this.selectMulti;
      let row = obj.row;
      let that = this;
      if (selectMulti) {
        let rows = this.checkRows;
        if (obj.checked) {
          let flag = rows.some((item) => {
            return row[fieldKey] == item[fieldKey];
          });
          if (!flag) {
            rows.push(obj.row);
          }
        } else {
          let rowid = obj.row[fieldKey];
          let delIndex;
          for (var i = 0; i < rows.length; i++) {
            if (rows[i][fieldKey] == rowid) {
              delIndex = i;
              break;
            }
          }
          if (delIndex != null) rows.splice(delIndex, 1);
        }
      } else {
        this.checkRows = [];
        this.checkRows.push(obj.row);
      }
    },
    addDataTable(obj) {
      let fieldKey = this.fieldKey;
      let selectMulti = this.selectMulti;
      let row = obj.row;
      let that = this;
      let $table1 = obj.$table;
      if (selectMulti) {
        let rows = this.checkRows;
        if (obj.checked) {
          let flag = rows.some((item) => {
            return row[fieldKey] == item[fieldKey];
          });
          if (!flag) {
            rows.push(obj.row);
          }
        } else {
          let rowid = obj.row[fieldKey];
          let delIndex;
          for (var i = 0; i < rows.length; i++) {
            if (rows[i][fieldKey] == rowid) {
              delIndex = i;
              break;
            }
          }
          if (delIndex != null) rows.splice(delIndex, 1);
        }
      } else {
        $table1.clearCheckboxRow();
        $table1.setCheckboxRow(obj.row, true);
        this.checkRows = [];
        this.checkRows.push(obj.row);
      }

      if (obj.checked) {
        // let ay = $table1.getTableData().fullData;
        // let aRows = this.findAllRows(ay);
        let aRows = $table1.getTableData().visibleData;
        let cRows = $table1.getCheckboxRecords();
        if (aRows.length == cRows.length) {
          $table1.setAllCheckboxRow(true);
        } else {
          $table1.setAllCheckboxRow(false);
        }
      } else {
        $table1.setAllCheckboxRow(false);
      }
    },
    clearTable1Select(index) {
      if (this.currentLayoutType == "H5") {
        this.checkRows.splice(index, 1);
      } else {
        let fieldKey = this.fieldKey;
        let selectMulti = this.selectMulti;
        let row = this.checkRows[index];
        var rowid = row[fieldKey];
        let $grid1 = this.getGrid();

        // let rows = $grid1.getTableData().fullData;
        let rows = $grid1.getTableData().visibleData;
        let row2 = this.findTreeRowById(rows, rowid);
        if (selectMulti) {
          if (row2) $grid1.setCheckboxRow(row2, false);
        } else {
          $grid1.clearCheckboxRow();
        }
        this.checkRows.splice(index, 1);
        if (row2) $grid1.setAllCheckboxRow(false);
      }
    },
    checkAll(res) {
      if (this.currentLayoutType !== "H5") {
        let fieldKey = this.fieldKey;
        var $grid = res.$grid;
        // let tableData = $grid.getTableData().fullData;
        // let allRows = this.findAllRows(tableData);
        let tableData = $grid.getTableData().visibleData;
        let allRows = $grid.getTableData().visibleData;
        $grid.setCheckboxRow(allRows, res.checked);
        allRows.forEach((lineData) => {
          let rowid = lineData[fieldKey];
          let tableData2 = this.checkRows;
          let row2;
          for (var i = 0; i < tableData2.length; i++) {
            let lineData2 = tableData2[i];
            if (lineData2[fieldKey] == rowid) {
              row2 = tableData2[i];
            }
          }
          if (res.checked) {
            if (!row2) {
              this.checkRows.push(lineData);
            }
          } else {
            if (row2) {
              let delIndex;
              let checkRows = this.checkRows;
              for (var i = 0; i < checkRows.length; i++) {
                if (checkRows[i][fieldKey] == rowid) {
                  delIndex = i;
                  break;
                }
              }
              if (delIndex != null) checkRows.splice(delIndex, 1);
            }
          }
        });
      }
    },
    clearChecked() {
      if (this.currentLayoutType !== "H5") {
        let $grid1 = this.getGrid();
        $grid1.clearCheckboxRow();
      }
      this.checkRows = [];
    },
    checkWithSubmit(obj) {
      if (!this.selectMulti) {
        let $grid1 = this.getGrid();
        var rows = $grid1.getCheckboxRecords(true);
        if (rows && rows.length) {
          this.dialogSubmit();
        }
      }
    },
    close() {
      let formRef = this.$refs.vFormRef;
      this.showDialog = false;
      this.$emit("update:visiable", false);
      this.option.close && this.option.close(formRef, this);
    },
    dialogSubmit() {
      let formRef = this.$refs.vFormRef;
      if (this.option.confirm) {
        if (this.option.confirm(this.checkRows, formRef, this) !== false) {
          this.close();
        }
      } else {
        this.close();
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .H5 .h5-fixed-bottom-btns {
  bottom: 95px;
}
::v-deep .tree-container {
  height: 100%;
  .tree-box {
    width: 14%;
    height: 100%;
    min-width: 13%;
    border-right: solid 1px #f0f0f0;
    .container-wrapper {
      height: calc(100% - 34px);
      > div {
        height: 100%;
      }
    }
    .tree-btns + .tree-list {
      height: calc(100% - 41px);
    }
  }
  .main-right {
    width: calc(86% - 8px);
    height: 100%;
  }
  .grid-height {
    height: 100% !important;
  }
  #labBtn {
    background-color: #f4f6fa;
    position: relative;
    width: 8px !important;
    z-index: 8;
    cursor: e-resize;
    display: inline-block !important;
    height: calc(100% + 8px);
    margin: -8px 0px !important;
    .icon {
      position: absolute;
      top: 50%;
      left: -4.5px;
      font-size: 17px;
      margin-top: -16.8px;
      color: #2a6494;
      i {
        display: block;
        transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -webkit-transform: rotate(90deg);
        -o-transform: rotate(90deg);
      }
    }
  }
}
::v-deep .labMargin .tree-container {
  display: flex;
}
/* ::v-deep .tree-container #labBtn {
      background-color: #f4f6fa;
      position: relative;
      width: 8px !important;
      z-index: 8;
      cursor: e-resize;
      display: inline-block !important;
      height: calc(100vh - 75px);
      margin: -7px 0 !important;
} */
</style>
