<template>
  <div class="base-detail-container">
    <!-- <div class="form-title_blue">属性设置</div> -->
    <ts-form-item style="margin-top: 5px">
      <ts-input v-model="selectData.type" title="控件类型" disabled readonly width="95%"></ts-input>
    </ts-form-item>
    <ts-form-item>
      <ts-switch
        titleWidth="80px"
        title="钻取文本"
        v-model="selectData.showMainText"
        on-label="是"
        off-label="否"
        width="50%"
        @change="refresh($event, 'showMainText')"
      ></ts-switch>
    </ts-form-item>
    <div v-if="!selectData.showMainText">
      <div class="flexbox form__box" style="width: 100%" @click="forbidBubbling">
        <div class="title form__title" style="width: 80px">钻取</div>
        <!-- 添加按钮 -->
        <div class="m-multiMil__add" @click="add">
          <!-- <span class="bg transition__all_3s"></span> -->
          <span class="text font16">+</span>
        </div>
        <div style="flex: 1"></div>
        <div style="width: 100px">
          <ts-button
            type="button"
            style="font-size: 12px"
            @click="savaTable"
            icon="iconfont icon-baocun1"
          >保存</ts-button>
        </div>
      </div>

      <div
        class="m-multiMil__list pdl5 pdb5"
        v-for="(item, index) in selectData.clickEvent"
        :key="index"
      >
        <div class="m-multiMil__order fl">{{ index + 1 }}</div>
        <!-- 内容区域 -->
        <div class="m-multiMil__content fl">
          <div style="display: flex; justify-content: space-around">
            <ts-select
              :key="'selectDataSource' + item.id"
              v-model="item.targetDataSource"
              :source="dataSourceData"
              width="40%"
              placeholder="请选择目标数据源"
              @selected="refresh($event, item, 'targetDataSource')"
            ></ts-select>
            <ts-select
              placeholder="请选择目标参数"
              :key="'selectDataParam' + selectData.id"
              :source="dataSourceColSource(item.selectDataSourceParam)"
              v-model="item.targetParam"
              @selected="refresh($event, item, 'targetParam')"
              width="29%"
            ></ts-select>
            <ts-select
              :key="'selectDataCode' + selectData.id"
              :source="dataSourceColSource(item.selectDataSourceData)"
              v-model="item.targetField"
              @selected="refresh($event, item, 'targetField')"
              width="29%"
              placeholder="请选择绑定字段"
            ></ts-select>
          </div>

          <div v-if="item.tableData" class="table__box" style="height: 200px; margin-bottom: 5px">
            <vxe-table
              height="100%"
              keep-source
              :ref="item.id"
              border
              row-id="field"
              resizable
              row-key
              :checkbox-config="{ reserve: true }"
              show-overflow
              @edit-closed="editClosedEvent($event, item)"
              @checkbox-all="selectALl($event, item)"
              @checkbox-change="selectChangeEvent($event, item)"
              :data="item.tableData"
              :edit-config="{ trigger: 'click', mode: 'cell' }"
            >
              <vxe-table-column width="40" align="center">
                <template v-slot>
                  <span class="drag-btn" style="cursor: pointer">
                    <i class="vxe-icon--menu"></i>
                  </span>
                </template>
                <template v-slot:header>
                  <!-- <vxe-tooltip v-model="showHelpTip1" content="按住后可以上下拖动排序！" enterable>
                <i class="vxe-icon--question" @click="showHelpTip1 = !showHelpTip1"></i>
                  </vxe-tooltip>-->
                  排序
                </template>
              </vxe-table-column>
              <vxe-table-column type="checkbox" align="center" width="40"></vxe-table-column>
              <vxe-table-column field="field" title="字段" width="60px"></vxe-table-column>
              <vxe-table-column
                field="title"
                title="显示名称"
                width="100px"
                :edit-render="{ name: 'input' }"
              ></vxe-table-column>
              <vxe-table-column
                field="width"
                title="宽度"
                width="60px"
                :edit-render="{ name: '$input', props: { type: 'number' } }"
              ></vxe-table-column>
              <vxe-table-column
                field="align"
                title="对齐方式"
                width="80px"
                :edit-render="{
                  name: 'select',
                  options: alginOption,
                  autoselect: true,
                }"
              ></vxe-table-column>
              <vxe-table-column field="fontColor" align="center" title="字体颜色" width="80px">
                <template v-slot="{ row }">
                  <ts-color-picker v-model="row.fontColor" @change="refresh($event, 'groundColor')" colorWidth="55px"></ts-color-picker>
                </template>
              </vxe-table-column>
              <vxe-table-column
                field="filter"
                title="格式化"
                width="100px"
                :edit-render="{
                  name: 'select',
                  options: filterOption,
                  autoselect: true,
                }"
              ></vxe-table-column>
            </vxe-table>
          </div>
          <div style="display: flex">
            <ts-switch
              title="钻取文本"
              v-model="item.showText"
              on-label="是"
              off-label="否"
              width="50%"
              @change="refresh($event, item, 'showText')"
            ></ts-switch>
            <ts-select
              v-show="item.showText"
              :key="'selectDataCode' + selectData.id"
              :source="dataSourceColSource(item.selectDataSourceData)"
              v-model="item.textField"
              @selected="refresh($event, item, 'textField')"
              width="50%"
              placeholder="请选择绑定字段"
            ></ts-select>
          </div>
        </div>
        <!-- button -->
        <div class="m-multiMil__del transition__all_3s fl" @click="del(index)">
          <i class="iconfont icon-Group-17"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import natureArrMixins from '../mixins/natureArrMixins'
