<template>
  <el-dialog
    :visible.sync="visible"
    width="920px"
    custom-class="custom-column__dialog"
    append-to-body
    :before-close="customColumnDialogCancel"
  >
    <template slot="title">
      <ht-h3 inline>自定义列</ht-h3>
      <span class="custom-column__desc">
        勾选需要显示的列
        <template v-if="isShowSetWidth">、设置列的宽度</template>
      </span>
    </template>
    <el-container class="custom-container">
      <div id="container" class="list-selector__container">
        <div id="left" class="list-selector__range">
          <el-card shadow="hover" style="height: 495px">
            <el-checkbox
              v-if="currentCustomColumns && currentCustomColumns.length > 0"
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              style="margin-bottom: 20px; display: flex; align-items: center"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-scrollbar
              class="selector-selected__scroll"
              :wrap-style="[{ maxHeight: '445px' }]"
            >
              <div
                style="display: flex; align-items: flex-end; flex-wrap: wrap"
              >
                <el-checkbox
                  v-for="item in currentCustomColumns"
                  :key="item.key"
                  v-model="item.checked"
                  :disabled="item.required"
                  :label="item.value"
                  :title="item.value"
                  style="
                    width: 135px;
                    margin-bottom: 10px;
                    display: flex;
                    margin-right: 10px;
                    align-items: center;
                  "
                >
                  {{ item.value }}
                </el-checkbox>
              </div>
            </el-scrollbar>
          </el-card>
        </div>
        <div id="right" class="list-selector__selected">
          <el-card shadow="hover" style="height: 495px">
            <div slot="header" class="selector-selected__header clearfix">
              <span>
                已选({{
                  currentSelectCustomColumns
                    ? currentSelectCustomColumns.length
                    : 0
                }})
              </span>
              <el-button
                type="text"
                style="float: right; padding: 3px 0"
                @click="clearAllSelects"
              >
                {{ $t('ht.common.clear') }}
              </el-button>
            </div>
            <el-scrollbar
              class="selector-selected__scroll"
              :wrap-style="[{ maxHeight: '465px' }]"
            >
              <!-- <draggable
                v-model="currentSelectCustomColumns"
                class="el-select-dropdown__list"
                tag="ul"
                v-bind="dragOptions"
                handle=".list-selector__handle"
                filter=".el-select-dropdown__item"
              > -->
              <ul class="el-select-dropdown__list">
                <li
                  v-for="(column, index) in currentSelectCustomColumns"
                  :key="column.key"
                  class="el-select-dropdown__item"
                >
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                      padding-right: 14px;
                    "
                  >
                    <div class="column-name__container">
                      <div
                        class="column-name__progress"
                        :style="progressWidth(column.width)"
                        style="padding-left: 14px"
                        :title="column.value"
                      >
                        <!-- <ht-icon
                          v-if="column.key != '序号'"
                          name="drag"
                          class="list-selector__handle follow-theme-color"
                          width="16"
                          height="16"
                          fill=""
                          style="margin-right: 8px;"
                        /> -->
                        <span class="column-name__title">
                          {{ column.value }}
                        </span>
                      </div>
                    </div>
                    <div class="column-name__tail">
                      <span
                        v-if="column.required"
                        class="column-name__required"
                      >
                        必选
                      </span>
                      <el-input
                        v-if="isShowSetWidth"
                        v-model="column.width"
                        placeholder="请输入内容"
                        :style="{ marginRight: column.required ? '20px' : '0' }"
                      >
                        <template slot="prepend">宽度</template>
                        <span slot="append">px</span>
                      </el-input>
                      <i
                        v-show="!column.required"
                        class="el-icon-error selector-selected__remove hover-follow-theme-color"
                        style="margin-left: 6px"
                        @click="removeSelected(column)"
                      ></i>
                    </div>
                  </div>
                </li>
              </ul>
              <!-- </draggable> -->
            </el-scrollbar>
          </el-card>
        </div>
      </div>
    </el-container>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="customColumnDialogCancel">
        取 消
      </el-button>
      <el-button size="small" @click="customColumnDialogReset">
        恢复默认
      </el-button>
      <el-button type="primary" size="small" @click="customColumnDialogSure">
        确 定
      </el-button>
    </span>
  </el-dialog>
