<template>
  <vxe-modal
    v-model="showModal"
    title="案件分配"
    @hide="onHide"
    height="582"
    width="1003"
    show-footer
    esc-closable
  >
    <div class="allocation-wrap">
      <div class="Content">
        <div style="margin-top: 10px; margin-bottom: 10px">
          <el-radio-group v-model="radio" @change="changeRadio">
            <el-radio :value="0">分配到调解中心</el-radio>
            <el-radio :value="1">分配到CPE</el-radio>
          </el-radio-group>
        </div>
        <template v-if="radio === 0 || radio === 1">
          <div class="mainContent">
            <div class="flex items-center my-3">
              <span class="mr-2">
                {{ radio === 0 ? '调解中心' : '分配到调解中心的cpe' }}
              </span>
              <el-select
                v-model="currentTenant"
                placeholder="请选择调解中心"
                style="width: 210px"
                @change="handleNodeClick"
              >
                <el-option
                  :label="item.name"
                  :value="item.id"
                  v-for="(item, index) in data"
                  :key="index"
                />
              </el-select>
            </div>

            <!-- <el-transfer
              v-model="value1"
              :data="data1"
              :titles="['CPE', '已选CPE']"
              ref="mytransfer"
              @left-check-change="leftChange"
            /> -->
          </div>
        </template>
        <div class="top" v-if="radio === 0 || (radio === 1 && currentTenant)">
          <div class="number-box">
            <div class="number-left">
              <div class="icon-wrapper">
                <el-icon><UserFilled size="850" /></el-icon>
              </div>
            </div>
            <div class="number-right">
              <p>待分配客户数量</p>
              <p>{{ statisis.unCustomerNum }}</p>
            </div>
          </div>
          <div class="number-box">
            <div class="number-left">
              <div class="icon-wrapper">
                <el-icon><List /></el-icon>
              </div>
            </div>
            <div class="number-right">
              <p>待分配案件数量</p>
              <p>{{ statisis.unCaseNum }}</p>
            </div>
          </div>
          <div class="number-box">
            <div class="number-left">
              <div class="icon-wrapper">
                <el-icon><UserFilled size="850" /></el-icon>
              </div>
            </div>
            <div class="number-right">
              <p>待分配金额</p>
              <p>{{ statisis.unAmount }}</p>
            </div>
          </div>
        </div>
        <template v-if="radio === 1 && currentTenant">
          <p class="my-2">分配方案</p>
          <div class="idea-box">
            <div class="left-idea">
              <div class="idea-btn">
                <el-button
                  type="primary"
                  :plain="currentAllBtn === item.value ? false : true"
                  v-for="(item, index) in options"
                  :key="index"
                  @click="chooseIdea(item.value)"
                  >{{ item.label }}</el-button
                >
              </div>
              <div class="reset-btn">
                <el-button type="primary" link :icon="RefreshRight" @click="resetAllocation"
                  >重新分配</el-button
                >
              </div>
            </div>
            <div class="right-idea">
              <ProTable
                :config="config"
                :data="tabledata"
                ref="caseLRef"
                :showPagination="false"
                :showToolBar="false"
              />
            </div>
          </div>
        </template>
      </div>
    </div>
    <template #footer>
      <el-button type="primary" @click="saveFrom" :disabled="!currentTenant" v-if="radio === 1"
        >保存</el-button
      >
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        :disabled="!currentTenant || (radio === 1 && !SaveBol)"
        >确认提交</el-button
      >
    </template>
  </vxe-modal>
</template>

