<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
      <el-form-item label="成员名称" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入成员名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属客服组" prop="appCustomerId">
        <el-select
          v-model="queryParams.appCustomerId"
          placeholder="请选择客服组"
          clearable
          filterable
          size="small"
        >
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.roleName"
            :value="parseRoleId(item.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          v-hasPermi="['app:customerMember:add']"-->
<!--          @click="handleAdd"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          v-hasPermi="['app:customerMember:edit']"
          @click="handleUpdate()"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          v-hasPermi="['app:customerMember:remove']"
          @click="handleDelete()"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          :loading="syncLoading"
          v-hasPermi="['app:customerMember:add']"
          @click="handleSyncSales"
        >同步销售</el-button>
        <el-tooltip
          effect="dark"
          content="该按钮初次同步可能较慢，后续再次同步只会新增新的销售数据"
          placement="top"
        >
          <i class="el-icon-question sync-sales-tip"></i>
        </el-tooltip>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" row-key="roleMemberId" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="所属客服组" align="center" prop="roleName" min-width="140" />
<!--      <el-table-column label="成员名称" align="center" prop="memberName" min-width="120" />-->
      <el-table-column label="绑定销售" align="center" prop="companyUserName" min-width="140" show-overflow-tooltip />
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.avatar"
            style="width: 50px; height: 50px; border-radius: 4px;"
            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]"
            fit="cover"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="remark" min-width="160" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['app:customerMember:edit']"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['app:customerMember:remove']"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属客服组" prop="appCustomerId">
          <el-select
            v-model="form.appCustomerId"
            placeholder="请选择所属客服组"
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="parseRoleId(item.id)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定销售" prop="companyUserId">
          <el-input
            v-model="form.companyUserName"
            placeholder="请选择绑定销售"
            readonly
            @click.native="openBindCompanyUserDialog"
          >
            <i slot="suffix" class="el-input__icon el-icon-search" @click.stop="openBindCompanyUserDialog"></i>
          </el-input>
        </el-form-item>
<!--        <el-form-item label="成员名称" prop="memberName">-->
<!--          <el-input v-model="form.memberName" placeholder="请输入成员名称" />-->
<!--        </el-form-item>-->
        <el-form-item label="头像" prop="avatar">
          <ImageUpload
            v-model="form.avatar"
            type="image"
            :limit="1"
            :file-size="1"
            :width="150"
            :height="150"
          />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择绑定销售" :visible.sync="bindCompanyUserOpen" width="500px" append-to-body>
      <el-form ref="bindCompanyUserForm" :model="bindCompanyUserForm" :rules="bindCompanyUserRules" label-width="100px">
        <el-form-item label="选择公司" prop="companyId">
          <el-select
            v-model="bindCompanyUserForm.companyId"
            placeholder="请选择公司"
            filterable
            style="width: 100%;"
            @change="handleBindCompanyChange"
          >
            <el-option
              v-for="item in companyOptions"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择销售" prop="companyUserId">
          <el-select
            v-model="bindCompanyUserForm.companyUserId"
            placeholder="请选择销售"
            filterable
            style="width: 100%;"
          >
            <el-option
              v-for="item in companyUserOptions"
              :key="item.userId"
              :label="item.nickName + '_' + item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBindCompanyUserForm">确 定</el-button>
        <el-button @click="cancelBindCompanyUser">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCustomerMember,
  addCustomerMember,
  updateCustomerMember,
  delCustomerMember,
  syncSalesCustomerMember,
  getSyncSalesCustomerMemberStatus
} from '@/api/app/customerMember'
import { listCustomerRoleOptions } from '@/api/app/customerRole'
import { getCompanyList, getCompanyUserList } from '@/api/company/companyUser'
import ImageUpload from '@/views/qw/sop/ImageUpload'

