<template>
  <div class="user-management">
    <router-view />
    <template v-if="!$route.params.id">
      <div>
        <div class="search">
          <div class="left" />
          <div class="right">
            <div>
              <el-input v-model="search.mark" style="width: 250px" placeholder="用户ID/手机号码" clearable />
            </div>
            <div>
              <el-select v-model="search.useMoney" style="width: 100%" placeholder="在途支用" clearable>
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </div>
            <div>
              <el-input v-model="search.managerName" style="width: 250px" placeholder="业务经理/风控经理" clearable />
            </div>
            <div class="leftBtn">
              <el-button type="primary" @click="fetchData">查询</el-button>
            </div>
            <div class="leftBtn">
              <el-button v-power="'batch_change_projectManager'" type="primary" @click="batchHandoverPM">批量移交业务经理</el-button>
            </div>
            <div class="leftBtn">
              <el-button v-power="'batch_change_riskManager'" type="primary" @click="batchHandoverRM">批量移交风控经理</el-button>
            </div>
          </div>
        </div>

        <div class="table-box">
          <cy-comm-table
            ref="commTable"
            v-loading="loading"
            :columns="columns"
            :table-options="tableOptions"
            :data="tableData"
            :count="total"
          />
        </div>
      </div>
    </template>

    <!-- 认领 -->
    <cy-dialog ref="receiveDialog" title="认领确认">
      <p style="text-align: center;">确认认领该用户，完成后续业务跟进么？</p>
      <div class="submit-btn">
        <el-button @click="$refs.receiveDialog.show = false">关闭</el-button>
        <el-button type="primary" @click="receiveSure">确定</el-button>
      </div>
    </cy-dialog>

    <!-- 分配-移交 -->
    <cy-dialog ref="assignDialog" title="选择人员" @close="$refs.ruleForm.resetFields()">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-position="top"
        label-width="150px"
        class="rule-form-orange"
      >
        <el-form-item :label="personType == 'PM'?'业务经理':'风控经理'" prop="userId" style="width: 100%">
          <el-select v-model="ruleForm.userId" style="width: 100%" placeholder="请选择人员">
            <el-option
              v-for="(item, index) in personList"
              :key="index + 'PM'"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="submit-btn">
        <el-button @click="$refs.assignDialog.show = false; $refs.ruleForm.resetFields()">关闭</el-button>
        <el-button type="primary" @click="assignSure">确定</el-button>
      </div>
    </cy-dialog>

    <!-- 重置密码 -->
    <cy-dialog ref="pwdDialog" title="重置密码">
      <p style="text-align: center;">确认重置密码？</p>
      <div class="submit-btn">
        <el-button @click="$refs.pwdDialog.show = false">关闭</el-button>
        <el-button type="primary" @click="resetSure">确定</el-button>
      </div>
    </cy-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import indexTable from './indexTable'
import { getUserList, receiveTask, getPMList, getRMList, distributeRM, batchDistributeRMs, distributePM, batchDistributePMs, resetPassword } from '@/api/userManage/index'

