<template>
  <div style="margin-left: 10px">
    <el-form>
      <el-button @click="backTo">返回</el-button>
    </el-form>
    <el-form class="select-container" v-show="showSearch">
      <div class="queryBox">
        <el-form-item label="客户号:" label-width="80px" style="display: flex">
          <el-input v-model="queryParams.custId" clearable @clear="onSearch" @keyup.enter.native="onSearch"></el-input>
        </el-form-item>
        <el-form-item label="客户名:" label-width="80px" style="display: flex">
          <el-input v-model="queryParams.custName" clearable @clear="onSearch" @keyup.enter.native="onSearch"></el-input>
        </el-form-item>
        <el-form-item label="分配状态:" label-width="100px" style="display: flex">
          <el-select v-model="queryParams.distributeTag" clearable @change="onSearch" @clear="onSearch">
            <el-option
              v-for="(item, index) in StateOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-form style="margin-bottom: 8px">
      <el-button type="primary" @click="distributeBatch" :disabled="multipleSelection.length === 0">批量分配</el-button>
      <el-button type="danger" @click="relieveBatch" :disabled="multipleSelection.length === 0">批量解除</el-button>
      <el-button type="primary" @click="importOut">导出</el-button>
      <!-- <download-btn type="text" icon="el-icon-bottom" btnName="导出" :downloadUrl="exportUrl" :paramsObj="exportParams"></download-btn> -->
      <!-- <el-button type="primary" @click="disDistributed">未分配</el-button> -->
      <right-toolbar :showSearch.sync="showSearch" :columns="columns" @queryTable="getList"></right-toolbar>
    </el-form>
    <el-table v-loading="loading" :data="tableData" class="table" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <template v-for="item in columns">
        <el-table-column v-if="item.visible" :prop="item.name" :label="item.label" :key="item.name"> </el-table-column>
      </template>
      <el-table-column label="操作">
        <template class="operate" #default="scope">
          <el-button type="text" @click.prevent="onDistributed(scope.row)" style="margin-right: 8px">分配</el-button>
          <el-popconfirm title="确定解除吗？" icon="el-icon-info" iconColor="red" @confirm="deleteClient(scope.row)">
            <el-button slot="reference" type="text" :disabled="!scope.row.belongUserName">解除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    <modal-cnt ref="modalCnt" :detailArr="detailArr" titleName="分配负责人员" @onRefresh="onReset"></modal-cnt>
  </div>
</template>
<script>
import { getCustManageData, downloadFile, custManageOperate, upanddel } from '@/api/grid/list/gridlist'
import ModalCnt from './modal-cnt'
import { gridPatternMap } from './../../constant-info'
import { commonCol, virtualCol, appendColumns } from './constant-info'
import { cloneDeep, isEmpty } from 'lodash'

export default {
  components: { ModalCnt },
  computed: {
    detailInfoObj() {
      return JSON.parse(sessionStorage.getItem('detailInfoObj'))
    },
    exportUrl() {
      return downloadFile
    },
    exportParams() {
      return {
        custDistributeList: ['98']
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        custId: null,
        custName: null,
        distributeTag: null
      },
      StateOptions: [
        { value: '0', label: '其它' },
        { value: '1', label: '未分配' }
      ],
      tableData: [],
      multipleSelection: [],
      detailArr: [],
      columns: []
    }
  },
  mounted() {
    this.getList()
    this.columns = this.getColumns()
  },
  methods: {
    getColumns() {
      const newArr = cloneDeep(appendColumns)
      if (this.detailInfoObj.gridPattern === '3') {
        newArr.splice(1, 0, ...virtualCol)
        return newArr?.map((ot, oInd) => ({
          ...ot,
          key: oInd
        }))
      } else {
        newArr.splice(1, 0, ...commonCol)
        return newArr?.map((ot, oInd) => ({
          ...ot,
          key: oInd
        }))
      }
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      const params = {
        gridPattern: this.detailInfoObj.gridPattern,
        gridLevel: this.detailInfoObj.gridLevel,
        gridId: this.detailInfoObj.gridId,
        gridName: this.detailInfoObj.gridName,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        distributeTag: this.queryParams.distributeTag,
        custId: this.queryParams.custId,
        custName: this.queryParams.custName
      }
      getCustManageData(params)
        .then((res) => {
          console.log(res)
          this.tableData = res?.rows?.map((ot) => ({
            ...ot,
            gridPattern: gridPatternMap[ot.gridPattern]
          }))
          this.total = res.total
        })
        .catch((err) => console.error(err))
        .finally(() => {
          setTimeout(() => {
            this.loading = false
          }, 100)
        })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.detailArr = val?.map((ot) => ({
        custIds: ot.custId,
        custPatterns: ot.custPattern,
        belongBranchId: ot.belongBranchId,
        belongUserName: ot.belongUserName
      }))
    },
    backTo() {
      this.$router.go(-1)
    },
    onSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    onReset() {
      this.queryParams.pageNum = 1
      this.queryParams.distributeTag = ''
      this.queryParams.custId = ''
      this.queryParams.custName = ''
      this.getList()
    },
    distributeBatch() {
      this.$refs.modalCnt.onOpen()
    },
    relieveBatch() {
      const resultArr = this.detailArr.filter((ot) => !ot.belongUserName)
      if (!isEmpty(resultArr)) {
        return this.$message.warning('所选列表存在归属客户经理为空时无法解除，请重新选择')
      }
      const params = {}
      params.custIds = this.detailArr?.map((ot) => ot.custIds)
      params.custPatterns = this.detailArr?.map((ot) => ot.custPatterns)
      params.belongUserNames = []
      params.belongUserIds = []
      this.doDel(params)
    },
    importOut() {
      this.download(
        `/system/gridSelect/exportList?gridPattern=${this.detailInfoObj.gridPattern}&gridLevel=${this.detailInfoObj.gridLevel}&gridId=${this.detailInfoObj.gridId}&gridName=${this.detailInfoObj.gridName}`,
        {},
        `${this.detailInfoObj.gridName}_${new Date().getTime()}.xlsx`
      )
    },
    onDistributed(row) {
      this.detailArr = [
        {
          custIds: row.custId,
          custPatterns: row.custPattern,
          belongBranchId: row.belongBranchId
        }
      ]
      this.$refs.modalCnt.onOpen()
    },
    disDistributed() {},
    async deleteClient(row) {
      this.doDel({
        custIds: [row.custId],
        custPatterns: [row.custPattern],
        belongUserNames: [],
        belongUserIds: []
      })
    },
    async doDel(params) {
      const res = await upanddel(params)
      if (res.code === 200) {
        this.$message.success('解除成功')
        this.onReset()
      } else {
        this.$message.error(res.msg)
      }
    }
  }
}
</script>
<style  lang="scss" scoped>
.select-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20px;
}
.queryBox {
  display: flex;
  justify-content: space-between;
  width: 60%;
  ::v-deep .el-form-item__label {
    display: inline-block;
    white-space: nowrap;
  }
  ::v-deep .el-form-item__content {
    margin-left: 0 !important;
  }
}
.batch-button {
  background-color: #409eff;
  color: white;
}
.distributed-button {
  border-radius: 0;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  border-top-right-radius: 20px;
  border-bottom-right-radius: 20px;
  background-color: #94c9ff;
  color: black;
}
.table {
  width: 100%;
  margin: 20px;
  text-align: center;
  vertical-align: middle;
}
a {
  margin: 5px;
}
</style>
