<template>
  <div class="dispatch-salary-advance">
    <p class="tips">
      <div class="tipscontent">
        <el-icon size="14px"><WarningFilled/></el-icon>
        温馨提醒：预支工资最大次数、最大额度不超过1万，阶梯比例最后一个区间的最大次数或结束额度请输入0，0代表9999。</div>
    </p>

    <el-form
        :inline="true"
        label-position="right"
        label-width="170px"
        :model="formLabelAlign"
        style="max-width: 90%"
        ref="ruleFormRef"
        :rules="rules"
        class="ruleFormRef"
    >

      <div class="box">
        <div class="boxTitle">平台与客户分成比例</div>
          <el-form-item label="比例" style="width: 1080px;" prop="ratio">
            <el-table :data="formLabelAlign.ratio">
              <el-table-column label="序号" align="center" prop="sn" />
              <el-table-column label="次数范围" align="center" prop="" >
                <template #default="{row}">
                  {{row.minAmount + '-' + (row.maxAmount==0?'无限制':row.maxAmount)}}
                </template>
              </el-table-column>
              <el-table-column label="金额范围" align="center" prop="" >
                <template #default="{row}">
                  {{row.minMoney + '-' + (row.maxMoney==0?'无限制':row.maxMoney)}}
                </template>
              </el-table-column>
              <el-table-column label="平台服务费比例" align="center" prop="" >
                <template #default="{row}">
                  {{row.platRatio + '%'}}
                </template>
              </el-table-column>
              <el-table-column label="客户留存比例" align="center" prop="" >
                <template #default="{row}">
                  {{row.customRatio + '%'}}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="edit" @click="add(scope)" >编辑</el-button>
                  <el-button link type="primary" icon="Delete" @click="delFee(scope)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button @click="add()" icon="Plus" style="width: 100%;border: 1px dashed #dcdfe6;margin-top: 6px;">新增</el-button>
          </el-form-item>
          <el-form-item style="width: 100%;">
            <div style="margin: 0 auto;">
              <el-button @click="resetForm">取消</el-button>
              <el-button @click="submitForm" type="primary" >提交</el-button>
            </div>
          </el-form-item>
      </div>
    </el-form>

    <!-- 新增手续费 -->
    <el-dialog :title=title v-model="open" width="500px" append-to-body>
      <el-form ref="addDialogRef" :model="addForm" :rules="feeRules" label-width="160">
        <el-form-item label="最小次数" prop="minAmount">
          <el-input v-model="addForm.minAmount" placeholder="请输入最小次数" type="number" @change="changeVal('minAmount',$event)" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="最大次数" prop="maxAmount">
          <el-input v-model="addForm.maxAmount" placeholder="请输入最大次数" type="number" @change="changeVal('maxAmount',$event)" />
        </el-form-item>
        <el-form-item label="起始额度" prop="minMoney">
          <el-input v-model="addForm.minMoney" placeholder="请输入起始额度" type="number" @change="changeVal('minMoney',$event)" :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="结束额度" prop="maxMoney">
          <el-input v-model="addForm.maxMoney" placeholder="请输入结束额度" type="number" @change="changeVal('maxMoney',$event)" />
        </el-form-item>
        <el-form-item label="平台服务费比例（%）" prop="platRatio">
          <el-input v-model="addForm.platRatio" placeholder="请输入平台服务费比例" type="number" onchange="if(value) if(value<=0){value=0} if(value>=100){value=100}" @change="ratioChange('plat')"/>
        </el-form-item>
        <el-form-item label="客户留存比例（%）" prop="customRatio">
          <el-input v-model="addForm.customRatio" placeholder="请输入客户留存比例" type="number" onchange="if(value) if(value<=0){value=0} if(value>=100){value=100}" @change="ratioChange('cus')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDialog()">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>


import {
  salaryAdvanceIntervalC, salaryAdvanceIntervalSingle,salaryAdvanceIntervalU,
} from "@/api/dispatch";

const { proxy } = getCurrentInstance();

const list = ref([]);
const open = ref(false)
const id = proxy.$route.query.id || '' // 编辑时数据id
const code = proxy.$route.query.code || '' // 编辑时数据code
const title = ref();
const disabled = ref(false);
const action = ref("insert");

let currentIndex;

const data = reactive({
  formLabelAlign: {
    ratio:[]
  },
  addForm:{},
  rules:{
    ratio: [{required: true,message:"请添加分成比例",trigger:"blur"}],
  },
  feeRules:{
    minAmount: [{required: true,message:"请输入最小次数",trigger:"blur"}],
    maxAmount: [{required: true,message:"请输入最大次数",trigger:"blur"}],
    minMoney: [{required: true,message:"请输入起始额度",trigger:"blur"}],
    maxMoney: [{required: true,message:"请输入结束额度",trigger:"blur"}],
    platRatio: [{required: true,message:"请输入平台分成比例",trigger:"blur"}],
    customRatio: [{required: true,message:"请输入客户留存比例",trigger:"blur"}],
  }
});

const { addForm,formLabelAlign,rules,feeRules } = toRefs(data);

