<template>
  <vxe-modal
    resize
    v-model="showModal"
    title="案件分派"
    @hide="onHide"
    height="582"
    width="1003"
    show-footer
    esc-closable
  >
    <div class="allocation-wrap">
      <div class="Content">
        <div class="top">
          <div class="number-box">
            <div class="number-left">
              <div class="icon-wrapper">
                <img src="@/assets/images/userlist.svg" />
              </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">
                <img src="@/assets/images/caselist.svg" />
              </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">
                <img src="@/assets/images/money.svg" />
              </div>
            </div>
            <div class="number-right">
              <p>待分派金额</p>
              <p>￥{{ statisis.unAmount }}</p>
            </div>
          </div>
        </div>
        <div style="margin-top: 10px; margin-bottom: 10px">
          <el-radio-group v-model="radio" @change="changeRadio">
            <el-radio :value="0" v-permission="'allcation_for_tenant'">分派到调解中心</el-radio>
            <el-radio :value="1">分派到CPE</el-radio>
          </el-radio-group>
        </div>
        <template v-if="radio === 0 || (radio === 1 && !step)">
          <div class="mainContent">
            <div class="flex items-center my-3">
              <span class="mr-2" v-if="radio === 0"> 调解中心 </span>
              <el-select
                v-if="radio === 0"
                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 v-else class="flex">
                <div class="tree-cpe">
                  <p class="bb">选择CPE</p>
                  <div class="flex">
                    <div class="tree-wrapper" style="border-right: none">
                      <el-tree
                        :data="data"
                        highlight-current
                        :props="defaultProps"
                        @node-click="handleNodeClick"
                      />
                    </div>
                    <div class="tree-wrapper">
                      <div class="flex items-center h-10 border-b">
                        <div class="px-3 border-r mr-auto h-full flex items-center justify-center">
                          <el-checkbox v-model="checked1" label="" @change="changeAll" />
                        </div>
                        <div class="flex-1 text-center">CPE</div></div
                      >
                      <el-tree
                        :data="alltabledata"
                        highlight-current
                        ref="allTreeRef"
                        node-key="id"
                        show-checkbox
                        :props="{
                          children: 'children',
                          label: 'username',
                        }"
                        @check-change="checkChange"
                      />
                    </div>
                  </div>
                </div>
                <div class="ml-3">
                  <p class="bb">已选CPE</p>
                  <div class="flex items-center h-10 border border-b-0">
                    <div class="w-10 border-r mr-auto h-full flex items-center justify-center">
                      序号
                    </div>
                    <div class="flex-1 text-center">CPE</div>
                  </div>
                  <div class="tree-wrapper" style="height: calc(100% - 3.8rem)">
                    <div v-for="(item, index) in tabledata" :key="index" class="flex">
                      <div class="w-10 mr-auto h-full flex items-center justify-center">
                        {{ index + 1 }}
                      </div>
                      <div class="flex-1 text-left pl-3">{{ item.cpe.username }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- <el-transfer
              v-model="value1"
              :data="data1"
              :titles="['CPE', '已选CPE']"
              ref="mytransfer"
              @left-check-change="leftChange"
            /> -->
          </div>
        </template>

        <template v-if="radio === 1 && currentTenant && step">
          <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"
              /> -->
              <vxe-grid
                v-bind="{...config, ...{data: tabledata}}"
                :show-footer="true"
                :footer-method="footerMethod"
                ref="caseLRef"
              ></vxe-grid>
            </div>
          </div>
        </template>
      </div>
    </div>
    <template #footer>
      <el-button @click="backform" v-if="step" style="float: left">上一步</el-button>
      <el-button
        type="primary"
        @click="saveFrom"
        :disabled="!currentTenant"
        v-if="radio === 1 && step"
        >保存</el-button
      >
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-if="radio === 0 || step"
        :disabled="!currentTenant || (radio === 1 && !SaveBol)"
        >确认提交</el-button
      >
      <el-button
        type="primary"
        @click="submitForm"
        v-if="!step && radio === 1"
        :disabled="!currentTenant || tabledata.length === 0"
        >下一步</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 Decimal from 'decimal.js';
  import { useUserStore } from '@/stores/modules/user';
  import {
    getLoanDistribute,
    distributeLoan,
    confirm,
    distributeCpe,
    changeDistributeCpe,
    getTenantUsers
  } from '@/api/allcation';
  import { getTenantPage } from '@/api/tenant';
  import { computed } from 'vue';
  import { reactive, ref, nextTick } from 'vue';
  import { useAuthStore } from '@/stores/modules/auth';
  const emits = defineEmits(['success']);
  const { authButtonListGet } = useAuthStore(); // 获取用户权限列表
  const userStore = useUserStore();
  const data = ref([]);
  const mytransfer = ref();
  const tabledata = ref([]);
  const alltabledata = ref([]);
  const lonsArr = ref([]);
  const SaveBol = ref(false);
  const showModal = ref(false);
  const currentTenant = ref();
  const allTreeRef = ref();
  const statisis = ref({});
  const currentAllBtn = ref();
  const checked1 = ref(false);
  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 = () => {
    let name = ''
    if (userStore.userInfo?.tenants && userStore.userInfo?.tenants.length > 0) {
      if (userStore.userInfo?.tenants.length < 2) {
        name = userStore.userInfo?.tenants[0].name
      } else {
        name = userStore.tenant.name
      }
    }
    getTenantPage({
      current: 1,
      size: 999999999,
      status: 'enable',
      name: name || null
    }).then((res) => {
      if (res.success) {
        data.value = res.result.content;
      }
    });
  };
  const chooseIdea = (type) => {
    editRowIndex.value = -1;
    currentAllBtn.value = type;
    const param = {
      type: currentAllBtn.value,
      tenantId: currentTenant.value,
    };
    if (tabledata.value && tabledata.value.length) {
      param['cpeIds'] = tabledata.value.map((v) => v.cpe.id);
    }
    if (lonsArr.value && lonsArr.value.length) {
      param['loanIds'] = lonsArr.value.map((v) => v.id);
    } else {
      param['borrowerName'] = pageParams.value.borrowerName;
      param['batchCode'] = pageParams.value.batchCode;
      param['borrowerIdCard'] = pageParams.value.idCard;
      param['borrowerPhone'] = pageParams.value.borrowerPhone;
      param['commissionAmount'] = pageParams.value.commissionAmount;
      param['remainingAmount'] = pageParams.value.remainingAmount;
    }
    distributeCpe(param).then((res) => {
      if (res.success) {
        tabledata.value = res.result;
      }
    });
  };
  const changeRadio = () => {
    let param = {};
    if (lonsArr.value && lonsArr.value.length) {
      param['loanIds'] = lonsArr.value.map((v) => v.id);
    } else {
      param = { ...pageParams.value };
    }
    radio.value === 0 && getStatisis(param);
    step.value = 0;
    currentTenant.value = null;
  };
  const openModal = (param, select) => {
    lonsArr.value = select;
    showModal.value = true;
    pageParams.value = param;
    currentAllBtn.value = null;
    console.log('sadasda')
    
    getTree();
    step.value = 0;
    if (!authButtonListGet.includes('allcation_for_tenant')) {
      radio.value = 1;
    } else {
      radio.value = 0;
    }
    
    let p = {}
    if (lonsArr.value && lonsArr.value.length) {
      p['loanIds'] = lonsArr.value.map((v) => v.id);
    } else {
      p = param;
    }
    radio.value === 0 && getStatisis(p);
    SaveBol.value = false;
    currentTenant.value = null;
    editRowIndex.value = -1;
    if (userStore.userInfo?.tenants && userStore.userInfo?.tenants.length > 0) {
      if (userStore.userInfo?.tenants.length < 2) {
        handleNodeClick(userStore.userInfo?.tenants[0])
        currentTenant.value = userStore.userInfo?.tenants[0].id;
      } else {
        handleNodeClick(userStore.tenant)
        currentTenant.value = userStore.tenant.id;
      }
    }
    tabledata.value = [];
    alltabledata.value = [];
    checked1.value = false;
  };
  const changeAll = () => {
    if (checked1.value) {
      allTreeRef.value.setCheckedNodes(alltabledata.value);
    } else {
      allTreeRef.value.setCheckedKeys([]);
    }
  };
  const backform = () => {
    step.value = 0;
  };
  const saveFrom = () => {
    if (currentAllBtn.value === 'CASE') {
      const sum = tabledata.value.reduce((pre, cur) => Decimal(pre).add(Decimal(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) => Decimal(pre).add(Decimal(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 (step.value) {
        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 {
        step.value = 1;
      }
    } else if (radio.value === 0) {
      // chooseIdea('BORROWER');
      const param = {};
      if (lonsArr.value && lonsArr.value.length) {
        param['loanIds'] = lonsArr.value.map((v) => v.id);
      } else {
        param['borrowerName'] = pageParams.value.borrowerName;
        param['batchCode'] = pageParams.value.batchCode;
        param['borrowerIdCard'] = pageParams.value.idCard;
        param['borrowerPhone'] = pageParams.value.borrowerPhone;
        param['commissionAmount'] = pageParams.value.commissionAmount;
        param['remainingAmount'] = pageParams.value.remainingAmount;
        param['tenantId'] = null;
      }
      distributeLoan(currentTenant.value, param).then((res) => {
        if (res.success) {
          ElMessage.success({
            message: '分派成功',
            plain: true,
          });
          showModal.value = false;
          emits('success');
        }
      });
    }
  };
  const handleNodeClick = (data1) => {
    if (typeof data1 === 'object') {
      currentTenant.value = data1.id;
      let param = {};
      if (lonsArr.value && lonsArr.value.length) {
        param['loanIds'] = lonsArr.value.map((v) => v.id);
      } else {
        param = { ...pageParams.value };
      }
      getStatisis(param, currentTenant.value);
      getTenantUsers({tenantId: data1.id, roleCode: 'CPE'}).then(res => {
        if (res.success && res.result) {
          alltabledata.value = res.result
        } else {
          alltabledata.value = []
        }
        tabledata.value = alltabledata.value.map((v) => ({
          cpe: v,
          borrowerNum: null,
          caseNum: null,
          amount: null,
        }));
        nextTick(() => {
          setTimeout(() => {
            allTreeRef.value.setCheckedNodes(alltabledata.value);
          });
        });
      }).catch(e => {
        alltabledata.value = []
        tabledata.value = []
        nextTick(() => {
          setTimeout(() => {
            allTreeRef.value.setCheckedNodes(alltabledata.value);
          });
        });
      })
      checked1.value = true;
    }
  };

  const resetAllocation = () => {
    chooseIdea(currentAllBtn.value);
  };
  const checkChange = (dara, ddd, aaa) => {
    nextTick(() => {
      const arr = allTreeRef.value.getCheckedNodes();
      tabledata.value = arr.map((v) => ({
        cpe: v,
        borrowerNum: null,
        caseNum: null,
        amount: null,
      }));
    });
  };
  const changeNum = (type, row, index) => {
    const sum = tabledata.value.reduce((pre, cur) => Decimal(pre).add(Decimal(cur[type])), 0);
    const sta_num = type === 'borrowerNum' ? statisis.value.unCustomerNum : statisis.value.unCaseNum
    const differ = Decimal(sum).sub(Decimal(sta_num))
    const msg = type === 'borrowerNum' ? '总数超过待分派案人数' : '总数超过待分派案件数'
    if (Number(sum) > Number(sta_num)) {
      row[type] = Decimal(row[type]).sub(Decimal(differ))
      return ElMessage.warning({
        message: msg,
        plain: true,
      });
    }
    
  };
  const leftChange = (value, direction) => {
    console.log(value, direction); //这个就是它包含的所有的属性以及事件，如果需要别的操作直接执行，也可以查询到
  };
  // 进行合计
  const sumNum = (costForm, type) => {
    let total = 0;
    for (let i = 0; i < costForm.length; i++) {
      total = Decimal(total).add(Decimal(costForm[i][type]))
    }
    return total;
  };
  const options = [
    {
      label: '以案人数均分',
      value: 'BORROWER',
    },
    {
      label: '以案件数均分',
      value: 'CASE',
    },
    {
      label: '以委案金额均分',
      value: 'AMOUNT',
    },
  ];
  const footerMethod = ({ columns, data }) => {
    const footerData = [
    columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return '合计';
        }
        if (
          ['borrowerNum', 'caseNum', 'amount'].includes(
            column.field
          )
        ) {
          return sumNum(data, column.field);
        }
        return null;
      }),
    ]
    return footerData
  }
  const config = computed(() => {
    // 去除分页控件，toolbar控件
    return {
      height: 'auto',
      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('borrowerNum', row, rowIndex)}
                    />
                  </>
                );
              } else {
                return <>{row.borrowerNum}</>;
              }
            },
          },
        },
        {
          field: 'caseNum',
          title: '分派案件数',
          slots: {
            default: ({ row, rowIndex }) => {
              if (currentAllBtn.value === 'CASE') {
                return (
                  <>
                    <ElInputNumber
                      v-model={row.caseNum}
                      onChange={() => changeNum('caseNum', row, 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 rgba(0, 0, 0, 0.1);
        height: 50px;
        display: flex;
        margin-right: 10px;
        margin-top: 10px;
      }
      .icon-wrapper {
        width: 40px;
        height: 40px;
        text-align: center;
        line-height: 40px;
        color: #bbc3ca;
        margin-right: 10px;
        font-size: 37px;
      }
    }
    .number-right {
      p:nth-child(1) {
        color: #aaa;
        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;
    .bb {
      padding-left: 14px;
      border: 1px solid #ebeef5;
      border-bottom: none;
    }
    .tree-wrapper {
      border: 1px solid #ebeef5;
      width: 290px;
      height: 318px;
    }
    .bc {
      display: flex;
    }
  }
</style>
