<template>
  <div>
    <el-row style="background: #f6f6f6; padding-top: 18px">
      <el-form :inline="true" label-width="120px">
        <el-col :span="8">
          <ht-form-item
            label=""
            label-width="120px"
            class="is-required"
            style="display: block"
          >
            <span slot="label">
              <el-tooltip
                content="需先在配置显示字段中选择字段添加到右侧，进行格式化配置后才可以下拉中进行选择"
                placement="top"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
              列分组字段
            </span>
            <el-select
              style="width: calc(33.33vw - 200px)"
              value-key="fieldName"
              v-model="config.columnGroupField"
              clearable
              :class="{notCheck: !config.columnGroupField}"
            >
              <el-option
                v-for="item in columnGroupFields"
                :key="item.name"
                :label="
                  item.desc + '(' + item.name + ')' + '(' + item.type + ')'
                "
                :value="item"
              >
              </el-option>
            </el-select>
          </ht-form-item>
          <span v-show="!config.columnGroupField" class="tip">必填</span>
        </el-col>
        <el-col :span="8">
          <ht-form-item label="行分组字段" label-width="120px">
            <span slot="label">
              <el-tooltip
                content="需先在配置显示字段中选择字段添加到右侧，进行格式化配置后才可以下拉中进行选择"
                placement="top"
              >
                <i class="el-icon-info"></i>
              </el-tooltip>
              行分组字段
            </span>
            <el-select
              value-key="name"
              v-model="config.rowGroupField"
              clearable
              style="width: calc(33.33vw - 200px)"
            >
              <el-option
                v-for="item in columnGroupFields"
                :key="item.name"
                :label="
                  item.desc + '(' + item.name + ')' + '(' + item.type + ')'
                "
                :value="item"
              >
              </el-option>
            </el-select>
          </ht-form-item>
        </el-col>
      </el-form>
    </el-row>
    <el-row style="width: 100%">
      <h3>配置显示字段</h3>
      <el-col :span="7">
        <el-table
          ref="table"
          border
          :max-height="tableHeight"
          :data="conditionSettingFields"
          tooltip-effect="dark"
          @row-dblclick="addOne"
          default-expand-all
          :tree-props="{children: 'fields'}"
          row-key="tempId"
          @select="selectChange"
          @select-all="selectAllChange"
          @selection-change="selectionChangeHandler"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            prop="name"
            label="列名"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="desc"
            label="注释"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            prop="type"
            label="类型"
            width="80"
          ></el-table-column>
        </el-table>
      </el-col>
      <el-col :span="1" style="text-align: center">
        <el-row>
          <el-button
            type="primary"
            circle
            icon="el-icon-arrow-right"
            title="将所选字段添加到显示页面"
            @click="addSelectionToDisplay()"
          />
        </el-row>
      </el-col>
      <el-col :span="16">
        <div class="tablebox">
          <el-table
            ref="conditionTable"
            border
            :max-height="tableHeight"
            :data="config.fields"
            tooltip-effect="dark"
            style="width: 100%"
            row-class-name="table-row"
          >
            <el-table-column
              label="序号"
              type="index"
              width="50"
              fixed="left"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="列名"
              width="120"
              fixed="left"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="desc" label="显示名">
              <template scope="scope">
                <div style="height: 75px; padding-top: 22px">
                  <ht-input
                    v-model="scope.row.desc"
                    placeholder="请输入显示名称"
                    :maxlength="20"
                    show-word-limit
                    validate="required"
                    style="width: 100%"
                  >
                    <el-button
                      icon="icon-guojihua"
                      slot="append"
                      style="width: 50px"
                      @click="editI18nMessage(scope.row.fieldName)"
                    >
                    </el-button>
                  </ht-input>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="format" label="显示设置">
              <template slot-scope="scope">
                <el-button
                  :type="!!scope.row.formatterType ? 'primary' : ''"
                  style="margin-right: 16px"
                  @click="formatConfig(scope.row)"
                  >格式化配置
                </el-button>
                <el-switch
                  v-model="scope.row.isTitle"
                  active-text="设为标题"
                  @change="switchChange(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>

            <el-table-column label="管理" width="240" fixed="right">
              <template slot="header">
                <span style="margin-right: 10px">管理</span>
                <el-button
                  @click="handleClearSelected"
                  v-show="config.fields && config.fields.length > 0"
                  >清空</el-button
                >
              </template>
              <template slot-scope="scope">
                <el-button
                  @click="sort(scope.$index, 1)"
                  title="上移"
                  type="text"
                  :disabled="scope.$index === 0"
                  >上移</el-button
                >
                <el-button
                  @click="sort(scope.$index, -1)"
                  title="下移"
                  type="text"
                  :disabled="scope.$index === config.fields.length - 1"
                  >下移</el-button
                >
                <el-button
                  @click="remove(scope.$index, scope.row)"
                  title="删除"
                  type="text"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>

    <i18n-message-edit
      ref="i18nMessageEdit"
      :message-key="i18nMessageKey"
      @after-save="afterSaveI18n"
    />

    <formatter-dialog ref="formatterDialog" @confirm="formatterConfirm" />
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import I18nMessageEdit from '@/components/system/I18nMessageEdit.vue'
import FormatterDialog from './FormatterDialog'