<script setup lang="jsx" name="allocationModal">
  import { UserFilled } from '@element-plus/icons-vue';
  import { RefreshRight } from '@element-plus/icons-vue';
  import { ElInputNumber, ElMessage } from 'element-plus';
  import {
    getLoanDistribute,
    distributeLoan,
    confirm,
    distributeCpe,
    changeDistributeCpe,
  } from '@/api/allcation';
  import { getTenantPage } from '@/api/tenant';
  import { computed } from 'vue';
  import { reactive, ref } from 'vue';
  const emits = defineEmits(['success']);

  const data = ref([]);
  const mytransfer = ref();
  const tabledata = ref([]);
  const SaveBol = ref(false);
  const showModal = ref(false);
  const currentTenant = ref();
  const statisis = ref({});
  const currentAllBtn = ref();
  const editRowIndex = ref(-1);
  const pageParams = ref({});
  const radio = ref(null);
  const step = ref(0);
  const searchParam = ref();
  const onHide = () => {};
  const getStatisis = (params, id) => {
    const p = JSON.parse(JSON.stringify(params));
    if (id) {
      p['tenantId'] = id;
    }
    delete p['current'];
    delete p['size'];
    getLoanDistribute(p).then((res) => {
      if (res.success) {
        statisis.value = res.result;
      }
    });
  };
  const getTree = () => {
    getTenantPage({
      current: 1,
      size: 999999999,
    }).then((res) => {
      if (res.success) {
        data.value = res.result.content;
      }
    });
  };
  const chooseIdea = (type) => {
    editRowIndex.value = -1;
    currentAllBtn.value = type;
    distributeCpe({
      type: currentAllBtn.value,
      borrowerName: pageParams.value.borrowerName,
      borrowerIdCard: pageParams.value.idCard,
      borrowerPhone: pageParams.value.borrowerPhone,
      commissionAmount: pageParams.value.commissionAmount,
      remainingAmount: pageParams.value.remainingAmount,
      tenantId: currentTenant.value,
    }).then((res) => {
      if (res.success) {
        tabledata.value = res.result;
      }
    });
  };
  const changeRadio = () => {
    radio.value === 0 && getStatisis(pageParams.value);
    currentTenant.value = null;
  };
  const openModal = (param) => {
    showModal.value = true;
    pageParams.value = param;
    currentAllBtn.value = null;
    getTree();
    step.value = 0;
    SaveBol.value = false;
    currentTenant.value = null;
    editRowIndex.value = -1;
  };
  const backform = () => {
    step.value = 0;
  };
  const saveFrom = () => {
    if (currentAllBtn.value === 'CASE') {
      const sum = tabledata.value.reduce((pre, cur) => pre + cur.caseNum, 0);
      if (Number(sum) !== Number(statisis.value.unCaseNum))
        return ElMessage.warning({
          message: '总数与待分配案件数不一致',
          plain: true,
        });
    } else if (currentAllBtn.value === 'BORROWER') {
      const sum = tabledata.value.reduce((pre, cur) => pre + cur.borrowerNum, 0);
      if (Number(sum) !== Number(statisis.value.unCustomerNum))
        return ElMessage.warning({
          message: '总数与待分配案人数不一致',
          plain: true,
        });
    }
    changeDistributeCpe({
      records: tabledata.value,
      distributeType: currentAllBtn.value,
    }).then((res) => {
      if (res.success) {
        ElMessage.success({
          message: '保存成功',
          plain: true,
        });
        SaveBol.value = true;
      }
    });
  };
  const submitForm = () => {
    if (radio.value === 1) {
      if (!SaveBol.value)
        ElMessage.warning({
          message: '要先保存',
          plain: true,
        });
      confirm({
        records: tabledata.value,
        distributeType: currentAllBtn.value,
      }).then((res) => {
        if (res.success) {
          ElMessage.success({
            message: '分配成功',
            plain: true,
          });
          showModal.value = false;
          emits('success');
        }
      });
    } else if (radio.value === 0) {
      // chooseIdea('BORROWER');
      distributeLoan(currentTenant.value, {
        borrowerName: pageParams.value.borrowerName,
        borrowerIdCard: pageParams.value.idCard,
        borrowerPhone: pageParams.value.borrowerPhone,
        commissionAmount: pageParams.value.commissionAmount,
        remainingAmount: pageParams.value.remainingAmount,
        tenantId: null,
      }).then((res) => {
        if (res.success) {
          ElMessage.success({
            message: '分配成功',
            plain: true,
          });
          showModal.value = false;
          emits('success');
        }
      });
    }
  };
  const handleNodeClick = () => {
    const item = data.value.find((v) => v.id === currentTenant.value);
    if (radio.value === 0) {
    } else {
      getStatisis(pageParams.value, currentTenant.value);
      tabledata.value = item.users.map((v) => ({
        cpe: v,
        borrowerNum: null,
        caseNum: null,
        amount: null,
      }));
    }
  };

  const resetAllocation = () => {
    chooseIdea(currentAllBtn.value);
  };
  const changeNum = (type, row, index) => {
    // editRowIndex.value = index;
    console.log('changeNum', type, row, index);
  };
  const leftChange = (value, direction) => {
    console.log(value, direction); //这个就是它包含的所有的属性以及事件，如果需要别的操作直接执行，也可以查询到
  };
  const options = [
    {
      label: '以案人数均分',
      value: 'BORROWER',
    },
    {
      label: '以案件数均分',
      value: 'CASE',
    },
    {
      label: '以委案金额均分',
      value: 'AMOUNT',
    },
  ];
  const config = computed(() => {
    // 去除分页控件，toolbar控件
    return {
      toolbarConfig: { enabled: false },
      columns: [
        { type: 'seq', width: 50, title: '序号' },
        {
          field: 'cpe.username',
          title: 'CPE',
        },
        {
          field: 'borrowerNum',
          title: '分配案人数',
          slots: {
            default: ({ row, rowIndex }) => {
              if (currentAllBtn.value === 'BORROWER') {
                return (
                  <>
                    <ElInputNumber
                      v-model={row.borrowerNum}
                      onChange={() => changeNum(1, row, rowIndex)}
                      disabled={editRowIndex.value > -1 && editRowIndex.value !== rowIndex}
                    />
                  </>
                );
              } else {
                return <>{row.borrowerNum}</>;
              }
            },
          },
        },
        {
          field: 'caseNum',
          title: '分配案件数',
          slots: {
            default: ({ row, rowIndex }) => {
              if (currentAllBtn.value === 'CASE') {
                return (
                  <>
                    <ElInputNumber
                      v-model={row.caseNum}
                      onChange={() => changeNum(2, row, rowIndex)}
                      disabled={editRowIndex.value > -1 && editRowIndex.value !== rowIndex}
                    />
                  </>
                );
              } else {
                return <>{row.caseNum}</>;
              }
            },
          },
        },
        {
          field: 'amount',
          title: '分配委案金额',
          // slots: {
          //   default: ({ row, rowIndex }) => {
          //     // if (currentAllBtn.value === 3) {
          //     //   return (
          //     //     <>
          //     //       <ElInputNumber
          //     //         v-model={row.num}
          //     //         onChange={() => changeNum(3, row, rowIndex)}
          //     //         disabled={editRowIndex.value > -1 && editRowIndex.value !== rowIndex}
          //     //       />
          //     //     </>
          //     //   );
          //     // } else {
          //       return <>{row.num}</>;
          //     // }
          //   },
          // },
        },
      ],
    };
  });

  const generateData = () => {
    const data = [];
    for (let i = 1; i <= 15; i++) {
      data.push({
        key: i,
        label: `Option ${i}`,
      });
    }
    return data;
  };

  const data1 = ref(generateData());
  const value1 = ref([]);
  const defaultProps = {
    children: 'children',
    label: 'name',
  };
  defineExpose({
    openModal,
  });
