<template>
  <div>
    <div class="search-box">
      <div style="display: flex; justify-content: space-between">
        <h4 class="cap">查询条件</h4>
        <el-button type="text" @click="isFieldShow = true">查询字段配置</el-button>
      </div>
      <vxe-modal v-model="isFieldShow" title="设置查询字段" height="80%">
        <el-table :data="searchOptions" class="JNPF-common-table" ref="searchTable" height="calc(100% - 50px)">
          <el-table-column prop="__config__.label" label="查询条件" />
          <el-table-column type="selection" width="55" align="center" />
        </el-table>
        <div style="display: flex; justify-content: end; margin-top: 10px">
          <el-button size="mini" @click="isFieldShow = false">取消</el-button>
          <el-button size="mini" @click="searchSelectionChange">保存</el-button>
        </div>
      </vxe-modal>
      <ColumnFilter @onAddSearchChange="SearchFilterChange" ref="ColumnFilter" v-if="setSeachFlag"></ColumnFilter>
      <vxe-table border size="small" :row-config="{ useKey: true }" :scroll-y="{ enabled: false }" :data="columnData.searchList" class="JNPF-common-table" ref="dragTableSearch">
        <vxe-column width="60">
          <template #default>
            <span class="drag-btn">
              <i class="drag-handler icon-ym icon-ym-darg" style="cursor: move; font-size: 20px" title="点击拖动" />
            </span>
          </template>
          <template #header>
            <el-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
              <i class="vxe-icon-question-circle-fill" @click="showHelpTip1 = !showHelpTip1"></i>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="__config__.label" title="列名" />
        <vxe-column field="__vModelName__" title="字段" />
        <vxe-column field="searchType" title="类型">
          <template slot-scope="scope">
            <!--              {{scope.row.searchType===3?'范围查询':scope.row.searchType===2?'模糊查询':'等于查询'}}-->
            <el-button @click="setSeachClick(scope.row)" plain size="mini"> 搜索设置 </el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <el-divider style="margin: 5px">表格配置</el-divider>
    <div class="column-box">
      <div class="flex flex-center" style="gap: 10px; margin-bottom: 5px; justify-content: space-between">
        <h4 class="cap">列表字段</h4>
        <el-button type="text" size="mini" @click="isGridStyleVisible = true">设置表格样式</el-button>
      </div>
      <vxe-modal v-model="isGridStyleVisible" width="40%" title="设置表格样式" show-footer>
        <el-form size="small" label-width="120px">
          <el-form-item label="表头背景色">
            <el-color-picker v-model="columnData.gridStyle.headerBackgroundColor" show-alpha :predefine="predefineColors"></el-color-picker>
          </el-form-item>
          <el-form-item label="表头字体大小">
            <el-input-number v-model="columnData.gridStyle.headerFontSize" :min="12" :precision="0" />
          </el-form-item>
          <el-form-item label="表头字体颜色">
            <el-color-picker v-model="columnData.gridStyle.headerFontColor" show-alpha :predefine="predefineColors"></el-color-picker>
          </el-form-item>
          <el-form-item label="内容区字体大小">
            <el-input-number v-model="columnData.gridStyle.bodyFontSize" :min="12" :precision="0" />
          </el-form-item>
        </el-form>
      </vxe-modal>
      <vxe-table
        border
        size="small"
        ref="xTable1"
        :row-config="{ useKey: true }"
        :tree-config="{ children: 'children' }"
        :scroll-y="{ enabled: false }"
        :data="columnData.columnList"
        :row-style="rowStyle"
      >
        <vxe-column width="60">
          <template #default>
            <span class="drag-btn">
              <i class="drag-handler icon-ym icon-ym-darg" style="cursor: move; font-size: 20px" title="点击拖动" />
            </span>
          </template>
          <template #header>
            <el-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
              <i class="vxe-icon-question-circle-fill" @click="showHelpTip1 = !showHelpTip1"></i>
            </el-tooltip>
          </template>
        </vxe-column>
        <vxe-column field="label" title="列名" tree-node />
        <vxe-column field="prop" title="字段" />
        <vxe-column field="visible" title="显示" width="90">
          <template #header> <vxe-checkbox v-model="visibleCheck" size="mini">显示</vxe-checkbox></template>
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.visible" @change="visibleCheckChange(scope)" />
          </template>
        </vxe-column>
        <!--        <vxe-column field="visible" title="移动端显示" width="90">-->
        <!--          <template #header> <vxe-checkbox v-model="mobileVisibleCheck" size="mini">移动端显示</vxe-checkbox></template>-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-checkbox v-model="scope.row.mobileVisible" />-->
        <!--          </template>-->
        <!--        </vxe-column>-->
        <vxe-column field="sortable" title="排序" width="90">
          <template #header> <vxe-checkbox v-model="sortCheck" size="mini">排序</vxe-checkbox></template>
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.sortable" />
          </template>
        </vxe-column>
        <vxe-column field="showSummary" title="合计" width="60">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.showSummary" />
          </template>
        </vxe-column>
        <vxe-column field="align" title="对齐">
          <template slot-scope="scope">
            <el-select v-model="scope.row.align" placeholder="请选择">
              <el-option v-for="item in alignOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
            </el-select>
          </template>
        </vxe-column>
        <vxe-column field="width" title="宽度">
          <template slot-scope="scope">
            <el-input-number size="mini" v-model="scope.row.width" placeholder="宽度" :min="0" :precision="0" controls-position="right" />
            <div>
              <el-checkbox v-model="scope.row.widthAuto">自适应</el-checkbox>
            </div>
          </template>
        </vxe-column>
        <vxe-column title="高级设置">
          <template slot-scope="scope">
            <el-button @click="setColor(scope.row)">色阶设置{{ scope.row?.colorScale?.isColorShow ? '(已设置)' : '' }}</el-button>
          </template>
        </vxe-column>
        <!--          <vxe-column field="width" title="关联表单">-->
        <!--            <template slot-scope="{ row, rowIndex }">-->
        <!--              <el-input :value="row.config.associatedFrom ? row.config.associatedFrom.fullName : ''" @focus="focusEvent(row, rowIndex)" suffix-icon="vxe-icon-flow-branch" placeholder="请选择"> </el-input>-->
        <!--            </template>-->
        <!--          </vxe-column>-->
      </vxe-table>
      <vxe-modal v-if="isColorVisible" v-model="isColorVisible" title="色阶设置">
        <el-form size="mini">
          <el-form-item label="是否开启">
            <el-switch v-model="fieldFormSet.colorScale.isColorShow"></el-switch>
          </el-form-item>
          <template v-if="fieldFormSet.colorScale.isColorShow">
            <div class="flex" style="margin-bottom: 10px; gap: 10px" v-for="(item, index) in fieldFormSet.colorScale.colorArr">
              <el-input v-model="item.text"></el-input>
              <el-color-picker v-model="item.color" show-alpha :predefine="predefineColors"> </el-color-picker>
              <el-button size="mini" type="text" @click="delColorArr(fieldFormSet.colorScale.colorArr, index)">X</el-button>
            </div>
            <el-button size="mini" @click="addColorArr(fieldFormSet.colorScale)">新增</el-button>
          </template>
          <el-button size="mini" @click="addColor(fieldForm)">确定</el-button>
        </el-form>
      </vxe-modal>
    </div>
  </div>
