<template>
  <div class="user-management-container">
    <el-row :gutter="20">
      <el-col :span="5" :xs="24">
        <div class="head-container" style="margin-bottom: 5px">
          <el-input v-model="filterText" placeholder="输入关键字进行过滤" />
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="deptOptions"
            default-expand-all
            :default-expanded-keys="[1]"
            :filter-node-method="filterNode"
            highlight-current
            node-key="id"
            :props="defaultProps"
            @node-click="handleNodeClick" />
        </div>
        <vab-query-form-left-panel>
          <el-button icon="el-icon-plus" type="primary" @click="getCheckedNodes($event)">添加区域</el-button>
        </vab-query-form-left-panel>
      </el-col>
      <el-col :sapn="19">
        <vab-query-form>
          <vab-query-form-top-panel>
            <el-form :inline="true" :model="queryForm" @submit.native.prevent>
              <el-form-item prop="custCode">
                <el-input v-model="queryForm.custCode" clearable placeholder="客户编码" />
              </el-form-item>

              <el-form-item prop="custName">
                <el-input v-model="queryForm.custName" clearable placeholder="客户名称" />
              </el-form-item>
              <el-form-item label="" prop="custIndustry">
                <el-select v-model="custIndustry" placeholder="请选择客户行业" style="width: 100%">
                  <el-option
                    v-for="item in industryOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button icon="el-icon-search" type="primary" @click="queryData">查询</el-button>
                <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
              </el-form-item>
            </el-form>
          </vab-query-form-top-panel>
        </vab-query-form>

        <vab-query-form-left-panel>
          <el-button icon="el-icon-plus" type="primary" @click="handleEdit($event)">添加</el-button>
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <el-button icon="el-icon-download" />
          <table-tool :check-list.sync="checkList" :columns="columns" />
        </vab-query-form-right-panel>

        <el-table
          v-loading="listLoading"
          border
          :data="list"
          style="width: 100%; height: 500px"
          @selection-change="setSelectRows">
          <el-table-column
            v-for="(item, index) in finallyColumns"
            :key="index"
            align="center"
            :label="item.label"
            :prop="item.prop"
            show-overflow-tooltip
            :sortable="item.sortable"
            :width="item.width">
            <template #default="{ row }">
              <span>{{ row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" show-overflow-tooltip width="85">
            <template #default="{ row }">
              <el-button type="text" @click="handleEdit(row)">编辑</el-button>
              <el-button type="text" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
          <template #empty>
            <el-image class="vab-data-empty" :src="require('@/assets/empty_images/data_empty.png')" />
          </template>
        </el-table>
        <el-pagination
          background
          :current-page="queryForm.pageNum"
          :layout="layout"
          :page-size="queryForm.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </el-col>
    </el-row>
    <edit ref="edit" @fetch-data="fetchData" />

    <reg-edit ref="reg-edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import Edit from './components/RegionEdit'
  import RegEdit from './components/RegEdit'
  import regionApi from '@/api/base/region/region'
  import TableTool from '@/components/table/TableTool'

  export default {
    name: 'Distr',
    components: { Edit, RegEdit, TableTool },
    data() {
      return {
        current: '',
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        filterText: '',
        custIndustry: '', // 客户行业  (没数据)
        queryForm: {
          pageNum: 1,
          pageSize: 10,
          userName: '',
        },
        deptOptions: undefined,
        defaultProps: {
          id: 'id',
          regionCode: 'regionCode',
          label: 'regionDesc',
        },
        treeDefaultExpandAll: true,
        regionId: 0,
        industryOptions: [], //客户行业

        checkList: [],
        columns: [
          {
            label: '省份',
            width: '100px',
            prop: 'distName',
            sortable: false,
          },
          {
            label: '客户数量',
            width: 'auto',
            prop: 'count',
            sortable: false,
            disableCheck: true,
          },
        ],
      }
    },

    computed: {
      height() {
        return this.$baseTableHeight(10)
      },
      finallyColumns() {
        console.log('finallyColums')
        return this.columns.filter((item) => this.checkList.includes(item.label))
      },
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      },
    },
    created() {
      this.fetchData()
      this.getRegion()
      this.getOptions()
    },
    methods: {
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          custCode: '',
          custName: '',
          custIndustry: '',
        }
      },
      getOptions() {
        Promise.all([this.getDicts('CustomerIndustry')])
          .then(([industry]) => {
            this.industryOptions = industry.data.values || []
          })
          .catch((err) => console.log(err))
      },
      async getRegion() {
        const { data: data } = await regionApi.getRegion({})
        var first_id = data.list[0].id

        console.log('区域', first_id)
        this.deptOptions = data.list
        this.queryForm.regionId = first_id //data.list[0].id
        this.$refs['edit'].setRegion(first_id)
        //默认第一选中
        this.$nextTick(() => {
          this.$refs.tree.setCurrentKey(first_id)
        })
        this.fetchData()
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true
        return data[this.defaultProps.label].indexOf(value) !== -1
      },
      // 节点单击事件
      handleNodeClick(data) {
        console.log('ID', data.id)
        this.$refs['edit'].setRegion(data.id)
        this.queryForm.regionId = data.id
        this.fetchData()
      },

      setSelectRows(val) {
        this.selectRows = val
      },
      getCheckedNodes() {
        this.$refs['reg-edit'].showEdit()
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.id) {
          console.log('deletedId', row.id)
          this.$baseConfirm('你确定要删除当前项吗', null, async () => {
            const { msg } = await regionApi.doDelete({ ids: row.id })
            this.$baseMessage(msg, 'success', 'vab-hey-message-success')
            await this.fetchData()
          })
        } else {
          if (this.selectRows.length > 0) {
            const ids = this.selectRows.map((item) => parseInt(item.id))
            console.log(ids)
            this.$baseConfirm('你确定要删除选中项吗', null, async () => {
              const { msg } = await regionApi.doDelete({ ids })
              this.$baseMessage(msg, 'success', 'vab-hey-message-success')
              await this.fetchData()
            })
          } else {
            this.$baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        console.log('ffff')
        this.queryForm.pageNum = 1
        this.fetchData()
      },

      async fetchData() {
        this.listLoading = true
        const {
          data: { list, total },
        } = await regionApi.getList(this.queryForm)
        this.list = list
        this.total = total
        this.listLoading = false
      },
    },
  }
</script>
<style>
  .el-tree-node:focus > .el-tree-node__content {
    /*设置选中的样式 */
    background-color: #dde9ff !important;
  }

  .el-tree-node__content:hover {
    /*设置鼠标飘过的颜色 */
    background: #eaf9ff !important;
    color: #007bff;
  }

  .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
    /*current选中的样式 */
    color: #4d95fd;
    font-weight: bold;
    background-color: #dde9ff !important;
  }

  .el-form-item__content {
    margin-right: 3px;
  }

  .vab-query-form[data-v-64063760] .el-form-item:first-child .el-form-item--small {
    margin: 0 10px 10px 0 !important;
  }
</style>