</script>
<style lang="scss" scoped>
  .allocation-wrap {
    height: 100%;
    .top {
      display: flex;
      .number-box {
        font-size: 15px;
        width: 235px;
        padding: 5px 0 5px 15px;
        border: 1px solid #f1f1f1;
        height: 50px;
        display: flex;
        margin-right: 10px;
        margin-top: 10px;
      }
      .icon-wrapper {
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        color: #bbc3ca;
        border: 2px solid #bbc3ca;
        border-radius: 100%;
        margin-right: 10px;
        font-size: 37px;
      }
    }
    .number-right {
      p:nth-child(1) {
        color: #cacaca;
        font-size: 13px;
      }
    }
  }
  .Content {
    height: calc(100% - 50px);
    .idea-box {
      height: calc(100% - 24px);
      display: flex;
    }
    .left-idea {
      width: 250px;
      border: 1px solid #ebeef5;
      display: flex;
      flex-direction: column;
    }
    .right-idea {
      width: calc(100% - 250px);
      :deep(.card) {
        padding: 0;
      }
    }
    .idea-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
      border-bottom: 1px solid #ebeef5;
      padding-bottom: 10px;
      .el-button {
        width: 150px;
        margin-left: 0 !important;
        margin-top: 15px;
      }
    }
    .reset-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .mainContent {
    display: flex;
    :deep(.el-transfer-panel .el-transfer-panel__header) {
      border-top-left-radius: 0;
      background: #fff;
      border-top-right-radius: 0;
    }
    :deep(.el-transfer__buttons) {
      padding: 0 5px;
    }
    :deep(.el-transfer-panel) {
      width: 250px;
    }
  }
</style>
