<template>
  <div class="dispatch-salary-advance">
    <p class="tips">
      <div class="tipscontent">
        <el-icon size="14px"><WarningFilled/></el-icon>
<!--        温馨提醒：预支工资最大次数、最大额度不超过1万，阶梯比例最后一个区间的最大次数或结束额度请输入0，0代表9999。</div>-->
        温馨提醒：阶梯比例最后一个区间的最大次数或结束额度请输入0，0代表无限制。</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 w100">
        <el-form-item label="用户结算日" prop="bill_day" >
          <div class="f_c">
            <el-input v-model="formLabelAlign.bill_day" type="number"/>
            <div class="tips">当月账单次月结算，超过次月结算日，用户未结算、系统会通知用户结算上月账单</div>
          </div>
        </el-form-item>
        <el-form-item label="系统结算日" prop="settle_day">
          <div class="f_c">
            <el-input v-model="formLabelAlign.settle_day" type="number"/>
            <div class="tips">用户未结算的情况下，系统会自动结算上月账单</div>
          </div>
        </el-form-item>
        <div style="height: 10px;"></div>
      </div>
      <div class="box">
        <el-form-item label="发薪账单手续费" prop="salaryBillFee">
            <el-input v-model="formLabelAlign.salaryBillFee" type="number" style="width: 300px;" />
        </el-form-item>
        <br/>
        <el-form-item label="合同账单手续费" prop="contractBillFee">
            <el-input v-model="formLabelAlign.contractBillFee" type="number" style="width: 300px;" />
        </el-form-item>
        <div style="height: 10px;"></div>
      </div>
      <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"}],
    bill_day: [{ required: true, message: "请输入用户结算日", trigger: ['blur', 'change']},
      { pattern : /^\d+$/, message: "请输入正整数", trigger: ['blur', 'change']},
      { validator: validateNumber, trigger: ['blur', 'change']}],
    settle_day: [{ required: true, message: "请输入系统结算日", trigger: ['blur', 'change']},
      { pattern : /^\d+$/, message: "请输入正整数", trigger: ['blur', 'change']},
      { validator: validateNumber, trigger: ['blur', 'change']}],
    salaryBillFee: [
      { required: true, message: "请输入发薪账单手续费", trigger: ['blur', 'change']},
      { pattern : /^\d+$/, message: "请输入正整数", trigger: ['blur', 'change']}
    ],
    contractBillFee: [
      { required: true, message: "请输入合同账单手续费", trigger: ['blur', 'change']},
      { pattern : /^\d+$/, message: "请输入正整数", trigger: ['blur', 'change']}
    ],
  },
  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<=0 || value>=10000000){
      addForm.value[type] = 0;
    }else {
      addForm.value[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 validateNumber(rule,value,callback) {
  if(value<1 || value>10){
    callback(new Error("请输入1-10之间的数字"));
  }else {
    callback();
  }
}

/** 新增、编辑手续费弹窗 */
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(`起始额度不能大于结束额度`);
        }
      }

      if(addForm.value.maxAmount==0 && addForm.value.maxMoney!=0){
        addForm.value.maxMoney=0;
      }
      if(addForm.value.maxMoney==0 && addForm.value.maxAmount!=0){
        addForm.value.maxAmount=0;
      }

      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 = 10000000;
            }
            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 = 10000000;
            }
            if(parseFloat(addForm.value.maxMoney)>=parseFloat(nextMAxAmount)){
              return proxy.$modal.msgWarning(`结束额度应小于下一阶梯的结束额度：`+nextData.maxMoney);
            }else {
              nextData.minMoney = parseFloat(addForm.value.maxMoney) + 1
            }
          }
        }
      }

      if(addForm.value.maxAmount==0 && addForm.value.maxMoney!=0){
        addForm.value.maxMoney=0;
      }
      if(addForm.value.maxMoney==0 && addForm.value.maxAmount!=0){
        addForm.value.maxAmount=0;
      }

      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;

    //校验用户结算日须早于结算日
    if(parseFloat(formLabelAlign.value.bill_day)>parseFloat(formLabelAlign.value.settle_day)){
      return proxy.$modal.msgWarning('用户结算日须早于系统结算日');
    }

    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.salaryAdvanceIntervalList;
    formLabelAlign.value.bill_day = res.data.billDay;
    formLabelAlign.value.settle_day = res.data.settleDay;
    formLabelAlign.value.contractBillFee = res.data.contractBillFee;
    formLabelAlign.value.salaryBillFee = res.data.salaryBillFee;
    if(res.data.salaryAdvanceIntervalList.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: 100cm;
}
.w100{
  .el-form-item{
    width: 100% !important;
    .f_c{
      display: flex;
      justify-content: flex-start;
      width: 100%;
      .el-input{
        width: 300px !important;
      }
      .tips{
        width: calc(100% - 300px);
        background: rgba($color: #000000, $alpha: 0);
      }
    }
  }
}
.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>
