<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="最低预支额度" prop="minAmount">
            <el-input v-model="formLabelAlign.minAmount" type="number" oninput="if(value) if(value<=0){value=0} if(value>9999){value=9999}"/>
          </el-form-item>
          <el-form-item></el-form-item>
          <el-form-item></el-form-item>
          <el-form-item label="无手续费当月累计限额" prop="freeAmount">
            <el-input v-model="formLabelAlign.freeAmount"  type="number" oninput="if(value) if(value<=0){value=0} if(value>9999){value=9999}"/>
          </el-form-item>
          <el-form-item></el-form-item>
      </div>
      <div class="box">
        <div class="boxTitle">阶梯手续费</div>
          <el-form-item label="手续费" style="width: 1010px;" prop="fee">
            <el-table :data="formLabelAlign.fee">
              <el-table-column label="手续费" align="center" prop="serviceFee" >
                <template #default="{row}">
                  {{row.serviceFee + '%'}}
                </template>
              </el-table-column>
              <el-table-column label="金额范围" align="center" prop="minAmount" >
                <template #default="{row}">
                  {{row.minAmount + '-' + row.maxAmount}}
                </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="110">
        <el-form-item label="手续费（%）" prop="serviceFee">
          <el-input v-model="addForm.serviceFee" placeholder="请输入手续费" type="number" onchange="if(value) if(value<=0){value=0} if(value>=1){value=1}" />
        </el-form-item>
        <el-form-item label="起始额度" prop="minAmount">
          <el-input v-model="addForm.minAmount" placeholder="请输入起始额度" type="number" onchange="if(value) if(value<=0){value=0} if(value>=9999){value=0}" :disabled="disabled"/>
        </el-form-item>
        <el-form-item label="结束额度" prop="maxAmount">
          <el-input v-model="addForm.maxAmount" placeholder="请输入结束额度" type="number" maxlength="4" onchange="if(value) if(value<=0){value=0} if(value>=9999){value=0}" />
        </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 {salaryAdvanceInsert, salaryAdvanceSingle, salaryAdvanceUpdate} 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);

let currentIndex;

const data = reactive({
  formLabelAlign: {
    minAmount:'',
    freeAmount:'',
    fee:[]
  },
  addForm:{},
  rules:{
    minAmount: [{required: true,message:"请输入最低预支额度",trigger:"blur"}],
    freeAmount: [{required: true,message:"请输入无手续费当月累计限额",trigger:"blur"}],
    fee: [{required: true,message:"请添加手续费",trigger:"blur"}],
  },
  feeRules:{
    serviceFee: [{required: true,message:"请输入手续费",trigger:"blur"}],
    minAmount: [{required: true,message:"请输入起始额度",trigger:"blur"}],
    maxAmount: [{required: true,message:"请输入结束额度",trigger:"blur"}],
  }
});

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

if(code){
  getSalaryAdvance();
}
/** 新增、编辑手续费弹窗 */
function add(e){
  if(e){
    title.value = "编辑手续费"
    disabled.value = e.$index === 0;
    addForm.value = {...e.row};
    currentIndex = e.$index;
  }else {
    addForm.value = {
      maxAmount: '',
      minAmount: '',
      serviceFee: ''
    }
    title.value = "新增手续费"
    disabled.value = true;
    let list = formLabelAlign.value.fee || []
    if(list.length===0){
      addForm.value.minAmount = 0;
    }else {
      let fee = list[list.length-1];
      if(fee.maxAmount==0){
        return proxy.$modal.msgWarning(`已存在无限制区间，无法新增`);
      }
      addForm.value.minAmount = parseFloat(fee.maxAmount) + 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.fee || []

    const isNewFee = title.value === '新增手续费';
    //校验起始额度、结束额度
    for (let i = 0;  i < list.length; i++) {
      if (isNewFee) {
        if(list[i].serviceFee == addForm.value.serviceFee){
          return proxy.$modal.msgWarning(`手续费已存在!`);
        }
      }else {
        if(i !== currentIndex){
          if(!list[i].id && !addForm.value.id){
            if(list[i].serviceFee == addForm.value.serviceFee){
              return proxy.$modal.msgWarning(`手续费已存在!`);
            }
          } else {
            if(list[i].serviceFee == addForm.value.serviceFee && list[i].id != addForm.value.id){
              return proxy.$modal.msgWarning(`手续费已存在!`);
            }
          }
        }
      }
    }

    if(title.value==='新增手续费'){
      if(addForm.value.maxAmount!=0){
        if(parseFloat(addForm.value.minAmount)>parseFloat(addForm.value.maxAmount)){
          return proxy.$modal.msgWarning(`起始额度不能大于结束额度!`);
        }
      }

      formLabelAlign.value.fee.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(`起始额度不能大于结束额度!`);
        }
      }

      //当前数据的上一条数据
      let lastData = formLabelAlign.value.fee[currentIndex-1];
      //当前数据的下一条数据
      let nextData = formLabelAlign.value.fee[currentIndex+1];
      //当前修改行数据
      let thisData = formLabelAlign.value.fee[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(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(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
            }
          }
        }
      }

      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.fee = list
    }

    open.value= false
  })
}
/** 删除手续费 */
function delFee(row){
  if(formLabelAlign.value.fee.length-1 === row.$index){
    formLabelAlign.value.fee.splice(row.$index, 1)
  }else {
    //自动修改下一条数据的起始额度
    if(row.$index==0){
      formLabelAlign.value.fee[row.$index+1].minAmount = 0;
    }else {
      formLabelAlign.value.fee[row.$index+1].minAmount = parseFloat(formLabelAlign.value.fee[row.$index-1].maxAmount) + 1
    }
    formLabelAlign.value.fee.splice(row.$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.fee[submitForm.fee.length-1].maxAmount!=0){
      return proxy.$modal.msgWarning('阶梯手续费最后一个区间的结束额度请输入0');
    }
    submitForm.fee = JSON.stringify(submitForm.fee)
    if(formLabelAlign.value.id){
      salaryAdvanceUpdate({...submitForm,code:code,rsapId:formLabelAlign.value.id}).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }else {
      salaryAdvanceInsert({...submitForm,code:code,}).then(res => {
        proxy.$modal.msgSuccess(res.code)
        const obj = { path: "/dispatch" };
        proxy.$tab.closeOpenPage(obj);
      })
    }
  })
}
/** 获取当前派遣公司下设置的预支工资额度 */
function getSalaryAdvance(){
  salaryAdvanceSingle({code:code}).then(res => {
    if(res.data){
      if(res.data.salaryAdvanceParam){
        formLabelAlign.value = res.data.salaryAdvanceParam;
      }
      if(res.data.salaryAdvanceFee){
        formLabelAlign.value.fee = res.data.salaryAdvanceFee;
      }
    }
  })
}


</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>
