<template>
    <div style="border-radius: 16px 16px 0 0;padding-bottom: 10px;" v-loading="loading">
      <el-radio-group v-model="gridType" style="width:100%" class="header-radio">
        <el-radio-button label="retail">零售</el-radio-button>
        <el-radio-button label="corporate">公司</el-radio-button>
        <el-radio-button label="corporate_account" v-if="is875">公司账户</el-radio-button>
      </el-radio-group>
      <el-form class="select-container" v-show="showSearch">
        <div class="queryBox">
            <el-form-item label="客户号:" label-width="80px" style="display: contents">
            <el-input v-model="queryParams.custId" style="width:100%" placehloder="请输入客户号" clearable @clear="onSearch" @keyup.enter.native="onSearch"></el-input>
            </el-form-item>
            <el-form-item label="客户名:" label-width="80px" style="display: contents">
            <el-input v-model="queryParams.custName" style="width:100%" clearable @clear="onSearch" @keyup.enter.native="onSearch"></el-input>
            </el-form-item>
            <el-form-item label="柜员号:" label-width="80px" style="display: contents">
            <el-input v-model="queryParams.tellerId" style="width:100%" clearable @clear="onSearch" @keyup.enter.native="onSearch"></el-input>
            </el-form-item>
            <el-form-item label="客户层级:" label-width="80px" style="display: contents">
            <el-select v-model="queryParams.custLevels" style="width:100%" clearable @clear="onSearch" @keyup.enter.native="onSearch">
              <el-option v-for="(item, index) in levelOptions" :key="index" :label="item" :value="item"></el-option>
            </el-select>
            </el-form-item>
            <!-- <el-form-item label="客户类型:" label-width="80px" style="display: contents">
            <el-select v-model="queryParams.custTypes" style="width:100%" multiple clearable @clear="onSearch" @keyup.enter.native="onSearch">
              <el-option v-for="(item, index) in typeOptions" :key="index" :label="item.label" :value="item.value"></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">
        <template v-if="isMove">
          <el-button type="primary" @click="transferBatch('move')" :disabled="multipleSelection.length === 0">批量移交</el-button>
          <el-button type="primary" @click="transferAll">全量移交</el-button>
        </template>
        <el-button type="primary" v-else @click="transferBatch('adjust')" :disabled="multipleSelection.length === 0">关系调整</el-button>
        <el-button type="primary" @click="customClaim">客户认领</el-button>
        <right-toolbar :showSearch.sync="showSearch" :columns="tableCloumns" @queryTable="getList"></right-toolbar>
      </el-form>
      <el-table ref="multipleTable" :data="tableData" :row-key="getRowKey" class="table" @selection-change="handleSelectionChange">
        <el-table-column type="selection" :reserve-selection="true" :selectable="selectable" width="55"></el-table-column>
        <template v-for="item in tableCloumns">
            <el-table-column v-if="item.visible" :prop="item.name" :label="item.label" :key="item.name">
              <template #default="scope" v-if="item.isMerged">
                <span>{{ scope.row.nickName }} {{ scope.row.userName }}</span>
              </template>
              <!-- <template #default="scope" v-else-if="item.label === '客户类型'">
                <span>{{ scope.row.custType==='0'?'个人':'商户' }}</span>
              </template> -->
              <template #default="scope" v-else-if="item.label === '客户号'">
                <el-button type="text" @click="handlePushCust(scope.row)">{{ scope.row.custId }}</el-button>
              </template>
            </el-table-column>
        </template>
        <el-table-column label="操作">
            <template class="operate" #default="scope">
            <el-button 
              type="text" 
              :disabled="!scope.row.transferFlag" 
              @click.prevent="onTransfer(scope.row)" 
              style="margin-right: 8px"
            >
              {{ isMove ? '移交' : '关系调整' }}
            </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
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        append-to-body
        width="60%"
        :title="batchType === 'move' ? '客户移交' : '关系调整'">
          <el-form ref="form" :model="clientForm" label-width="80px" style="margin-left: 10%">
            <el-form-item label="客户名称" v-if="!batchVisible && !isFullTransfer">
              <el-input v-model="clientForm.custName" class="dialog-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="客户号" v-if="!batchVisible && !isFullTransfer">
              <el-input v-model="clientForm.custId" class="dialog-input" disabled></el-input>
            </el-form-item>
            <el-form-item label="客户账号" v-if="gridType==='corporate_account' && !batchVisible && !isFullTransfer">
              <el-input v-model="clientForm.accountNo" class="dialog-input" disabled></el-input>
            </el-form-item>
            <el-table v-if="batchVisible && !isFullTransfer" :data="batchData" style="max-height: 230px; overflow: auto; margin-bottom: 10px">
              <el-table-column prop="custName" label="客户姓名"></el-table-column>
              <el-table-column prop="custId" label="客户号"></el-table-column>
              <el-table-column v-if="gridType==='corporate_account'" prop="accountNo" label="客户账号"></el-table-column>
            </el-table>
            <el-form-item label="移交到">
            <section class="user-info">
            <span>归属机构</span>
            <treeselect ref="orgTree" size="small" v-model="userDeptList" :options="deptOptions"
                placeholder="请选择" :show-count="true" noOptionsText="暂无数据" noResultsText="暂无数据" @select="(node) => onDeptTreeSelect(node)"
                @deselect="clearTreeSelect" @open="onOrgTreeFocus" :flat="false" />
            </section>
            <section class="user-info">
            <span>客户经理</span>
            <el-select @focus="onClientManagerFocus" ref="clientManager" v-model="authUser"
                :multiple-limit="0" size="small" filterable placeholder="请选择" class="input-box">
                <el-option v-for="option in managerOptions" :key="option.userId"
                :label="`${option.deptName}-${option.userName}-${option.nickName}`"
                :value="option.userName"></el-option>
            </el-select>
            </section>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="okHandler">确定</el-button>
          </div>
        </el-dialog>
        <el-dialog
        :visible.sync="claimVisible"
        :close-on-click-modal="false"
        @close="handleCancelClaim"
        append-to-body
        width="80%"
        title="客户认领">
          <el-form ref="form" :model="claimForm" label-width="160px" @submit.native.prevent>
            <el-form-item label="客户名/客户账号" style="position: relative">
              <el-input v-model="claimForm.custName" style="width: 300px" @clear="customClaim" @keyup.enter.native="customClaim"></el-input>
              <el-button type="primary" style="position: absolute; top: 0; left: 320px" @click="customClaim">查询</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="claimData" class="my-table" v-loading="loadingClaim" height="330" @selection-change="handleSelectionChangeClaim">
            <el-table-column type="selection" width="55px" :selectable="isRowSelectable" />
            <el-table-column prop="custId" label="客户号"></el-table-column>
            <el-table-column prop="accountNo" label="客户账号"></el-table-column>
            <el-table-column prop="custName" label="客户名"></el-table-column>
            <el-table-column label="现客户经理">
              <template #default="scope">
                {{ scope.row.nickName }} {{ scope.row.userName }}
              </template>
            </el-table-column>
            <el-table-column prop="claimStatus" label="禁选原因"></el-table-column>
          </el-table>
          <pagination v-show="totalClaim > 0" :total="totalClaim" :page.sync="claimForm.pageNum" :limit.sync="claimForm.pageSize" @pagination="customClaim" />
          <div slot="footer" class="dialog-footer">
            <el-button @click="handleCancelClaim">取消</el-button>
            <el-button type="primary" :disabled="multipleSelectionClaim.length===0" @click="okHandlerClaim">确定</el-button>
          </div>
        </el-dialog>
    </div>