export default {
  name: 'UserManagement',
  mixins: [indexTable],
  data() {
    return {
      search: {
        mark: '',
        useMoney: '',
        managerName: ''
      },
      receiveInfo: {},
      personList: [],
      projectManagers: [],
      riskManagers: [],
      ruleForm: {
        id: '',
        userId: null
      },
      rules: {
        userId: [{ required: true, message: '请选择人员', trigger: 'change' }]
      },

      handleType: '',
      personType: ''

    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.fetchData()
    this.getPorjectManagers()
    this.getRiskManagers()
  },
  methods: {
    fetchData() {
      this.loading = true
      const params = {
        ...this.search,
        page: this.page,
        rows: this.size
      }
      getUserList(params).then(({ rows, records }) => {
        // rows.map(item => {
        //   item.mainCompany = item.list.map(ele => {
        //     return ele.mainCompany
        //   })
        // })
        this.tableData = rows || []
        this.total = records
        this.loading = false
      })
    },

    handlerOperate(type, row) {
      if (type === 'receive') { // 认领
        this.receive(row)
      } else if (type === 'reset') {
        this.resetPwd(row)
      } else {
        this.assign(type, row.id)
      }
    },

    // 认领
    receive(info) {
      this.receiveInfo = info
      this.$refs.receiveDialog.show = true
    },

    // 重置密码
    resetPwd(info) {
      this.receiveInfo = info
      this.$refs.pwdDialog.show = true
    },

    // 确认认领
    receiveSure() {
      const clientUserId = this.receiveInfo.id
      receiveTask(clientUserId).then(res => {
        if (res.success) {
          this.$message.success('认领成功')
          this.$refs.receiveDialog.show = false
          this.fetchData()
        } else {
          this.$message.warning(res.msg)
          this.$refs.receiveDialog.show = false
        }
      })
    },

    // 确认重置
    resetSure() {
      const clientUserId = this.receiveInfo.id
      resetPassword({ clientUserId }).then(res => {
        if (res.success) {
          this.$message.success('重置成功')
          this.$refs.pwdDialog.show = false
          // this.fetchData()
        } else {
          this.$message.warning(res.msg)
          this.$refs.pwdDialog.show = false
        }
      })
    },

    // 分配-移交
    assign(type, id) {
      this.ruleForm.id = id
      this.handleType = type
      if (type === 'assignPM') { // 分配业务经理
        this.personType = 'PM'
        this.personList = this.projectManagers
      } else if (type === 'handoverPM') { // 移交业务经理
        this.personType = 'PM'
        this.personList = this.projectManagers
      } else if (type === 'handoverRM') { // 移交风控经理
        this.personType = 'RM'
        this.personList = this.riskManagers
      } else if (type === 'handoverPMBatch') { // 批量业务
        this.personType = 'PM'
        this.personList = this.projectManagers
      } else if (type === 'handoverRMBatch') { // 批量风控
        this.personType = 'RM'
        this.personList = this.riskManagers
      }

      this.$refs.assignDialog.show = true
    },

    // 确认分配-移交
    assignSure() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          if (this.handleType === 'assignPM') {
            distributePM(this.ruleForm.id, this.ruleForm.userId, false).then(({ data }) => {
              this.$message.success('提交成功')
              this.$refs.ruleForm.resetFields()
              this.$refs.assignDialog.show = false
              this.fetchData()
            })
          } else if (this.handleType === 'handoverPM') {
            distributePM(this.ruleForm.id, this.ruleForm.userId, true).then(({ data }) => {
              this.$message.success('提交成功')
              this.$refs.ruleForm.resetFields()
              this.$refs.assignDialog.show = false
              this.fetchData()
            })
          } else if (this.handleType === 'handoverRM') {
            distributeRM(this.ruleForm.id, this.ruleForm.userId).then(({ data }) => {
              this.$message.success('提交成功')
              this.$refs.ruleForm.resetFields()
              this.$refs.assignDialog.show = false
              this.fetchData()
            })
          } else if (this.handleType === 'handoverPMBatch') {
            const postData = {
              userIds: this.ruleForm.id,
              projectManagerId: this.ruleForm.userId
            }
            batchDistributePMs(postData).then(({ data }) => {
              this.$message.success('提交成功')
              this.$refs.ruleForm.resetFields()
              this.$refs.assignDialog.show = false
              this.fetchData()
            })
          } else if (this.handleType === 'handoverRMBatch') {
            const postData = {
              userIds: this.ruleForm.id,
              riskManagerId: this.ruleForm.userId
            }
            batchDistributeRMs(postData).then(({ data }) => {
              this.$message.success('提交成功')
              this.$refs.ruleForm.resetFields()
              this.$refs.assignDialog.show = false
              this.fetchData()
            })
          }
        }
      })
    },

    // 批量移交业务经理
    batchHandoverPM() {
      if (this.$refs.commTable.multipleSelection.length) {
        const users = this.$refs.commTable.multipleSelection
        const userIds = users.map(item => {
          return item.id
        })

        this.assign('handoverPMBatch', userIds)
      } else {
        this.$message.warning('请选择用户')
      }
    },

    // 批量移交风控经理
    batchHandoverRM() {
      if (this.$refs.commTable.multipleSelection.length) {
        const users = this.$refs.commTable.multipleSelection
        const userIds = users.map(item => {
          return item.id
        })

        this.assign('handoverRMBatch', userIds)
      } else {
        this.$message.warning('请选择用户')
      }
    },

    // 业务经理
    getPorjectManagers() {
      getPMList().then(({ data }) => {
        this.projectManagers = data || []
      })
    },

    // 风控经理
    getRiskManagers() {
      getRMList().then(({ data }) => {
        this.riskManagers = data || []
      })
    }

  }
}
</script>

<style lang="scss" scoped>
.user-management{

  .table-icon-box {
    .icon-orange {
    font-size: 18px!important;
  }
}
}
</style>