export default {
  name: 'KanbanConfig',
  components: {
    FormatterDialog,
    I18nMessageEdit,
  },
  props: {
    data: Object,
  },
  data() {
    return {
      tableHeight: document.documentElement.clientHeight - 245,
      i18nMessageKey: '',
      config: {
        columnGroupField: {},
        rowGroupField: {},
        fields: [],
      },
      dataTemplate: {},
      selection: [],
      displayFieldMap: {},
      selectedRow: {},
    }
  },
  computed: {
    ...mapGetters('form', {
      displaySettingFields: 'displayFormListCommonVar',
    }),
    conditionSettingFields() {
      // 去掉流程字段
      let conditionSettingFields = JSON.parse(
        JSON.stringify(this.$store.getters['form/conditionFormListCommonVar'])
      )
      if (conditionSettingFields.length) {
        conditionSettingFields[0].fields =
          conditionSettingFields[0].fields.filter((item) => !item.flowField)
      }
      //处理字段列表，添加相应的字段
      let tempId = 0
      conditionSettingFields.forEach((p) => {
        p['tempId'] = tempId = tempId + 1
        p['isParent'] = true
        p.fields &&
          p.fields.forEach((s) => {
            s['tempId'] = tempId = tempId + 1
            s['isParent'] = false
          })
      })
      return conditionSettingFields
    },
    columnGroupFields() {
      return this.config.fields.filter((item) => !!item.formatterType)
    },
    rowGroupFields() {
      return this.config.fields
    },
  },
  mounted() {
    this.dataTemplate = this.data.bpmDataTemplate
    this.initData()
  },
  methods: {
    initData() {
      if (this.dataTemplate.kanbanConfig) {
        this.config = JSON.parse(this.dataTemplate.kanbanConfig) || {
          columnGroupField: {},
          rowGroupField: {},
          fields: [],
        }
      }
      if (this.dataTemplate.displayField) {
        let displayFields = JSON.parse(this.dataTemplate.displayField) || {}
        displayFields.forEach((item) => {
          this.displayFieldMap[item.name] = item
        })
      }
    },
    //双击字段列表中的字段时将该字段加入到显示字段
    addOne(row) {
      if (row.isParent) {
        return
      }
      if (!this.isAdded(row.name)) {
        let field = this.getConditionField(row)
        this.config.fields.push(field)
      }
      this.doLayoutTable()
    },
    isAdded(name) {
      return this.config.fields.map((field) => field.name).includes(name)
    },
    getMixProp(tableName, oldTableField, name) {
      let subItemName = tableName + (oldTableField || name)
      return subItemName.replace(/_/g, '').toLowerCase()
    },
    getConditionField(field) {
      let fieldName = this.getMixProp(
        field.tableName,
        field.oldTableField,
        field.name
      )
      let displayField = this.getFormatterData(fieldName)
      return {
        name: field.originName,
        fieldName: fieldName,
        desc: field.desc || '',
        type: field.type || '',
        format: '',
        status: null,
        colPrefix: field.colPrefix || '',
        showFlowField: true,
        isFlowField: false,
        tableName: field.tableName,
        right: '[{"type":"everyone","id":"","name":"","script":""}]',
        isTitle: this.config.fields.length === 0,
        formatterType: displayField.formatterType,
        formatterData: displayField.formatterData,
        dataDictionary: displayField.dataDictionary,
        dataDictionaryKey: displayField.dataDictionaryKey,
      }
    },
    getFormatterData(fieldName) {
      let displayField = this.displayFieldMap[fieldName] || {}
      if (['3', '2'].includes(displayField.formatterType)) {
        return {}
      }
      return {
        formatterType:
          displayField.formatterType === '4' ? '2' : displayField.formatterType,
        formatterData: displayField.formatterData,
        dataDictionary: displayField.dataDictionary,
        dataDictionaryKey: displayField.dataDictionaryKey,
      }
    },
    getDataId(data) {
      return data['tempId']
    },
    selectChange(selection, row) {
      // 如果selection中存在row代表是选中，否则是取消选中
      if (
        selection.find((val) => {
          return this.getDataId(val) === this.getDataId(row)
        })
      ) {
        if (row.fields) {
          //注意这里的children是后台返回数据的children字段
          row.fields.forEach((val) => {
            this.$refs.table.toggleRowSelection(val, true)
            if (val.fields) {
              this.selectChange(selection, val)
            }
          })
        }
      } else {
        this.toggleRowSelection(selection, row)
      }
    },
    toggleRowSelection(selection, data) {
      if (data.children) {
        //注意这里的children也是后台返回数据的children字段
        data.children.forEach((val) => {
          this.$refs.table.toggleRowSelection(val, false)
          if (val.children) {
            this.toggleRowSelection(selection, val)
          }
        })
      }
    },
    /**
     * 用于树形表格多选, 选中所有
     * @param selection
     */
    selectAllChange(selection) {
      // 如果选中的数目与请求到的数目相同就选中子节点，否则就清空选中
      if (
        selection &&
        selection.length === this.conditionSettingFields.length
      ) {
        selection.forEach((val) => {
          this.selectChange(selection, val)
        })
      } else {
        this.$refs.table.clearSelection()
      }
    },
    // 选择改变
    selectionChangeHandler(val) {
      this.selections = val
    },
    handleClearSelected() {
      this.$confirm('确认清空所有显示字段？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.config.fields = []
          this.$refs.table.clearSelection()
        })
        .catch(() => {})
    },
    addToDisplay(selection) {
      if (!selection || selection.length < 1) {
        this.$message({
          message: '请在左侧列表中选择要作为条件的字段',
          type: 'warning',
        })
      }
      selection.forEach((obj) => {
        this.addOne(obj)
      })
      this.doLayoutTable()
    },
    addSelectionToDisplay() {
      this.addToDisplay(this.$refs.table.selection)
    },
    addAllToDisplay() {
      this.addToDisplay(this.displaySettingFields)
    },
    editI18nMessage(columnName) {
      this.i18nMessageKey = `formTemplate.${this.dataTemplate.alias}.kanban.${columnName}`
      this.$refs.i18nMessageEdit.handleOpen()
    },
    afterSaveI18n(data) {
      data.key = data.key.replace('$', '#')
      this.dataTemplate.desc = data.key
      this.dataTemplate.desc_zh = data.desc
    },
    //显示字段排序
    sort(index, step) {
      let temp = this.config.fields[index - step]
      this.$set(this.config.fields, index - step, this.config.fields[index])
      this.$set(this.config.fields, index, temp)
    },
    remove(index) {
      if (this.config.fields[index].isTitle) {
        this.config.fields.splice(index, 1)
        if (this.config.fields.length > 0) {
          this.$set(this.config.fields[0], 'isTitle', true)
        }
      } else {
        this.config.fields.splice(index, 1)
      }
    },
    saveConfig() {
      if (
        !this.config.columnGroupField ||
        JSON.stringify(this.config.columnGroupField) === '{}'
      ) {
        this.$message.error('列分组字段不能为空')
        return false
      }
      let requiredArr = []
      this.config.fields.forEach((c) => {
        if (!c.desc) {
          requiredArr.push('显示名' + c.name)
        }
      })
      if (requiredArr.length > 0) {
        this.$message.error(
          '【看板配置】【' + requiredArr.join(',') + '】不能为空'
        )
        return false
      }
      this.dataTemplate.kanbanConfig = this.config
        ? JSON.stringify(this.config)
        : null
      return true
    },
    doLayoutTable() {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    switchChange(row) {
      let _this = this
      this.config.fields.forEach((field) => {
        if (field.name !== row.name) {
          _this.$set(field, 'isTitle', false)
        } else {
          _this.$set(field, 'isTitle', true)
        }
      })
    },
    formatConfig(row) {
      this.selectedRow = row
      this.$refs.formatterDialog.open(row)
    },
    formatterConfirm(row) {
      this.selectedRow.formatterType = row.formatterType
      this.selectedRow.formatterData = row.formatterData
      this.selectedRow.dataDictionary = row.dataDictionary
      this.selectedRow.dataDictionaryKey = row.dataDictionaryKey
      if (row.fieldName === this.config.columnGroupField.fieldName) {
        this.config.columnGroupField.formatterType = row.formatterType
        this.config.columnGroupField.formatterData = row.formatterData
        this.config.columnGroupField.dataDictionary = row.dataDictionary
        this.config.columnGroupField.dataDictionaryKey = row.dataDictionaryKey
      }
      if (row.fieldName === this.config.rowGroupField.fieldName) {
        this.config.rowGroupField.formatterType = row.formatterType
        this.config.rowGroupField.formatterData = row.formatterData
        this.config.rowGroupField.dataDictionary = row.dataDictionary
        this.config.rowGroupField.dataDictionaryKey = row.dataDictionaryKey
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.el-table >>> .el-radio-group {
  margin-left: 10px;
  margin-right: 10px;
}

.mobile-btn {
  &:focus {
    border: 1px solid #dcdfe6;
    color: #606266;
  }
}

.tip {
  color: rgb(229, 85, 85);
  position: relative;
  top: -18px;
  right: -119px;
  font-size: 12px;
}

.is-active__btn {
  border: 1px solid #409eff;
  background: #409eff;
  color: #fff;

  &:focus {
    color: #fff;
  }
}
::v-deep {
  .default-row > .cell {
    overflow: visible !important;
  }

  .el-button--mini {
    padding: 7px;
  }

  .tablebox {
    .el-table--scrollable-x .el-table__body-wrapper {
      overflow: auto !important;
    }
  }

  .el-table__fixed-right-patch {
    background-color: #f5f7fa !important;
  }

  .el-table th.gutter {
    display: none !important;
    width: 0 !important;
  }

  .el-table colgroup col[name='gutter'] {
    display: none !important;
    width: 0 !important;
  }

  .el-table__body {
    width: 100% !important;
  }

  .notCheck {
    input {
      border: solid 1px #e55555;
    }
  }

  .table-row {
    .el-table__cell {
      padding: 0;
    }
  }
}
</style>
