<template>
  <div class="customer-wrap">
    <div class="nav_box">
      <el-radio-group v-model="activeTab" class="header-radio" @input="handleTabChange">
        <el-radio-button
          label="mine"
          :disabled="!isHeadCustGroupAdmin"
          :class="{ 'btn-disabled': !isHeadCustGroupAdmin }"
        >
          我创建的
        </el-radio-button>
        <el-radio-button
          label="sharedToMe"
          :disabled="isHeadCustGroupAdmin"
          :class="{ 'btn-disabled': isHeadCustGroupAdmin }"
        >
          下发给我的
        </el-radio-button>
      </el-radio-group>
    </div>

    <div v-show="showSearch" class="search-area">
      <el-form
        ref="queryForm"
        :model="queryParams"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="客群名称" prop="groupName">
          <el-input
            v-model="queryParams.groupName"
            placeholder="请输入客群名称"
            clearable
            style="width: 200px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="客群模式" prop="groupMode">
          <el-select
            v-model="queryParams.groupMode"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="静态" value="0" />
            <el-option label="动态" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="客群状态" prop="groupStatus">
          <el-select
            v-model="queryParams.groupStatus"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="正常" value="0" />
            <el-option label="已禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="客群标签" prop="groupTags">
          <el-select
            v-model="queryParams.groupTags"
            placeholder="请选择"
            clearable
            filterable
            style="width: 150px"
          >
            <el-option
              v-for="tag in allTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <section class="operate-cnt">
      <div class="operate-left">
        <template v-if="isMineTab">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="handleAdd">
            新增
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="small"
            :disabled="multiple"
            @click="handleDelete"
          >
            删除
          </el-button>
        </template>
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </section>

    <div class="main_table">
      <el-table
        v-loading="loading"
        :data="groupList"
        style="width: 100%"
        max-height="625"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-if="isMineTab"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column label="客群名称" prop="groupName" width="120" show-overflow-tooltip />
        <el-table-column label="客群模式" align="center" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.groupMode === '0'" type="info" size="small">静态</el-tag>
            <el-tag v-else-if="scope.row.groupMode === '1'" type="success" size="small">动态</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="客户数量" align="center" prop="custCount" width="120" />
        <el-table-column label="客群状态" align="center" width="120">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.groupStatus === '0'" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="scope.row.groupStatus === '1'" type="danger" size="small">已禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="客群标签" min-width="150">
          <template slot-scope="scope">
            <template v-if="scope.row.groupTags">
              <el-tag
                v-for="tag in scope.row.groupTags.split(',')"
                :key="tag"
                size="small"
                style="margin-right: 5px; margin-bottom: 3px"
              >
                {{ tag.trim() }}
              </el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="创建者" prop="nickName" width="120" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >
              查看
            </el-button>
            <template v-if="isMineTab">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <create-dialog
      :visible.sync="dialogVisible"
      :group-data="form"
      :is-edit="isEdit"
      @submit="handleSubmit"
    />
  </div>
</template>

<script>
import { listCustGroup, getCustGroup, deleteCustGroup, getAllGroupTags } from '@/api/group/custGroup'
import { mapGetters } from 'vuex'
import CreateDialog from './components/create-dialog'