</template>
<script>
  import utils from '@/utils.js'
  import { encode, decode } from '@/util/base64'
  const draggable = require('vuedraggable')
  import _ from 'lodash'
  export default {
    name: 'CustomColumn',
    components: { draggable },
    props: {
      customColumns: {
        type: Array,
        default: () => {
          return null
        },
      },
      visible: {
        type: Boolean,
        default: false,
      },
      customColumnsDefault: {
        type: Array,
        default: () => {
          return null
        },
      },
      //是否显示自定义列的宽度设置
      isShowSetWidth: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        customColumnsHashCode: null,
        currentCustomColumns: null,
        currentSelectCustomColumns: null,
        storageCustomColumns: null,
        checkAll: false,
        isIndeterminate: true,
      }
    },
    computed: {
      dragOptions() {
        return {
          animation: 0,
          group: 'description',
          disabled: false,
          ghostClass: 'ghost',
        }
      },
      progressWidth() {
        return (width) => {
          return width == 'auto'
            ? { width: '100%' }
            : { width: `${(width / 1000) * 100}%` }
        }
      },
    },
    watch: {
      visible: function (newVal) {
        if (newVal) {
          this.initialCurrentCustomColumn()
        } else {
          this.currentCustomColumns = null
          this.currentSelectCustomColumns = null
          this.storageCustomColumns = null
        }
      },
      currentCustomColumns: {
        handler(val) {
          if (val) {
            let data = _.cloneDeep(val)
            this.currentSelectCustomColumns = data.filter(
              (item) => item.checked
            )
            let checkedCount = this.currentSelectCustomColumns.length
            this.checkAll = checkedCount === this.currentCustomColumns.length
            this.isIndeterminate =
              checkedCount > 0 &&
              checkedCount < this.currentCustomColumns.length
            this.$forceUpdate()
          }
        },
        immediate: true,
        deep: true,
      },
    },
    mounted() {
      setTimeout(() => {
        this.initialCurrentCustomColumn()
        this.applyCustomColumn()
      }, 10)
    },
    methods: {
      handleNameClick(column) {
        if (!column.required) {
          column.checked = !column.checked
        }
      },
      getCustomColumnsHashCode() {
        if (
          !this.customColumnsHashCode &&
          this.customColumns &&
          this.customColumns.length > 0
        ) {
          const keys = this.customColumns.reduce((m, n) => m.concat(n.key), [])
          // 获取当前自定义列表项的hashCode
          this.customColumnsHashCode = utils.hashCode(keys.join(','))
        }
      },
      // 自定义列表项确定按钮
      customColumnDialogSure() {
        // 同步选中状态到localStorage中
        if (this.customColumnsHashCode) {
          let cloCurrentCustomColumns = this.currentCustomColumns
          cloCurrentCustomColumns.forEach((item) => {
            this.currentSelectCustomColumns.forEach((selItem) => {
              if (item.key === selItem.key) {
                item.width = selItem.width
              }
            })
          })
          this.setLocalStorage(
            this.customColumnsHashCode,
            cloCurrentCustomColumns
          )
        }
        this.applyCustomColumn()
        this.$emit('update:visible', false)
      },
      // 自定义列表项取消按钮
      customColumnDialogCancel() {
        this.$emit('update:visible', false)
      },
      // 自定义列恢复默认
      customColumnDialogReset() {
        if (this.customColumnsDefault) {
          this.currentCustomColumns = [
            ..._.cloneDeep(this.customColumnsDefault),
          ]
        } else {
          // 如果未传自定义列的默认值，则保留之前的代码逻辑
          this.currentCustomColumns.forEach((item) => {
            if (!item.checked) item.checked = !item.checked
          })
        }
      },
      // 初始化自定义列表项
      initialCurrentCustomColumn() {
        // 1.根据当前列构建storage存储hash
        this.getCustomColumnsHashCode()
        // 2.通过hash获取localStorage中的设置
        if (this.customColumnsHashCode) {
          this.currentCustomColumns = this.getLocalStorage(
            this.customColumnsHashCode
          )
        }
        // 3.没有localStorage时，复制一份传入的数据
        if (!this.currentCustomColumns) {
          this.currentCustomColumns = [...this.customColumns]
        }
        this.currentSelectCustomColumns = this.currentCustomColumns.filter(
          (item) => item.checked
        )
      },
      // 将自定义列表项应用到当前表格、自定义列表项数组中
      applyCustomColumn() {
        if (
          !this.currentCustomColumns ||
          this.currentCustomColumns.length == 0
        ) {
          return
        }
        this.currentSelectCustomColumns.forEach((item) => {
          this.currentCustomColumns.forEach((val) => {
            if (item.key === val.key) {
              val = item
            }
          })
        })
        // this.currentCustomColumns = this.sortList(
        //   this.currentSelectCustomColumns,
        //   this.currentCustomColumns
        // )
        this.$emit('apply-custom-column', [this.currentCustomColumns])
      },

      // 从localStorage中获取用于存放自定义列表项的对象
      getObjectFromLocalStorage() {
        if (localStorage) {
          let customColumnSetting = localStorage.getItem('customColumnSetting')
          if (!customColumnSetting) {
            customColumnSetting = '{}'
          }
          /* eslint-disable */
          try {
            customColumnSetting = JSON.parse(customColumnSetting)
          } catch (e) {}
          /* eslint-enable */
          if (!customColumnSetting || typeof customColumnSetting != 'object') {
            customColumnSetting = {}
          }
          return customColumnSetting
        }
        return null
      },
      setLocalStorage(key, value) {
        let customColumnSetting = this.getObjectFromLocalStorage()
        if (customColumnSetting) {
          customColumnSetting[key] = encode(JSON.stringify(value))
          localStorage.setItem(
            'customColumnSetting',
            JSON.stringify(customColumnSetting)
          )
        }
      },
      getLocalStorage(key) {
        let customColumnSetting = this.getObjectFromLocalStorage()
        if (customColumnSetting) {
          const result = customColumnSetting[key]
          if (result) {
            return JSON.parse(decode(result))
          }
        }
        return null
      },
      sortList(list, needSort) {
        const _list = list.map((li) => li.key)
        return needSort.sort((a, b) => {
          return _list.indexOf(a.key) < _list.indexOf(b.key) ? -1 : 1
        })
      },
      handleCheckAllChange(val) {
        for (let key in this.currentCustomColumns) {
          this.$set(this.currentCustomColumns[key], 'checked', val)
          if (
            this.currentCustomColumns[key].hasOwnProperty('required') &&
            this.currentCustomColumns[key].required
          ) {
            this.$set(this.currentCustomColumns[key], 'checked', true)
          }
        }
      },
      removeSelected(item) {
        for (let key in this.currentCustomColumns) {
          if (this.currentCustomColumns[key].key == item.key) {
            this.$set(this.currentCustomColumns[key], 'checked', false)
            break
          }
        }
      },
      clearAllSelects() {
        for (let key in this.currentCustomColumns) {
          if (!this.currentCustomColumns[key].required) {
            this.$set(this.currentCustomColumns[key], 'checked', false)
          }
        }
      },
    },
  }