</template>
<script>
import Sortable from 'sortablejs'

export default {
  name: 'scene',
  props: {
    columnData: {
      type: Object,
      default: () => {}
    },
    searchOptions: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      sceneIndex: -1,
      predefineColors: ['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585'],
      showHelpTip1: false,
      visibleCheck: false,
      mobileVisibleCheck: false,
      sortCheck: false,
      isFieldShow: false,
      setSeachFlag: false,
      isGridStyleVisible: false,
      alignOptions: [
        {
          value: 'left',
          label: '左对齐'
        },
        {
          value: 'center',
          label: '居中'
        },
        {
          value: 'right',
          label: '右对齐'
        }
      ],

      fieldForm: {
        isColorShow: false
      },
      fieldFormSet: {
        isColorShow: false
      },
      // 色阶设置
      isColorVisible: false
    }
  },
  watch: {
    isFieldShow(val) {
      if (val) {
        this.$nextTick(() => {
          this.searchOptions.forEach((item) => {
            const searchList = this.columnData.searchList.find((v) => v.__vModel__ === item.__vModel__)
            if (searchList) {
              this.$refs.searchTable.toggleRowSelection(item)
            }
          })
        })
      } else {
        this.$refs.searchTable.clearSelection()
      }
    },
    visibleCheck(val) {
      if (val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.visible = true
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
      if (!val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.visible = false
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
    },
    mobileVisibleCheck(val) {
      if (val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.mobileVisible = true
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
      if (!val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.mobileVisible = false
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
    },
    sortCheck(val) {
      if (val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.sortable = true
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
      if (!val) {
        const columnList = g.T.toTable(this.columnData.columnList, 'children').map((item) => {
          item.sortable = false
          return item
        })
        this.columnData.columnList = g.T.toTree(columnList, 'children', '_ID', '_PID')
      }
    }
  },
  mounted() {
    this.rowDrop()
    this.filterDrop()
  },
  methods: {
    searchSelectionChange(val) {
      if (this.sceneIndex > -1) {
        this.scenes[this.sceneIndex].searchList = this.$refs.searchTable.selection
        this.columnData.searchList = this.scenes[this.sceneIndex].searchList
      } else {
        this.columnData.masterScenes.searchList = this.$refs.searchTable.selection
        this.columnData.searchList = this.$refs.searchTable.selection
      }
      this.isFieldShow = false
    },
    rowStyle({ row }) {
      const colorList = ['#ff4500', '#ff8c00', '#ffd700', '#90ee90', '#00ced1', '#1e90ff', '#c71585']
      if (this?.columnData?.joinList) {
        const tableList = g.removeRepeatAttr(this.columnData.joinList.map((v) => v.config.tableName))
        const obj = {}
        tableList.forEach((v, index) => {
          obj[v] = colorList[index]
        })
        if (row?.config?.tableName && obj[row?.config?.tableName]) {
          return {
            // backgroundColor: obj[row?.config?.tableName],
            color: obj[row?.config?.tableName]
          }
        }
      }
    },
    setSeachClick(row) {
      this.setSeachFlag = true //

      this.$nextTick(() => {
        this.$refs.ColumnFilter.onFilterEdit(row)
      })
    },
    SearchFilterChange(val) {
      this.columnData.searchList.forEach((item) => {
        if (item.__vModel__ === this.selectSearchId) {
          item['value-format'] = val['dateFormat']
          item.format = val.format
          item.type = val.dateType
          item.dateType = val.dateType
          item.value = val.conditions[0].values ? (val.conditions[0].values[0] !== 'Invalid date' ? val.conditions[0].values : null) : null
          item.function = val.conditions[0].function
        }
      })
    },
    filterDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.dragTableSearch
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ newIndex, oldIndex }) => {
            const currRow = this.columnData.searchList.splice(oldIndex, 1)[0]
            this.columnData.searchList.splice(newIndex, 0, currRow)
          }
        })
      })
    },
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable1
        this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
          handle: '.drag-btn',
          onEnd: ({ item, oldIndex }) => {
            const options = { children: 'children' }
            const targetTrElem = item
            const wrapperElem = targetTrElem.parentNode
            const prevTrElem = targetTrElem.previousElementSibling
            const tableTreeData = this.columnData.columnList
            const selfRow = xTable.getRowNode(targetTrElem).item
            const selfNode = XEUtils.findTree(tableTreeData, (row) => row === selfRow, options)
            if (prevTrElem) {
              // 移动到节点
              const prevRow = xTable.getRowNode(prevTrElem).item
              const prevNode = XEUtils.findTree(tableTreeData, (row) => row === prevRow, options)
              if (XEUtils.findTree(selfRow[options.children], (row) => prevRow === row, options)) {
                // 错误的移动
                const oldTrElem = wrapperElem.children[oldIndex]
                wrapperElem.insertBefore(targetTrElem, oldTrElem)
                return this.message({ content: '不允许自己给自己拖动！', status: 'error' })
              }
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              if (xTable.isTreeExpandByRow(prevRow)) {
                // 移动到当前的子节点
                prevRow[options.children].splice(0, 0, currRow)
              } else {
                // 移动到相邻节点
                prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
              }
            } else {
              // 移动到第一行
              const currRow = selfNode.items.splice(selfNode.index, 1)[0]
              tableTreeData.unshift(currRow)
            }
            // 如果变动了树层级，需要刷新数据
            this.columnData.columnList = [...tableTreeData]
          }
        })
      })
    },
    // 色阶设置
    setColor(item) {
      console.log(item)
      this.fieldForm = item
      this.fieldFormSet = g.Copy(item)
      this.isColorVisible = true
    },
    visibleCheckChange(row) {
      row.mobileVisible = row.visible
      console.log(row)
    },
    addColor() {
      this.fieldForm = this.fieldFormSet
      this.columnData.columnList.forEach((item) => {
        if (item.propId === this.fieldForm.propId) {
          item.colorScale = this.fieldFormSet.colorScale
        }
      })
      this.isColorVisible = false
    },
    addColorArr(item) {
      let colorArr = item.colorArr || []
      if (colorArr.length < 1) {
        this.predefineColors.forEach((item) => {
          colorArr.push({
            text: '',
            color: item
          })
        })
      } else {
        colorArr.push({
          text: '',
          color: ''
        })
      }
      this.$set(item, 'colorArr', colorArr)
    },
    delColorArr(item, index) {
      item.splice(index, 1)
    }
  }
}
</script>
<style scoped lang="scss"></style>