export default {
  name: 'CustGroup',
  components: { CreateDialog },
  data() {
    return {
      loading: false,
      showSearch: true,
      activeTab: 'mine',
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      groupList: [],
      dialogVisible: false,
      isEdit: false,
      form: {},
      refreshTimer: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        groupName: null,
        groupMode: null,
        groupStatus: null,
        groupTags: null,
        viewType: 'mine'
      },
      // 所有标签列表
      allTags: []
    }
  },
  computed: {
    ...mapGetters(['roles']),
    isHeadCustGroupAdmin() {
      return ['headAdmin', 'headPublic', 'headPrivate', 'headOps'].some(role => this.roles.includes(role))
    },
    isMineTab() {
      return this.activeTab === 'mine'
    }
  },
  created() {
    this.activeTab = this.resolveTab(this.$route.query.tab)
    this.getList()
    this.loadAllTags()
  },
  watch: {
    '$route.query.refresh'() {
      this.activeTab = this.resolveTab(this.$route.query.tab)
      this.queryParams.pageNum = 1
      this.getList()
    },
    roles() {
      const nextTab = this.resolveTab(this.activeTab)
      if (nextTab !== this.activeTab) {
        this.activeTab = nextTab
      }
    }
  },
  beforeDestroy() {
    this.clearRefreshTimer()
  },
  methods: {
    resolveTab(tab) {
      if (!this.isHeadCustGroupAdmin) {
        return 'sharedToMe'
      }
      return tab === 'sharedToMe' ? 'sharedToMe' : 'mine'
    },

    clearRefreshTimer() {
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer)
        this.refreshTimer = null
      }
    },

    refreshList(delay = 0) {
      this.clearRefreshTimer()
      if (delay > 0) {
        this.refreshTimer = setTimeout(() => {
          this.getList()
          this.refreshTimer = null
        }, delay)
        return
      }
      this.getList()
    },

    getList() {
      this.loading = true
      this.activeTab = this.resolveTab(this.activeTab)
      this.queryParams.viewType = this.activeTab
      listCustGroup(this.queryParams).then(response => {
        this.groupList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /** 加载所有标签列表 */
    loadAllTags() {
      getAllGroupTags().then(response => {
        this.allTags = response.data || []
      }).catch(() => {
        this.allTags = []
      })
    },

    handleTabChange() {
      this.activeTab = this.resolveTab(this.activeTab)
      this.ids = []
      this.single = true
      this.multiple = true
      this.queryParams.pageNum = 1
      this.queryParams.viewType = this.activeTab
      this.getList()
    },

    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.queryParams.viewType = this.activeTab
      this.handleQuery()
    },

    handleSelectionChange(selection) {
      if (!this.isMineTab) {
        this.ids = []
        this.single = true
        this.multiple = true
        return
      }
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    handleAdd() {
      this.reset()
      this.isEdit = false
      this.dialogVisible = true
    },

    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids[0]
      getCustGroup(id).then(response => {
        this.form = response.data
        this.isEdit = true
        this.dialogVisible = true
      })
    },

    handleView(row) {
      this.$router.push({
        path: '/group/custGroup/detail',
        query: { groupId: row.id, viewType: this.resolveTab(this.activeTab) }
      })
    },

    handleDelete(row) {
      const ids = row.id ? [row.id] : this.ids
      this.$modal.confirm('是否确认删除选中的客群？').then(() => {
        return deleteCustGroup(ids)
      }).then(() => {
        if (this.groupList.length <= ids.length && this.queryParams.pageNum > 1) {
          this.queryParams.pageNum -= 1
        }
        this.ids = []
        this.single = true
        this.multiple = true
        this.refreshList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },

    handleSubmit() {
      this.dialogVisible = false
      this.queryParams.pageNum = 1
      this.refreshList(800)
    },

    reset() {
      this.form = {
        id: null,
        groupName: null,
        groupMode: '0',
        groupStatus: '0',
        shareEnabled: 0,
        shareDeptIdList: [],
        remark: null,
        validTime: null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.customer-wrap {
  background-color: #ffffff;
  overflow: hidden;
  box-shadow: 0 3px 8px 0 #00000017;
  border-radius: 16px 16px 0 0;
  padding: 0 30px 24px;

  .nav_box {
    overflow: hidden;
    margin: 0 -30px 8px;
    border-radius: 16px 16px 0 0;

    .header-radio {
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid #ebebeb;

      .btn-disabled {
        ::v-deep .el-radio-button__inner {
          background-color: #e7e7e7;
          color: #999999;
          cursor: not-allowed;
        }
      }

      .el-radio-button {
        flex: 1;

        ::v-deep .el-radio-button__inner {
          width: 100%;
          border: none;
          font-weight: 400;
          letter-spacing: 0.44px;
          line-height: 25px;
          font-size: 16px;
          color: #666666;
          padding: 11px 0 12px 0;
          border-radius: 0;
          box-shadow: none;
        }

        ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
          background-color: #4886f8;
          font-weight: 400;
          color: #ffffff;
          border-bottom-left-radius: 0;
          border-bottom-right-radius: 0;
        }

        &:nth-child(2) {
          &::before,
          &::after {
            content: '';
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            height: 21px;
            width: 1px;
            background: #ebebeb;
            z-index: 1;
          }

          &::after {
            right: 1px;
          }
        }

        &.is-active {
          &::before,
          &::after {
            content: none;
          }
        }
      }
    }
  }

  .search-area {
    padding: 16px 0;
    border-bottom: 1px solid #ebebeb;
    margin-bottom: 16px;

    .el-form {
      margin-bottom: -8px;

      .el-form-item {
        margin-bottom: 8px;
      }
    }
  }

  .operate-cnt {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 24px 0 16px 0;

    .operate-left {
      display: flex;
      gap: 8px;
      min-height: 32px;
    }

    .el-button {
      border-radius: 4px;
    }
  }

  .main_table {
    ::v-deep .el-pagination {
      margin-top: 15px;
    }
  }
}
</style>
