<script setup>
import { ref,reactive,watch } from "vue";
import {ElMessage} from "element-plus"

import { contractInterface } from "@/api/api.js";


const props = defineProps({
  allocationVisible: {
    default: false,
    type: Boolean,
  },
  allocationForm: {
    type: Object,
    default: {},
  }
})
const emits=defineEmits(['update:allocationForm','update:allocationVisible','emitGetTableData'])

const listObj=reactive({
  listArr:[]
})
const allNum=ref(0)
const TotalPointsContent=ref("")

// 取消弹框
const handleClose=()=>{
  listObj.listArr = [];
  emits("update:allocationForm", {});
  emits("update:allocationVisible", false);
}
// 提交弹框
const addAllocationHandler=async()=>{
  listObj.listArr.forEach((item,index) => {
    item.Money = Number(item.Money) || 0;
    item.Proportion = Number(item.Proportion) || 0;
    item.List.forEach((_) => {
      _.Money = Number(_.Money) || 0;
      _.Proportion = Number(_.Proportion) || 0;
    });
  });
  let arrList = listObj.listArr;
  const res = await contractInterface.getAllocationDetailUpdate({
    CompanyContractId: props.allocationForm.CompanyContractId,
    List: arrList,
  });
  if (res.Ret === 200) {
    ElMessage.success("操作成功");
    emits('emitGetTableData')
    handleClose();
  }
}
// 处理百分比
const roundedResult=(row)=>{
  let num = row.Proportion >= 0 ? (row.Proportion * 100) / 100 / 100 : row.Proportion / 100;
  row.Money = Number(row.Proportion ? (allNum.value * num).toFixed(2) : '') || 0
  return row.Money;
}
// 输入框的限制
const restrictInput=(item)=>{
  if (item.Proportion > 100) return (item.Proportion = 100);
  if (item.Proportion < -100) return (item.Proportion = -100);
}

// 数量的总和
const allPerCentHandler=(item)=>{
  let num = 0;
  item && item.List.forEach((key) => (num = num + +key.Proportion));
  return num.toFixed(2);
}
// 获取数据
const getList=async()=>{
  const res = await contractInterface.getAllocationDetail({
    CompanyContractId: props.allocationForm.CompanyContractId,
  });
  if (res.Ret === 200) {
    allNum.value = res.Data.Money;
    listObj.listArr = res.Data.List;
    TotalPointsContent.value = res.Data.TotalPointsContent;
  }
}
// 平均分配
const averageaAllocation=()=>{
  let isName = [];
  listObj.listArr.forEach((item) => {
    if (!item.ChartPermissionName.includes("研选")) {
      isName.push(true);
    }
  });
  let num = 100 / isName.length;
  listObj.listArr.forEach((item) => {
    if (item.ChartPermissionName != "研选订阅" && item.ChartPermissionName != "研选扣点包") {
      item.Proportion = num;
    }
    let childrenNum = num / item.List.length;
    item.List.forEach((key) => {
      if (key.RealName != "研选订阅" && key.RealName != "研选扣点包") {
        key.Proportion = Math.round(childrenNum*100)/100;
      }
    });
  });
}

watch(()=>props.allocationVisible,(newVal)=>{
  newVal && getList();
},
{immediate:true})

</script>

<template>
  <div class="container-allocation-number-rai">
    <el-dialog title="派点" width="1300px" v-model="props.allocationVisible" v-dialogDrag :close-on-click-modal="false" :modal-append-to-body="false" center @close="handleClose">
      <div class="top-content">
        <div>
          <h5>总点数：{{ TotalPointsContent }}</h5>
          <el-button style="margin-top: 20px" type="primary" @click="averageaAllocation">平均分配</el-button>
        </div>

        <p>
          1）单行业套餐只能在对应行业内部分配研究员贡献百分比<br />
          2）多行业套餐先在行业间分配百分比（最低不低于平均值的一半），再分配到个人<br />
          3）允许总额20%以内的负分<br />
          4）转正后一个季度内可以提交和修改
          <br />
        </p>
      </div>
      <div class="content-box">
        <div v-for="item in listObj.listArr" :key="item.ChartPermissionName">
          <div class="industry-ul">
            <span :class="['industry-name', item.ChartPermissionId == '31' && 'name-yanxuan', item.ChartPermissionId == '52' && 'points-name']">{{ item.ChartPermissionName }}</span>
            <template v-if="item.ChartPermissionId != '31' && item.ChartPermissionId != '52'">
              <el-input :min="-100" :max="100" type="number" v-model="item.Proportion" @input="restrictInput(item)" style="width: 76px; margin: 0 5px 0 8px">
                <template #suffix>
                  <div class="per_cent_">%</div>
                </template>
              </el-input>
              <p style="width: 38px">{{ roundedResult(item) }}</p>
            </template>
            <p style="width: 38px; height: 32px; line-height: 32px; text-align: center" v-else>{{ item.Money }}</p>
          </div>
          <div v-for="study in item.List" :key="study.RealName" class="industry-ul">
            <span :class="['study-name', item.ChartPermissionId == '31' && 'name-yanxuan', item.ChartPermissionId == '52' && 'points-name']">{{ study.RealName }}</span>
            <template v-if="!study.RealName.includes('研选')">
              <el-input :min="-100" :max="100" type="number" v-model="study.Proportion" style="width: 76px; margin: 0 5px 0 8px">
                <template #suffix>
                  <div class="per_cent_">%</div>
                </template>
              </el-input>
              <p style="width: 38px">{{ roundedResult(study) }}</p>
            </template>
            <p style="width: 38px; height: 32px; line-height: 32px; text-align: center" v-else>{{ study.Money }}</p>
          </div>
          <div class="all-item" v-if="item.ChartPermissionId != '31' && item.ChartPermissionId != '52'">
            <span> {{ allPerCentHandler(item) == 0 ? "" : `总占比：` }}</span>
            <span> {{ allPerCentHandler(item) == 0 ? "" : `${allPerCentHandler(item)}` }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose" size="large">取 消</el-button>
          <el-button type="primary" @click="addAllocationHandler" size="large">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss">
.container-allocation-number-rai {
  overflow: hidden;
  .top-content {
    display: flex;
    justify-content: space-between;
  }
  .content-box {
    width: 100%;
    overflow: hidden;
    overflow-x: auto;
    display: flex;
    .industry-ul {
      display: flex;
      align-items: center;
      margin: 30px 0;
      width: 180px;
      color: #333;
      margin-right: 25px;
      .per_cent_ {
        line-height: 32px;
      }
      .industry-name {
        width: 58px;
        flex-shrink: 0;
        font-weight: 800;
        font-size: 16px;
        line-height: 22px;
      }
      .study-name {
        width: 58px;
        flex-shrink: 0;
        font-size: 14px;
        line-height: 22px;
      }
      p {
        color: #9999;
        font-size: 14px;
      }
    }
  }
  .all-item {
    display: flex;
    padding-right: 15px;
    align-items: center;
    // justify-content: center;
    color: #999;
    font-size: 14px;
    span {
      display: inline-block;
      width: 80px;
    }
  }
  .name-yanxuan {
    width: 70px !important;
  }
  .points-name {
    width: 80px !important;
  }
  /* 取消[type='number']的input的上下箭头 */
  input::-webkit-inner-spin-button {
    -webkit-appearance: none !important;
  }

  input::-webkit-outer-spin-button {
    -webkit-appearance: none !important;
  }

  input[type="number"] {
    -moz-appearance: textfield;
  }
}
</style>