</template>

<script>
import { gridCmpmList, gridCmpmTransferCreate, gridCmpmCustListTag, gridCmpmTransferClaimList, gridCmpmTransferCreateClaim, gridCmpmTransferAdjust } from '@/api/gridSearch/performanceGridSearch/index'
import { cloneDeep, isEmpty } from 'lodash'
import { systemUserDeptTreeAll } from '@/api/grid/address/tree.js'
import { getUserListByDeptIds } from "@/api/grid/region.js";
import { mapGetters } from "vuex";
export default {
  data() {
    return{
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        custId: null,
        custName: null,
        tellerId: null
        // custTypes: ['0', '1']
      },
      tableData: [],
      multipleSelection: [],
      columns: [
        // { label: `客户类型`, visible: true, name: 'custType' },
        { label: `客户号`, visible: true, name: 'custId' },
        { label: `客户姓名`, visible: true, name: 'custName' },
        { label: `客户层级`, visible: true, name: 'custLevel' },
        { label: `客户经理柜员号`, visible: true, name: 'userName', isMerged: true },
        { label: `网点名称`, visible: true, name: 'outletName' },
        { label: `支行名称`, visible: true, name: 'branchName' },
        { label: `客户来源`, visible: true, name: 'source' }
      ],
      dialogVisible: false,
      clientForm: {
        custName: '',
        custId: '',
        accountNo: ''
      },
      authUser: '',
      deptOptions: [],
      userDeptList: null,
      checkedArr: [], // 选择的机构ID
      managerOptions: [],
      prevUserName: '',
      gridType: 'retail',
      batchVisible: false,
      batchType: '',
      batchData: [],
      isFullTransfer: false,
      levelOptions: [],
      claimVisible: false,
      claimForm: {
        custName: '',
        pageNum: 1,
        pageSize: 10
      },
      totalClaim: 0,
      claimData: [],
      multipleSelectionClaim: [],
      loadingClaim: false,
      typeOptions: [
        { label:'个人', value:'0' },
        { label:'商户', value:'1' }
      ]
    }
  },
  computed: {
    ...mapGetters(["roles", 'userName']),
    // 海宁
    is875() {
      return this.userName.slice(0, 3) === '875'
    },
    isMove() {
      const isOk = ['outletAdmin', 'commonManager']
      const arr = isOk.filter(item => this.roles.findIndex(v => v === item) > -1)
      return arr.length > 0
    },
    tableCloumns() {
      const newCol = [...this.columns]
      newCol.splice(1,0,{ label: `账户号`, visible: true, name: 'accountNo' })
      return this.gridType === 'corporate_account' ? newCol : this.columns
    }
  },
  mounted() {
    this.getList()
    gridCmpmCustListTag({ gridType:this.gridType }).then(res => {
      this.levelOptions = res.data
    })
  },
  watch: {
    userDeptList(val) {
      if (!val) {
        this.managerOptions = []
        this.authUser = ''
      }
    },
    gridType(val) {
      this.getList()
      this.tabChange()
      gridCmpmCustListTag({ gridType:this.gridType }).then(res => {
        this.levelOptions = res.data
      })
    }
  },
  methods: {
    tabChange() {
      this.$refs.multipleTable.clearSelection()
      this.multipleSelection = []
      this.batchData = []
    },
    /** 查询用户列表 */
    getList() {
        this.loading = true
        const params = {
        //   custLevel: this.detailInfoObj.gridLevel,
          gridType: this.gridType,
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize,
          userName: this.queryParams.tellerId,
          // custTypes: this.queryParams.custTypes,
          custId: this.queryParams.custId,
          custName: this.queryParams.custName,
          custLevels: this.queryParams.custLevels
        }
        gridCmpmList(params)
          .then((res) => {
            this.tableData = res?.rows
            this.total = res.total
          })
          .catch((err) => console.error(err))
          .finally(() => {
            setTimeout(() => {
              this.loading = false
            }, 100)
          })
      },
      getDeptTreeSelect() {
        systemUserDeptTreeAll().then((response) => {
          this.deptOptions = response.data
        })
      },
      // 选择归属机构
      onDeptTreeSelect(node) {
        this.fetchSelectOptions([node.id]);
      },
      // 取消勾选归属机构
      clearTreeSelect(node) {
        const index = this.checkedArr.findIndex((id) => id === node.id);
        if (index > -1) {
          this.checkedArr.splice(index, 1);
        }
        const { children = [] } = node;
        if (children.length > 0) {
          children.map((child) => {
            const index = this.checkedArr.findIndex((id) => id === child.id);
            if (index > -1) {
              this.checkedArr.splice(index, 1);
            }
          });
        }
      },
      fetchSelectOptions(deptIds) {
        if (isEmpty(deptIds)) {
          return (this.managerOptions = []);
        }
        getUserListByDeptIds({ deptIds: deptIds }).then((response) => {
          this.managerOptions = response.data;
        });
      },
      onOrgTreeFocus() {
        // this.$refs.clientManager.blur()
      },
      onClientManagerFocus() {
        // this.$refs.orgTree.blurInput()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      selectable(row, index) {
        return row.transferFlag === true
      },
      getRowKey(row) {
        return row.id
      },
      onSearch() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      onReset() {
        this.queryParams.pageNum = 1
        this.queryParams.tellerId = ''
        this.queryParams.custId = ''
        this.queryParams.custName = ''
        this.queryParams.custLevels = ''
        // this.queryParams.custTypes = []
        this.getList()
      },
      onTransfer(row) {
        this.clientForm = {
          custName: row.custName,
          custId: row.custId,
          accountNo: row.accountNo,
          custType: row.custType,
          prevUserName: row.userName,
        }
        this.prevUserName = row.userName
        this.dialogVisible = true
        this.batchType = this.isMove ? 'move' : 'adjust'
        this.getDeptTreeSelect()
      },
      transferBatch(type) {
        this.batchVisible = true
        this.batchType = type
        this.batchData = this.multipleSelection.map(item => ({
            custName: item.custName,
            custId: item.custId,
            accountNo: item.accountNo,
            custType: item.custType,
            prevUserName: item.userName,
          }))
        const custNameList = this.multipleSelection.map(item => item.custName).join(',')
        const custIdList = this.multipleSelection.map(item => item.custId).join(',')
        const accountNoList = this.multipleSelection.map(item => item.accountNo).join(',')
        this.clientForm = this.batchData
        const allSome = this.multipleSelection.every(item => item.userName === this.multipleSelection[0].userName)
        if (!allSome && this.batchType === 'move') {
          this.$message.warning('批量移交需选择相同的客户经理')
          this.$refs.multipleTable.clearSelection()
          this.multipleSelection = []
          return
        }
        this.prevUserName = this.multipleSelection[0].userName
        this.dialogVisible = true
        this.getDeptTreeSelect()
      },
      transferAll() {
        this.isFullTransfer = true
        this.prevUserName = this.tableData[0].userName
        this.dialogVisible = true
        this.getDeptTreeSelect()
      },
      handleCancel() {
        this.dialogVisible = false
        this.userDeptList = null
        this.batchVisible = false
        this.isFullTransfer = false
      },
      okHandler() {
        if (this.authUser === this.prevUserName) {
          this.$message.warning('移交人和被移交人一致，请重新选择')
          return
        }
        const API = this.batchType === 'move' ? gridCmpmTransferCreate : gridCmpmTransferAdjust
        API({
          custList:this.batchVisible ? this.clientForm : [this.clientForm],
          gridType: this.gridType,
          nextUserName: this.authUser,
          userName: this.authUser,
          prevUserName: this.prevUserName,
          isFullTransfer: this.isFullTransfer
        }).then(res => {
          this.$message.success(res.msg)
          this.dialogVisible = false
          this.userDeptList = null
          this.batchVisible = false
          this.$refs.multipleTable.clearSelection()
          this.multipleSelection = []
          this.isFullTransfer = false
          this.getList()
        })
      },
      handlePushCust(row) {
        let path = ''
        if (row.custType === '0') {
          // 零售
          path = '/360charts/indexcharts'
        } else if (row.custType === '1') {
          // 商户
          path = '/360charts/commercial'
        } else if (row.custType === '2') {
          // 企业
          path = '/360charts/firm'
        }
        if (!path) return
        this.$router.push({
          path,
          query: {
            custId: row.custId,
            selectedTab: '0',
            backUrl: '/gridSearch/performanceGridSearch'
          }
        })
      },
      customClaim() {
        this.claimVisible = true
        this.loadingClaim = true
        gridCmpmTransferClaimList({
          ...this.claimForm,
          custKey: this.claimForm.custName,
          gridType: this.gridType }).then(res => {
          this.claimData = res.rows
          this.totalClaim = res.total
          this.loadingClaim = false
        })
      },
      handleSelectionChangeClaim(val) {
        this.multipleSelectionClaim = val
      },
      handleCancelClaim() {
        this.claimVisible = false
        this.claimForm = {
          custName: '',
          pageNum: 1,
          pageSize: 10
        }
        this.totalClaim = 0
      },
      okHandlerClaim() {
        // const allSome = this.multipleSelectionClaim.every(item => item.userName === this.multipleSelectionClaim[0].userName)
        // if (!allSome) {
        //   this.$message.warning('批量移交需选择相同的客户经理')
        //   this.$refs.multipleTable.clearSelection()
        //   this.multipleSelectionClaim = []
        //   return
        // }
        const clientForm = this.multipleSelectionClaim.map(item => ({
          custName: item.custName,
          custId: item.custId,
          accountNo: item.accountNo,
          prevUserName: item.userName,
          custType: item.custType,
        }))
        gridCmpmTransferCreateClaim({
          custList: clientForm,
          gridType: this.gridType,
          userName: this.$store.state.user.userName
        }).then(res => {
          this.claimVisible = false
          this.claimForm = {
            custName: '',
            pageNum: 1,
            pageSize: 10
          }
          this.$message.success('提交成功')
          this.totalClaim = 0
          this.getList()
        })
      },
      isRowSelectable(row, index) {
        return row.claimFlag === true
      }
  }
}
</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: 80%;
  gap: 10px;
  ::v-deep .el-form-item__label {
    display: inline-block;
    white-space: nowrap;
  }
  ::v-deep .el-form-item__content {
    margin-left: 0 !important;
    width: 100%
  }
}
.table {
  width: 100%;
  margin: 20px;
  text-align: center;
  vertical-align: middle;
}
a {
  margin: 5px;
}
.dialog-input {
  width: 80%
}
.user-info {
  margin-bottom: 5px;
  margin-left: 26px;
  display: flex;
  align-items: center;

  ::v-deep .vue-treeselect__control {
    width: 320px !important;
    height: 32px;
  }

  span {
    width: 70px !important;
    margin-right: 10px;
    font-size: 14px;
    color: #606266;

    &::before {
      content: "*";
      left: -3px;
      color: #ff4d42;
      position: relative;
      top: 2px;
    }
  }

  .input-box {
    width: 320px !important;
  }
}

.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;
        }
      }

      .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;
        }

        ::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;
          }
        }
      }
    }
.my-table::before {
  height: 0;
}
</style>