if(code){
  getSalaryAdvanceInterval();
}

function ratioChange(type){
  if('plat'==type){
    let ratio = 100 - addForm.value.platRatio;
    if(ratio<0){
      addForm.value.customRatio = 0;
      addForm.value.platRatio = 100;
    } else if(ratio>100) {
      addForm.value.customRatio = 100;
      addForm.value.platRatio = 0;
    }else {
      addForm.value.customRatio = ratio;
    }
  }else {
    let ratio = 100 - addForm.value.customRatio;
    if(ratio<0) {
      addForm.value.platRatio = 0;
      addForm.value.customRatio = 100;
    }else  if(ratio>100) {
      addForm.value.platRatio = 100;
      addForm.value.customRatio = 0;
    }else {
      addForm.value.platRatio = ratio
    }
  }
}

function changeVal(type,value){
  if(value){
    if(value.length>4){
      if(value.slice(0, 4)>=9999){
        addForm.value[type] = 0;
      }else {
        addForm.value[type] = value.slice(0, 4);
      }
    }else {
      if(value<=0 || value>=9999){
        addForm.value[type] = 0;
      }else {
        addForm.value[type] = value;
      }
    }
  }
}

/** 新增、编辑手续费弹窗 */
function add(e){
  if(e){
    title.value = "编辑分成比例"
    disabled.value = e.$index === 0;
    addForm.value = {...e.row};
    currentIndex = e.$index;
  }else {
    addForm.value = {}
    title.value = "新增分成比例"
    disabled.value = true;
    let list = formLabelAlign.value.ratio || []
    if(list.length===0){
      addForm.value.minAmount = 0;
      addForm.value.minMoney = 0;
    }else {
      let ratio = list[list.length-1];
      if(ratio.maxAmount==0 || ratio.maxMoney==0){
        return proxy.$modal.msgWarning(`已存在无限制区间，无法新增`);
      }
      addForm.value.minAmount = parseFloat(ratio.maxAmount) + 1;
      addForm.value.minMoney = parseFloat(ratio.maxMoney) + 1;
    }
  }

  open.value= true;
  if(proxy.$refs.addDialogRef!=undefined){
    proxy.$refs.addDialogRef.clearValidate()
  }
}
/** 保存手续费 */
function submitDialog(){
  proxy.$refs.addDialogRef.validate((valid) => {
    if (!valid) return;
    let list = formLabelAlign.value.ratio || []

    if(title.value==='新增分成比例'){
      if(addForm.value.maxAmount!=0){
        if(parseFloat(addForm.value.minAmount)>parseFloat(addForm.value.maxAmount)){
          return proxy.$modal.msgWarning(`最小次数不能大于最大次数`);
        }
      }
      if(addForm.value.maxMoney!=0){
        if(parseFloat(addForm.value.minMoney)>parseFloat(addForm.value.maxMoney)){
          return proxy.$modal.msgWarning(`起始额度不能大于结束额度`);
        }
      }

      addForm.value.sn = list.length + 1;
      formLabelAlign.value.ratio.push({...addForm.value})
    }else {
      if(addForm.value.maxAmount!=0 || currentIndex!=list.length-1){
        if(parseFloat(addForm.value.minAmount)>parseFloat(addForm.value.maxAmount)){
          return proxy.$modal.msgWarning(`最小次数不能大于最大次数`);
        }
      }
      if(addForm.value.maxMoney!=0 || currentIndex!=list.length-1){
        if(parseFloat(addForm.value.minMoney)>parseFloat(addForm.value.maxMoney)){
          return proxy.$modal.msgWarning(`起始额度不能大于结束额度`);
        }
      }

      //当前数据的上一条数据
      let lastData = formLabelAlign.value.ratio[currentIndex-1];
      //当前数据的下一条数据
      let nextData = formLabelAlign.value.ratio[currentIndex+1];
      //当前修改行数据
      let thisData = formLabelAlign.value.ratio[currentIndex];
      if(currentIndex==0 && addForm.value.maxAmount==0){
          list.splice(1,list.length-1)
      }else {
        if(currentIndex!==0){
          if(addForm.value.minAmount==0){
            return proxy.$modal.msgWarning('最小次数不能为0');
          }
          if(addForm.value.minMoney==0){
            return proxy.$modal.msgWarning('起始额度不能为0');
          }

          if(thisData.minAmount != addForm.value.minAmount){
            if(addForm.value.minAmount==1){
              return proxy.$modal.msgWarning('最小次数不能为1');
            }
            if(parseFloat(addForm.value.minAmount)<=parseFloat(lastData.minAmount)+1){
              return proxy.$modal.msgWarning(`最小次数应大于上一阶梯的最小次数+1：`+ (parseFloat(lastData.minAmount) + 1) );
            }else if(parseFloat(addForm.value.minAmount)>parseFloat(lastData.maxAmount)){
              return proxy.$modal.msgWarning(`最小次数应小于等于上一阶梯的最大次数：`+lastData.maxAmount);
            }else {
              lastData.maxAmount = addForm.value.minAmount - 1;
            }
          }
          if(thisData.minMoney != addForm.value.minMoney){
            if(addForm.value.minMoney==1){
              return proxy.$modal.msgWarning('起始额度不能为1');
            }
            if(parseFloat(addForm.value.minMoney)<=parseFloat(lastData.minMoney)+1){
              return proxy.$modal.msgWarning(`起始额度应大于上一阶梯的起始额度+1：`+ (parseFloat(lastData.minMoney) + 1) );
            }else if(parseFloat(addForm.value.minMoney)>parseFloat(lastData.maxMoney)){
              return proxy.$modal.msgWarning(`起始额度应小于等于上一阶梯的结束额度：`+lastData.maxMoney);
            }else {
              lastData.maxMoney = addForm.value.minMoney - 1;
            }
          }
        }

        if(currentIndex!==list.length-1){
          if(thisData.maxAmount != addForm.value.maxAmount){
            let nextMAxAmount = nextData.maxAmount;
            if(nextMAxAmount==0){
              nextMAxAmount = 9999;
            }
            if(parseFloat(addForm.value.maxAmount)>=parseFloat(nextMAxAmount)){
              return proxy.$modal.msgWarning(`最大次数应小于下一阶梯的最大次数：`+nextData.maxAmount);
            }else {
              nextData.minAmount = parseFloat(addForm.value.maxAmount) + 1
            }
          }
          if(thisData.maxMoney != addForm.value.maxMoney){
            let nextMAxAmount = nextData.maxMoney;
            if(nextMAxAmount==0){
              nextMAxAmount = 9999;
            }
            if(parseFloat(addForm.value.maxMoney)>=parseFloat(nextMAxAmount)){
              return proxy.$modal.msgWarning(`结束额度应小于下一阶梯的结束额度：`+nextData.maxMoney);
            }else {
              nextData.minMoney = parseFloat(addForm.value.maxMoney) + 1
            }
          }
        }
      }

      list[currentIndex] = addForm.value
      // for(let i = 0; i < list.length; i++) {
      //   if (list[i].id == addForm.value.id) {
      //     list[i] = addForm.value
      //   }
      // }
      formLabelAlign.value.ratio = list
    }

    open.value= false
  })
}
/** 删除分成比例 */
function delFee(row){
  if(formLabelAlign.value.ratio.length-1 === row.$index){
    formLabelAlign.value.ratio.splice(row.$index, 1)
  }else {
    //自动修改下一条数据的起始值
    if(row.$index==0){
      formLabelAlign.value.ratio[row.$index+1].minAmount = 0;
      formLabelAlign.value.ratio[row.$index+1].minMoney = 0;
    }else {
      formLabelAlign.value.ratio[row.$index+1].minAmount = parseFloat(formLabelAlign.value.ratio[row.$index-1].maxAmount) + 1
      formLabelAlign.value.ratio[row.$index+1].minMoney = parseFloat(formLabelAlign.value.ratio[row.$index-1].maxMoney) + 1
    }
    formLabelAlign.value.ratio.splice(row.$index, 1)

    // 序号更新
    formLabelAlign.value.ratio = formLabelAlign.value.ratio.map((item, index) => ({
      ...item,
      sn: index + 1
    }));
  }
}
/** 取消 */
function resetForm(){
  proxy.$router.go(-1);
}
/** 提交 */
function submitForm(){
  proxy.$refs.ruleFormRef.validate(async (valid) => {
    if (!valid) return;
    const submitForm = {...formLabelAlign.value}
    if(submitForm.ratio[submitForm.ratio.length-1].maxAmount!=0 && submitForm.ratio[submitForm.ratio.length-1].maxMoney!=0){
      return proxy.$modal.msgWarning('分成比例最后一个区间的最大次数或者结束额度请输入0');
    }
    submitForm.ratio = JSON.stringify(submitForm.ratio)
    if(action.value=='update'){
      salaryAdvanceIntervalU({...submitForm,code:code}).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }else {
      salaryAdvanceIntervalC({...submitForm,code:code,}).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }
  })
}
/** 获取当前派遣公司下设置的平台与客户分成比例 */
function getSalaryAdvanceInterval(){
  salaryAdvanceIntervalSingle({code:code}).then(res => {
    formLabelAlign.value.ratio = res.data;
    if(res.data.length>0){
      action.value = "update";
    }
  })
}


</script>
<style lang="scss">
.dispatch-salary-advance {
  .el-form.ruleFormRef {
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;

    .el-form-item {
      width: 30%;

      .el-input, .el-select, .el-date-editor.el-input, .el-date-editor.el-input__wrapper {
        width: 100%;
      }
    }
  }
}
.tips{
  margin-top: 0px;
  padding: 8px;
  color: #ED6F1C;
  background: #FFFAE8;
  line-height: 1.4;
  font-size: 12px;
  display: flex;
  justify-content: flex-start;
}

.tipscontent{
  margin-left: 7.4%;
}
.box{
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  margin: 0% -4% 1% -4%;
  padding-top:2%;
  background-color: white;
  width: 950%;
}
.boxTitle{
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 16px;
  margin: 0% auto 2% 3%;
}
</style>
