<!--
 * @Author: @liulin
 * @Date: 2022-06-06 16:33:44
 * @LastEditors: Please set LastEditors
-->
<template>
  <div class="fullheight">
    <el-dialog
      title="模板配置"
      :visible.sync="dialogVisibleTemplete"
      :before-close="handleClose"
      :modal="false"
      fullscreen
    >
      <el-container class="fullheight" style="border: 1px solid #eee">
        <el-aside
          :width="'200px'"
          :style="{height: addFields.tableHeight + 'px'}"
          style="
            border-right: 1px solid #eee;
            transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
          "
        >
          <div class="tree-header flex">
            <el-input placeholder="请输入" v-model="filterText" clearable>
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <div
              :class="
                isIeExplorer
                  ? 'tree-button-group is-ie-explorer flex'
                  : 'tree-button-group flex'
              "
            >
              <i
                :class="{'icon-zhankai': !isExpand, 'icon-shouqi': isExpand}"
                :title="isExpand ? '收起' : '展开'"
                @click="handleExpandCollapse"
              />
              <i
                class="icon-sync"
                :class="{'icon-spin': loading}"
                title="刷新"
                @click="refresh"
              />
            </div>
          </div>
          <el-tree
            :data="menusData"
            :props="defaultProps"
            :filter-node-method="filterNode"
            :default-checked-keys="defaultCheckedKeys"
            :default-expanded-keys="defaultExpandedKeys"
            node-key="id"
            @node-click="handleNodeClick"
            accordion
            ref="tree"
            highlight-current
            style="background: #fafafa"
          >
            <span class="custom-tree-node" slot-scope="{node}">
              <div>
                <i class="el-icon-s-order icon"></i>
                <span style="padding-left: 4px">{{ node.label }}</span>
              </div>
            </span>
          </el-tree>
        </el-aside>
        <el-container>
          <el-row :gutter="10">
            <el-col :span="12">
              <div class="head-content no-margin">字段列表</div>
              <el-table
                ref="allFieldsTable"
                :data="addFields.data"
                border
                stripe
                v-loading="addFields.loading"
                :height="addFields.tableHeight"
                highlight-current-row
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="40"> </el-table-column>
                <el-table-column
                  label="序号"
                  type="index"
                  align="center"
                  width="60"
                ></el-table-column>
                <el-table-column
                  label="字段名称"
                  align="center"
                  prop="fieldName"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  label="字段编码"
                  align="center"
                  prop="field"
                  show-overflow-tooltip
                >
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="12">
              <div class="head-content no-margin">已选字段</div>
              <el-table
                :data="addFields.selectData"
                border
                stripe
                :height="addFields.tableHeight"
                highlight-current-row
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  label="序号"
                  type="index"
                  align="center"
                  width="60"
                ></el-table-column>
                <el-table-column
                  label="字段名称"
                  align="center"
                  prop="fieldName"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  label="字段编码"
                  align="center"
                  prop="field"
                  show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                  label="计算方式"
                  align="center"
                  prop="calculationMethod"
                  show-overflow-tooltip
                >
                  <!-- validate="required" -->
                  <template v-slot="{row}">
                    <dict-select
                      v-model="row.calculationMethod"
                      dictCode="zdytz-jsfs"
                      placeholder="请选择计算方式"
                      clearable
                      :disabled="!disabledKeys.includes(row.fieldTypeValue)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="60">
                  <template slot-scope="scope">
                    <el-button
                      circle
                      type="danger"
                      icon="el-icon-delete"
                      @click="handleDelFields(scope.row)"
                    ></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-container>
      </el-container>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleTemplete = false">取 消</el-button>
        <el-button type="primary" @click="handleSumbit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisibleTemplete: false,
      filterText: '', //树型搜索内容,
      isIeExplorer: false,
      isExpand: false,
      loading: false,
      menusData: [],
      defaultProps: {
        label: 'name',
        code: 'code',
        id: 'id',
        children: 'children',
        isLeaf: 'leaf', // 指定节点是否为叶子节点，仅在指定了 lazy 属性的情况下生效
      },
      defaultCheckedKeys: [],
      defaultExpandedKeys: [],
      node: '',
      resolve: '',
      addFields: {
        data: [],
        loading: false,
        tableHeight: 300,
        selectData: [],
      },
      selectFields: [],
      menusParams: {
        pageBean: {
          page: 1,
          pageSize: -1,
          showTotal: true,
        },
        querys: [
          {
            group: 'main',
            operation: 'EQUAL',
            property: 'MENU_ALIAS_',
            relation: 'AND',
            value: '',
          },
        ],
        sotrer: [
          {
            direction: 'ASC',
            property: 'SN_',
          },
        ],
      },
      disabledKeys: ['2', '3', '4'],
    }
  },
  mounted() {
    this.getMenusData()
    this.calcTableHeight()
    this.$root.$on('resize', () => {
      this.calcTableHeight(500)
    })
    this.getMenusPropsData('projectManagement')
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    defaultCheckedKeys(val) {
      this.$refs.tree.setCheckedKeys(val)
    },
  },
  methods: {
    show(data) {
      this.dialogVisibleTemplete = true
      this.addFields.selectData = data
    },
    handleClose(done) {
      done()
    },
    getMenusData() {
      let menus = JSON.parse(sessionStorage.getItem('currentFrontMenus'))
      //过滤不需要的树节点
      let menus_ = this.filterMenusData(menus)
      let arrMenus = [
        {
          name: '菜单名称',
          code: 'root',
          children: [],
          id: 0,
          isLeaf: true,
          alias: 'root',
        },
      ]
      arrMenus[0].children.push(...menus_)
      this.menusData = arrMenus
      this.defaultExpandedKeys.push(0)
    },
    // 过滤树节点
    filterMenusData(data) {
      data.forEach((item, index) => {
        // 过滤年度计划、统计报表、安全，环保和文件库
        if (
          item.alias == 'AnnualPlan' ||
          item.alias == 'statisticalReport' ||
          item.alias == 'fileLibrary'
        ) {
          data.splice(index, 1)
        }
        // 过滤环保和其他
        if (item.alias == 'processManagement') {
          item.children.forEach((item1, index1) => {
            if (item1.alias == 'securityManagement') {
              item1.children.forEach((item2, index2) => {
                if (
                  item2.alias == 'constructionEnvironmentProtection' ||
                  item2.alias == 'constructionOther'
                ) {
                  item1.children.splice(index2, 1)
                }
              })
            }
          })
        }
        //过滤技术资料和经济资料
        if (item.alias == 'processManagement') {
          item.children.forEach((item1, index1) => {
            if (item1.alias == 'technicalInformation') {
              item.children.splice(index1, 1)
            }
          })
        }
      })
      data.forEach((item, index) => {
        if (item.alias == 'planningEIA') {
          data.splice(index, 1)
        }
        if (item.alias == 'processManagement') {
          item.children.forEach((item1, index1) => {
            if (item1.alias == 'economicData') {
              item.children.splice(index1, 1)
            }

            if (item1.alias == 'securityManagement') {
              item1.children.forEach((item2, index2) => {
                if (item2.alias == 'constructionOther') {
                  item1.children.splice(index2, 1)
                }
              })
            }
          })
        }
      })
      return data
    },
    //点击节点
    handleNodeClick(data) {
      if (data.alias && data.children.length == 0) {
        this.currentComponent = data.alias
      }
      this.getMenusPropsData(data.alias)
    },
    getMenusPropsData(alias) {
      this.menusParams.querys[0].value = alias
      this.$http
        .post('${cqxy}/biz/menuField/v1/query', this.menusParams)
        .then((res) => {
          this.addFields.data = res.data.rows
        })
    },
    // 树状菜单的全部展开和收起
    handleExpandCollapse() {
      let elTree = this.$refs.tree
      for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
        elTree.store._getAllNodes()[i].expanded = this.isExpand
      }
      this.isExpand = !this.isExpand
    },
    //树状刷新
    refresh() {
      this.loading = true
      this.$emit('refresh', () => {
        this.loading = false
        this.filterText = ''
        this.getMenusData()
      })
      setTimeout(() => {
        this.loading = false
        this.filterText = ''
        this.getMenusData()
      }, 2000)
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.defaultProps.label].indexOf(value) !== -1
    },
    handleSelectionChange(selection) {
      selection.forEach((element) => {
        this.$set(element, 'calculationMethod', 1)
        if (!this.selectFields.includes(element.fieldName)) {
          this.selectFields.push(element)
          this.addFields.selectData.push(element)
        }
      })
      this.addFields.selectData = this.deweight(this.addFields.selectData)
    },
    deweight(arr) {
      let map = new Map()
      for (let i of arr) {
        if (!map.has(i.id)) {
          map.set(i.id, i)
        }
      }
      return [...map.values()]
    },
    handleDelFields(row) {
      // console.log(row)
      this.addFields.selectData = this.addFields.selectData.filter(
        (item) => item.fieldName !== row.fieldName
      )
      this.selectFields = this.selectFields.filter(
        (item) => item.fieldName !== row.fieldName
      )
       let formData = new FormData()
      formData.append('ids', row.id)
      this.$http
        .post('${cqxy}/biz/menuCustomizeField/v1/delete', formData)
        .then((res) => {
          if (res.data.state) {
            this.$message.success(res.data.message)
          } else {
            this.$message.error(res.data.message)
          }
        })
    },
    handleSumbit() {
      // console.log(this.addFields.selectData)
      this.$emit('submitPropsData', this.addFields.selectData)
      this.dialogVisibleTemplete = false
    },
    // 动态计算表格的高度，自适应当前容器
    calcTableHeight(delay) {
      // let gap = this.type == 'import' ? 206 : 236
      let gap = 150
      setTimeout(() => {
        this.addFields.tableHeight =
          document.documentElement.clientHeight * 0.9 - gap
      }, delay || 0)
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.form-empty {
  position: absolute;
  text-align: center;
  width: 300px;
  font-size: 20px;
  top: 200px;
  left: 50%;
  margin-left: -150px;
  color: rgba(0, 0, 0, 0.5);
}
div.tree-header {
  min-height: 30px;
  /deep/ .el-input--small .el-input__inner {
    border: none;
  }
  i:hover {
    cursor: pointer;
  }
}
div.tree-header >>> .el-input__inner {
  border-width: 0;
  padding-right: 0;
}
div.tree-button-group i {
  cursor: pointer;
  display: inline;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}
div.tree-button-group i:hover {
  color: lightcoral;
}
.tree-button-group {
  margin-left: 10px;
}
.is-ie-explorer {
  margin-right: 25px;
}
.flex {
  display: flex;
}
.shrink {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 50px;
  border-bottom: 8px solid transparent;
  border-right: none;
  border-left: 12px solid #ebebeb;
  border-top: 8px solid transparent;
  opacity: 0.9;
  cursor: pointer;
  i {
    position: absolute;
    top: 50%;
    left: -14px;
    transform: translateY(-50%);
  }
  &:hover {
    color: #21aeff;
  }
}
>>> .el-dialog__body {
  padding-top: 0px;
}
.sort-icon {
  font-size: 16px;
  vertical-align: middle;
}
.dt-button-group {
  margin-bottom: 20px;
}
.head-content {
  margin-bottom: 15px;
  height: 32px;
  line-height: 32px;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 0;
}
/deep/ .el-row {
  width: 100%;
}
</style>