export default {
  name: 'CustomerMember',
  components: { ImageUpload },
  data() {
    return {
      loading: true,
      syncLoading: false,
      syncTimer: null,
      showSearch: true,
      total: 0,
      ids: [],
      single: true,
      multiple: true,
      memberList: [],
      roleOptions: [],
      companyOptions: [],
      companyUserOptions: [],
      bindCompanyUserOpen: false,
      bindCompanyUserForm: {
        companyId: null,
        companyUserId: null
      },
      bindCompanyUserRules: {
        companyId: [
          { required: true, message: '请选择公司', trigger: 'change' }
        ],
        companyUserId: [
          { required: true, message: '请选择销售', trigger: 'change' }
        ]
      },
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        appCustomerId: null
      },
      form: {},
      rules: {
        appCustomerId: [
          { required: true, message: '请选择所属客服组', trigger: 'change' }
        ],
        companyUserId: [
          { required: true, message: '请选择绑定销售', trigger: 'change' }
        ],
        // memberName: [
        //   { required: true, message: '成员名称不能为空', trigger: 'blur' }
        // ]
      }
    }
  },
  created() {
    this.loadRoleOptions()
    this.getList()
  },
  beforeDestroy() {
    this.clearSyncTimer()
  },
  methods: {
    clearSyncTimer() {
      if (this.syncTimer) {
        clearInterval(this.syncTimer)
        this.syncTimer = null
      }
    },
    handleSyncSales() {
      this.$confirm('是否确认同步销售数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.syncLoading = true
        return syncSalesCustomerMember()
      }).then(response => {
        if (response.code !== 200) {
          this.syncLoading = false
          this.msgError(response.msg || '提交同步任务失败')
          return
        }
        this.msgSuccess('同步任务已提交，同步中。。。')
        this.clearSyncTimer()
        this.syncTimer = setInterval(() => {
          this.pollSyncSalesStatus()
        }, 2000)
        this.pollSyncSalesStatus()
      }).catch(() => {
        this.syncLoading = false
      })
    },
    pollSyncSalesStatus() {
      getSyncSalesCustomerMemberStatus().then(response => {
        if (response.code !== 200) {
          return
        }
        const data = response.data || {}
        if (data.status === 'running') {
          return
        }
        this.clearSyncTimer()
        this.syncLoading = false
        if (data.status === 'success') {
          this.msgSuccess(data.message || '同步完成')
          this.getList()
          this.loadRoleOptions()
        } else if (data.status === 'fail') {
          this.msgError(data.message || '同步失败')
        }
      }).catch(() => {
        this.clearSyncTimer()
        this.syncLoading = false
        this.msgError('查询同步状态失败')
      })
    },
    parseRoleId(value) {
      if (value === null || value === undefined || value === '') {
        return null
      }
      const num = Number(value)
      return Number.isNaN(num) ? value : num
    },
    loadRoleOptions() {
      listCustomerRoleOptions().then(response => {
        this.roleOptions = (response.rows || []).map(item => ({
          ...item,
          id: this.parseRoleId(item.id)
        }))
      })
    },
    getList() {
      this.loading = true
      listCustomerMember(this.queryParams).then(response => {
        this.memberList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    resetBindCompanyUserForm() {
      this.bindCompanyUserForm = {
        companyId: null,
        companyUserId: null
      }
      this.companyUserOptions = []
      this.$nextTick(() => {
        this.$refs.bindCompanyUserForm && this.$refs.bindCompanyUserForm.clearValidate()
      })
    },
    openBindCompanyUserDialog() {
      getCompanyList().then(response => {
        if (response.code === 200) {
          this.companyOptions = response.data || []
          this.resetBindCompanyUserForm()
          this.bindCompanyUserOpen = true
        } else {
          this.msgError(response.msg || '获取公司列表失败')
        }
      }).catch(() => {
        this.msgError('获取公司列表失败')
      })
    },
    handleBindCompanyChange(companyId) {
      this.bindCompanyUserForm.companyUserId = null
      if (!companyId) {
        this.companyUserOptions = []
        return
      }
      getCompanyUserList({ companyId }).then(response => {
        if (response.code === 200) {
          this.companyUserOptions = response.data || []
        } else {
          this.msgError(response.msg || '获取销售列表失败')
          this.companyUserOptions = []
        }
      }).catch(() => {
        this.msgError('获取销售列表失败')
        this.companyUserOptions = []
      })
    },
    submitBindCompanyUserForm() {
      this.$refs.bindCompanyUserForm.validate(valid => {
        if (!valid) {
          return
        }
        const selected = this.companyUserOptions.find(
          item => item.userId === this.bindCompanyUserForm.companyUserId
        )
        this.form.companyUserId = this.bindCompanyUserForm.companyUserId
        this.form.companyUserName = selected
          ? `${selected.nickName}_${selected.userName}`
          : ''
        this.bindCompanyUserOpen = false
        this.$refs.form && this.$refs.form.validateField('companyUserId')
      })
    },
    cancelBindCompanyUser() {
      this.bindCompanyUserOpen = false
      this.resetBindCompanyUserForm()
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        roleMemberId: null,
        appCustomerId: null,
        companyUserId: null,
        companyUserName: null,
        avatar: null,
        remark: null
      }
      this.resetForm('form')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        keyword: null,
        appCustomerId: null
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roleMemberId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增客服'
    },
    handleUpdate(row) {
      const target = row || this.memberList.find(item => item.roleMemberId === this.ids[0])
      if (!target) {
        return
      }
      this.form = {
        roleMemberId: target.roleMemberId,
        appCustomerId: target.appCustomerId != null && target.appCustomerId !== ''
          ? this.parseRoleId(target.appCustomerId)
          : null,
        companyUserId: target.companyUserId,
        companyUserName: target.companyUserName,
        avatar: target.avatar,
        remark: target.remark
      }
      this.open = true
      this.title = '修改客服'
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate()
      })
    },
    handleDelete(row) {
      const ids = row ? row.roleMemberId : this.ids.join(',')
      this.$confirm('是否确认删除选中的客服数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delCustomerMember(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    },
    buildSubmitData() {
      const data = {
        appCustomerId: this.parseRoleId(this.form.appCustomerId),
        avatar: this.form.avatar,
        remark: this.form.remark,
        companyUserId: this.form.companyUserId,
        companyUserName: this.form.companyUserName
      }
      if (this.form.roleMemberId != null) {
        data.roleMemberId = this.form.roleMemberId
      }
      return data
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const data = this.buildSubmitData()
        const request = this.form.roleMemberId != null
          ? updateCustomerMember(data)
          : addCustomerMember(data)
        request.then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.form.roleMemberId != null ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          } else {
            this.msgError(response.msg || '保存失败')
          }
        })
      })
    }
  }
}
</script>

<style scoped>
.el-input__icon {
  cursor: pointer;
}
.sync-sales-tip {
  margin-left: 6px;
  color: #909399;
  cursor: pointer;
  font-size: 14px;
  vertical-align: middle;
}
</style>