</script>
<style lang="scss" scoped>
  ::v-deep {
    .custom-column__dialog {
      .el-dialog__header {
        .custom-column__desc {
          margin-left: 10px;
          color: $base-color-gray;
          font-size: 14px;
        }
        .el-dialog__headerbtn {
          top: 16px;
        }
      }

      .el-dialog__body {
        @include base-scrollbar;

        padding: 24px;
        max-height: 800px;
        overflow-y: auto;

        .el-select-dropdown__item {
          padding: 0;
          cursor: default;
          box-sizing: border-box;
        }

        .el-select-dropdown__item ~ .el-select-dropdown__item {
          border-top-width: 0;
        }

        .column-name__head {
          display: inline-block;
          padding: 0 12px;
          box-sizing: border-box;
          border-left-width: 0;
          border-top-width: 0;
          border-bottom-width: 0;
        }

        .column-name__container {
          width: 180px;
          display: inline-block;
          cursor: pointer;
          position: relative;
          overflow: hidden;
          text-overflow: ellipsis;
          height: 30px;

          .column-name__progress {
            width: 30%;
            box-sizing: border-box;
            background: #f9f9f9;
            max-width: 180px;
            .column-name__title {
              width: 170px;
              display: inline-block;
              cursor: pointer;
              position: relative;
              overflow: hidden;
              text-overflow: ellipsis;
            }
          }

          .column-name__sort {
            visibility: hidden;
            margin: 0 5px;
            cursor: move;
          }

          span {
            color: #262626;
            font-size: 14px;
            font-weight: 500;
          }
          &.custom-column__handle:hover .column-name__sort {
            // visibility: inherit;
          }
        }

        .column-name__tail {
          display: flex;
          float: right;
          align-items: center;
          justify-content: flex-end;
          input,
          span {
            //margin-right: 5px;
            font-size: 13px;
            color: $base-color-gray;
          }

          .column-name__required {
            margin-right: 10px;
          }

          input {
            width: 50px;
            border-right: 0;
            padding: 0 5px;
          }
          input:focus {
            border-color: #c0c4cc;
          }
        }
      }
      #container {
        display: flex; /*中间弹性盒布局*/
        flex-wrap: nowrap; /*排列不下时不换行*/
        overflow: hidden;
      }
      #left {
        order: 0;
        width: 488px;
        height: 500px;
        margin-right: 24px;
        .el-card__body {
          padding: 20px 8px 20px 20px;
        }
      }
      #right {
        order: 2;
        width: 360px;
        height: 500px;
      }
      .el-card__header {
        padding: 14px 20px !important;
      }
      #right .el-card__body {
        padding: 0;
      }
      .el-input-group__prepend {
        padding: 0 8px;
        background: #f9f9f9;
      }
      .el-input-group__append {
        padding: 0 5px;
        background: #fff;
      }
      .el-checkbox__label {
        width: 135px;
        text-overflow: ellipsis;
        overflow: hidden;
        display: inline-block;
      }
    }
  }
</style>