export default {
  name: 'attr-base',
  props: {},
  mixins: [natureArrMixins],
  data() {
    return {
      showHelpTip1: false,
      dataSourceData: {
        dataType: 'local',
        data: this.$store.state.bi.dataSource,
        code: 'id',
        text: 'queryName',
        condition: 'condition',
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      },
      filterOption: [
        {
          label: '无',
          value: '0'
        },
        {
          label: '千分位',
          value: '1'
        },
        { label: 'YYYY-MM-DD', value: '2' },
        { label: 'YYYY-MM-DD-hh-mm-ss', value: '3' },
        { label: '保留两位小数', value: '4' }
      ],
      alginOption: [
        { label: '靠左', value: 'left' },
        { label: '居中', value: 'center' },
        { label: '靠右', value: 'right' }
      ],
      currentValue: [],
      title_width: '',
      times: null,
      selectData: JSON.parse(JSON.stringify(this.$store.state.bi.selectData)),
      natureArrIds: [],
      childDatasList: [],
      fieldList: []
    }
  },
  computed: {},
  created() {
    this.rowDrop()
    this.reLook()
    this.natureArrIds = []
    this.getNatureArrIds(this.$store.state.bi.natureArr)
  },
  methods: {
    savaTable() {
      this.selectData.clickEvent.forEach(element => {
        element.selectData = element.tableData.filter(table =>
          element.selectData.some(select => select.id == table.id)
        )
      })
      this.changeStoreArray()
      this.$utils.msg(this, '操作成功', 'success')
    },
    rowDrop() {
      this.$nextTick(() => {
        for (let item of this.selectData.clickEvent) {
          const xTable = this.$refs[item.id][0]
          this.sortable1 = Sortable.create(
            xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'),
            {
              handle: '.drag-btn',
              onEnd: ({ newIndex, oldIndex }) => {
                const currRow = item.tableData.splice(oldIndex, 1)[0]
                item.tableData.splice(newIndex, 0, currRow)
              }
            }
          )
        }
      })
    },
    editClosedEvent(ev, item) {
      // let xTable = this.$refs.xTable
      let field = ev.column.property
      // let cellValue = ev.row[field]
      // this.changeStoreArray()
      // this.$nextTick(()=>{
      //       this.$refs[item.id][0].reloadRow(ev.row, null, field)
      // this.$refs[item.id][0].updateData()
      // })
    },
    reLook() {
      //  回显数据
      if (this.selectData.clickEvent && this.selectData.clickEvent.length > 0) {
        this.selectData.clickEvent.forEach(element => {
          element.tableData.forEach(table => {
            element.selectData.forEach(select => {
              if (table.id == select.id) {
                this.$nextTick(() => {
                  this.$refs[element.id][0].setCheckboxRow(table, true)
                })
              }
            })
          })
        })
      }
    },
    selectALl(args, item) {
      //点击全选按钮
      let { selection } = args
      item.selectData = selection
      this.changeStoreArray()
    },
    selectChangeEvent(args, item) {
      //点击单个复选框
      let { selection } = args
      item.selectData = selection
      this.changeStoreArray()
    },
    dataSourceColSource(data) {
      return {
        dataType: 'local',
        code: 'name',
        text: 'name',
        data: data || [],
        isReq: true,
        value: {
          name: '',
          code: ''
        }
      }
    },
    // 监听数据源字段

    refresh(ev, item, key) {
      this.$nextTick(() => {
        switch (key) {
          case 'targetDataSource': //iconValaue
            item.targetDataSource = ev.id
            item.targetDataSourceName = ev.queryName
            item.selectDataSourceData = []
            item.selectDataSourceResultData = []
            item.selectDataSourceParam = []
            if (ev.serviceType == '2') {
              // 结果集
              for (let items of JSON.parse(ev.columnDefine)) {
                item.selectDataSourceResultData.push({
                  name: items.name,
                  tableColumns: items.tableColumns
                })
              }
            } else {
              for (let items of JSON.parse(ev.columnDefine)) {
                item.selectDataSourceData.push({
                  name: items.name
                })
              }
            }
            for (let items of JSON.parse(ev.conditionDefine)) {
              item.selectDataSourceParam.push({
                name: items.name
              })
            }
            let tableData = item.selectDataSourceData.map(res => {
              return {
                field: res.name,
                title: res.name,
                width: '60',
                align: 'center',
                fontColor: '#333',
                filter: '0',
                fontSize: '12',
                id: this.$utils.uuid()
              }
            })
            item.tableData = tableData
            item.selectData = [...tableData]
            this.$nextTick(() => {
              this.$refs[item.id][0].setAllCheckboxRow(true)
            })
            this.rowDrop()
            break
          case 'targetParam': //字体大小
            item.targetParam = ev.name
            break
          case 'targetField': //字段参数
            item.targetField = ev.name
            break
          case 'showText': //字段参数
            item.showText = ev
            break
          case 'textField': //钻取文本字段
            item.textField = ev.name
            break
          case 'showMainText':
            this.selectData.showMainText = ev
            break
          case 'center': //背景颜色
            item.backgroundColor = ev
            break
          case 'showTitle': //背景颜色
            item.title = ev.name
            break
        }
        this.changeStoreArray()
      })
    },
    forbidBubbling(e) {
      e.stopPropagation()
    },
    del(index) {
      for (let i in this.selectData.clickEvent) {
        if (index === Number(i)) {
          this.selectData.clickEvent.splice(i, 1)
          break
        }
      }
    },
    add() {
      if (!this.selectData.clickEvent) {
        this.selectData.clickEvent = []
      }
      const d = {
        id: this.$utils.uuid(6),
        targetDataSource: '',
        targetParam: '',
        targetField: '',
        tableData: [],
        selectData: []
      }
      this.selectData.clickEvent.push(d)
    }
  },
  mounted() {
    if (!this.selectData.clickEvent) {
      this.selectData.clickEvent = []
    }
  },
  watch: {
    '$store.state.bi.selectData': {
      handler(val) {
        this.selectData = JSON.parse(JSON.stringify(val))
      }
    },
    '$store.state.bi.natureArr': {
      handler(val) {
        this.natureArrIds = []
        this.getNatureArrIds(val[this.$store.state.bi.dialogEditors.length - 1])
      }
    }
  }
}
</script>
<style lang="less" scoped>
.sysManageSystemDepartment__editor {
  height: calc(100% - 14px);
}
</style>
