<template>
    <q-dialog
        v-model="persistent"
        full-height
        maximized
        position="right"
        persistent
        @hide="closeCutomer"
        transition-show="slide-left"
    >
        <div class="customMain" v-if="addMsg">
            <div class="cycle_Title">市场顾问教师提成规则</div>
            <div style="margin-top: 10px;">
                <q-input
                    filled
                    stack-label
                    :dense="false"
                    v-model="addMsg.Name"
                    style="width: 640px;"
                    ref="Name"
                    class="col-12 q-pb-lg"
                    label="方案名称"
                    :rules="[val => !!val || '请填写方案名称']"
                />
            </div>
              <q-select
                filled
                stack-label
                option-value="SId"
                option-label="SName"
                v-model="addMsg.SchoolIds"
                use-chips
                :options="SchoolList"
                label="校区"
                :dense="false"
                class="col-6 q-pr-lg q-pb-lg"
                emit-value
                multiple
                map-options
               @input="$forceUpdate()"
            />

            <div style="display: flex;align-items: center;">
                <span style="width: 75px;">类型：</span>
                <q-radio v-model="addMsg.Type" val="1" label="市场" />
                <q-radio v-model="addMsg.Type" val="2" label="顾问" />
                <q-radio v-model="addMsg.Type" val="3" label="教师" />
            </div>
            <div style="display: flex;align-items: center;">
                <span style="width: 75px;">课程类型：</span>
                <q-radio v-model="addMsg.CourseType" val="1" label="包含" />
                <q-radio v-model="addMsg.CourseType" val="2" label="不包含" />
            </div>
            <q-select
                filled
                stack-label
                option-value="CourseId"
                option-label="CourseName"
                v-model="addMsg.CourseList"
                use-chips
                use-input
                :options="myCourseList"
                label="课程"
                :dense="false"
                class="col-6 q-pr-lg q-pb-lg"
                emit-value
                multiple
                map-options
                @filter="filterFn"
            />


            <div style="margin-top: 10px;" >
                <q-input
                    filled
                    style="width: 640px;"
                    stack-label
                    type="number"
                    :dense="false"
                    v-model="addMsg.FirstRate"
                    ref="FirstRate"
                    class="col-12 q-pb-lg"
                    label="首次发放比例（%）"
                    :rules="[val => !!val || '请填写首次发放比例']"

                />
            </div>
            <div style="margin-top: 10px;" >
                <q-input
                    filled
                    style="width: 640px;"
                    stack-label
                    type="number"
                    :dense="false"
                    v-model="addMsg.CourseRate"
                    ref="CourseRate"
                    class="col-12 q-pb-lg"
                    label="课程比例（%）"
                    :rules="[val => val >=0 || '请填写课程比例']"

                />
            </div>
            <div style="display: flex;align-items: center;margin-bottom: 15px;">
                 <q-select
                    filled
                    stack-label
                    option-value="Id"
                    option-label="EmployeeName"
                    v-model="addMsg.EmpList"
                    use-chips
                    use-input
                    :options="myEmployeeList"
                    label="提成人员"
                    :dense="false"
                    emit-value
                    multiple
                    map-options
                    @filter="filterEmployee"
                    style="flex:1;"
                    @input='getpersonnel(1)'
                />
                <div class="q-gutter-sm" style="margin-right: 18px;">
                     <q-checkbox v-model="personnel" label="全选" @input='getallpersonnel(1)'/>
                </div>
            </div>
            <!-- <div style="display: flex;align-items: center;margin-bottom: 15px;">
                <q-select
                    filled
                    stack-label
                    option-value="Id"
                    option-label="EmployeeName"
                    v-model="addMsg.ChildEmpList"
                    use-chips
                    use-input
                    :options="myEmployeeList"
                    label="部门人员"
                    :dense="false"
                    emit-value
                    multiple
                    map-options
                    @filter="filterEmployee"
                    style="flex:1;"

                    @input='getpersonnel(2)'

                />
                 <div class="q-gutter-sm" style="margin-right: 18px;">
                     <q-checkbox v-model="branch" label="全选" @input='getallpersonnel(2)'/>
                </div>
            </div> -->


            <div>
                <span style="width: 75px;">提成类型：</span>
                <q-radio v-model="addMsg.SendType" val="1" label="业绩比例" />
                <q-radio v-model="addMsg.SendType" val="2" label="固定金额" />
            </div>
            <!-- style="margin-bottom: 80px;"  -->
            <div v-if="addMsg.SendType=='1'"
            :style="{'margin-bottom': addMsg.Type==1&&addMsg.ChildEmpList
            &&addMsg.ChildEmpList.length>0?'0':'80px'}">
                <div>业绩比例</div>

                <div
                    v-for="(x,y) in addMsg.RateList"
                    :key="y"
                    style="display: flex;align-items: center;margin-bottom: 10px;"
                >
                    <q-input
                        clearable
                        filled
                        v-model="x.StartValue"
                        style="width: 190px;margin-right: 5px;"
                        type="number"
                        @input="$forceUpdate()"
                        label="初始值"
                    />
                    <q-input
                        clearable
                        filled
                        v-model="x.EndValue"
                        style="width: 190px;margin-right: 5px;"
                        type="number"
                        @input="$forceUpdate()"
                        label="结束值"
                    />
                    <q-input
                        clearable
                        filled
                        v-model="x.Rate"
                        style="width: 190px;margin-right: 5px;"
                        type="number"
                        @input="$forceUpdate()"
                        label="提成比例（%）"
                    />
                    <q-btn
                        round
                        size="xs"
                        color="deep-orange"
                        icon="delete"
                        v-if="addMsg.RateList.length > 1"
                        @click="addMsg.RateList.splice(y, 1)"
                        style="margin-left: 10px;"
                    />
                    <q-btn
                        round
                        size="xs"
                        color="primary"
                        icon="add"
                        v-if="addMsg.RateList.length == y + 1"
                        @click="addMsg.RateList.push({ StartValue: '', EndValue: '', Rate: '' })"
                        style="margin-left: 10px;"
                    />
                </div>
            </div>
            <div v-if="addMsg.SendType=='2'"
            :style="{'margin-bottom': addMsg.Type==1&&addMsg.ChildEmpList
            &&addMsg.ChildEmpList.length>0?'0':'80px'}">
                <div>固定金额</div>

                <div style="display: flex;align-items: center;margin-bottom: 10px;">
                    <q-input
                        clearable
                        filled
                        v-model="addMsg.PeopleMoney"
                        style="width: 190px;margin-right: 5px;"
                        type="number"
                        @input="$forceUpdate()"
                        label="提成金额">
                        <template v-slot:append>
                            <span class="fz14">/人</span>
                        </template>
                    </q-input>
                    <q-input
                        clearable
                        filled
                        v-model="addMsg.ExtraMoney"
                        style="width: 190px;margin-right: 5px;"
                        type="number"
                        @input="$forceUpdate()"
                        label="额外奖励">
                        <template v-slot:append>
                            <span class="fz14">/人</span>
                        </template>
                    </q-input>
                    <div>
                        <!-- <span class="fz14 text-negative">注释：额外奖励需确认邀约咨询30分钟以上</span> -->
                    </div>
                </div>
            </div>
            <div v-if="addMsg.Type==1&&addMsg.ChildEmpList&&addMsg.ChildEmpList.length>0"
              :style="{'margin-bottom': addMsg.EnableZGAward==0?'80px':''}" >
              <q-toggle v-model="addMsg.EnableZGAward"
              label="是否启用部门人头奖励"
              left-label
              false-value="0"
              true-value="1"/>
            </div>
            <div style="margin-bottom: 80px;" v-if="addMsg.EnableZGAward==1">
              <div>人头奖励阶梯列表</div>

              <div
                  v-for="(x,y) in addMsg.ZGAwardList"
                  :key="y"
                  style="display: flex;align-items: center;margin-bottom: 10px;"
              >
                  <q-input
                      clearable
                      filled
                      v-model="x.StartValue"
                      style="width: 190px;margin-right: 5px;"
                      type="number"
                      @input="$forceUpdate()"
                      label="初始值"
                  />
                  <q-input
                      clearable
                      filled
                      v-model="x.EndValue"
                      style="width: 190px;margin-right: 5px;"
                      type="number"
                      @input="$forceUpdate()"
                      label="结束值"
                  />
                  <q-input
                      clearable
                      filled
                      v-model="x.Rate"
                      style="width: 190px;margin-right: 5px;"
                      type="number"
                      @input="$forceUpdate()"
                      label="提成金额"
                  />
                  <q-btn
                      round
                      size="xs"
                      color="deep-orange"
                      icon="delete"
                      v-if="addMsg.ZGAwardList.length > 1"
                      @click="addMsg.ZGAwardList.splice(y, 1)"
                      style="margin-left: 10px;"
                  />
                  <q-btn
                      round
                      size="xs"
                      color="primary"
                      icon="add"
                      v-if="addMsg.ZGAwardList.length == y + 1"
                      @click="addMsg.ZGAwardList.push({ StartValue: '', EndValue: '', Rate: '' })"
                      style="margin-left: 10px;"
                  />
              </div>
          </div>
          <div style="margin-bottom: 80px;">
            <div>部门共同奖金分配</div>
            <div
                  v-for="(x,y) in addMsg.DeptAwardList"
                  :key="y"
                  style="display: flex;align-items: center;margin-bottom: 10px;"
              >
                  <q-select
                    filled
                    stack-label
                    option-value="Id"
                    option-label="EmployeeName"
                    v-model="x.EmpId"
                    use-input
                    :options="myEmployeeList"
                    label="奖励分配人员"
                    :dense="false"
                    emit-value
                    map-options
                    @filter="filterEmployee"
                    style="width: 240px;margin-right: 5px;"
                    @input='getDeptPersonnel(x,y)'
                />
                <q-input
                      clearable
                      filled
                      v-model="x.Rate"
                      style="width: 190px;"
                      type="number"
                      @input="$forceUpdate()"
                      label="奖励分配比例（%）"
                  />
                  <q-btn
                      round
                      size="xs"
                      color="deep-orange"
                      icon="delete"
                      v-if="addMsg.DeptAwardList.length > 1"
                      @click="addMsg.DeptAwardList.splice(y, 1)"
                      style="margin-left: 10px;"
                  />
                  <q-btn
                      round
                      size="xs"
                      color="primary"
                      icon="add"
                      v-if="addMsg.DeptAwardList.length == y + 1"
                      @click="addMsg.DeptAwardList.push({ EmpId: '',EmName:'', Rate: '' })"
                      style="margin-left: 10px;"
                  />
              </div>
          </div>
            <div style="width: 100%;height: 50px;position: absolute;left: 0;bottom: 0;background: #FFF;display: flex;align-items: center;padding: 0 20px;justify-content: flex-end;">
                <q-btn
                    color="accent"
                    size="sm"
                    class="q-mr-md"
                    label="保存"
                    @click="setAdd()"
                ></q-btn>
            </div>

            <div class="dialog-out-close" @click="closeCutomer">
                <i class="iconfont icon-close" style="font-size:26px;" />
            </div>
        </div>
    </q-dialog>
</template>
<script>



export default {
    components: {

    },
    props: {
        saveObj: {
            type: Object,
            default: null
        },
        isAdd: {// true新增 false修改
            type: Boolean,
            default: true
        },
        loyeeList: {//人员列表
            type: Array,
            default: []
        },
        CourseList: {//课程下拉列表
            type: Array,
            default: []
        },
        SchoolList:{//校区下拉列表
             type: Array,
            default: []
        },
        selectData:{//修改带过来的对象
            type: Object,
            default: {}
        }
    },
    data() {
        return {
            persistent: true,
            addMsg: null,
            //员工列表
            employeeList: [],
            myEmployeeList: [],
            allCourseList: [],
            myCourseList:[],
            personnel:false,//人员全选
            branch:false,//部门人员
        }
    },
    created() {
        this.employeeList = JSON.parse(JSON.stringify(this.loyeeList))
        this.myEmployeeList = JSON.parse(JSON.stringify(this.loyeeList))
        this.allCourseList = JSON.parse(JSON.stringify(this.CourseList))
        this.myCourseList = JSON.parse(JSON.stringify(this.CourseList))
        if (this.isAdd == true) {//新增
            this.addMsg = {
                Id: 0,
                Name: '',
                Type: '1',
                CourseType: '1',
                SchoolIds: [],
                CourseList: [],//课程列表
                EmpList: [],//提现人员
                ChildEmpList: [],//部门人员
                CourseRate: '',//课程比例
                FirstRate:'',//首次发放比例
                RateList: [
                    { StartValue: '', EndValue: '', Rate: '' }
                ],
                SendType: '1',
                PeopleMoney: 0,
                ExtraMoney: 0,
                EnableZGAward: '0',
                ZGAwardList: [
                    { StartValue: '', EndValue: '', Rate: '' }
                ],
                DeptAwardList:[
                  {EmpId:null,EmName:null,Rate:null}
                ]
            }
        } else {//修改
            this.addMsg = JSON.parse(JSON.stringify(this.selectData))
            this.addMsg.Type = this.addMsg.Type.toString()
            this.addMsg.CourseType = this.addMsg.CourseType.toString()
            this.addMsg.SchoolIds = this.selectData.SchoolIds?this.selectData.SchoolIds.split(',').map(Number):[] ;
            this.addMsg.CourseList = this.getId(this.selectData.CourseList,2)
            this.addMsg.EmpList = this.getId(this.selectData.EmpList,3)
            this.addMsg.ChildEmpList = this.getId(this.selectData.ChildEmpList,3)
            this.addMsg.SendType = this.addMsg.SendType?String(this.addMsg.SendType):'1'
            this.addMsg.PeopleMoney = this.addMsg.PeopleMoney?this.addMsg.PeopleMoney:0
            this.addMsg.ExtraMoney = this.addMsg.ExtraMoney?this.addMsg.ExtraMoney:0
            this.addMsg.EnableZGAward = this.addMsg.EnableZGAward?String(this.addMsg.EnableZGAward):'0'
            this.addMsg.DeptAwardList = this.addMsg.DeptAwardList?this.addMsg.DeptAwardList:[{EmpId:null,EmName:null,Rate:null}]
            if(this.addMsg.EmpList.length== this.employeeList.length){
                this.personnel=true
            }else{
                this.personnel=false
            }

            if(this.addMsg.ChildEmpList.length== this.employeeList.length){
                this.branch=true
            }else{
                this.branch=false
            }
            if(this.addMsg.RateList.length==0){
                this.addMsg.RateList.push({ StartValue: '', EndValue: '', Rate: '' })
            }
            if(this.addMsg.ZGAwardList&&this.addMsg.ZGAwardList.length==0&&this.addMsg.EnableZGAward){
                this.addMsg.ZGAwardList.push({ StartValue: '', EndValue: '', Rate: '' })
            }

        }
    },
    mounted() {

    },
    methods: {
        getId(arr,type){
            let list = [];
            let Id = 'Id';
            if(type==1){
                Id = 'SId';
            }else if(type==2){
                Id = 'CourseId';
            }else if(type==3){
                Id = 'Id';
            }
            if(arr && arr.length>0){
                arr.forEach(x=>{
                    list.push(x[Id])
                })
            }
            return list
        },
        closeCutomer() {
            this.$emit('close')
        },


        //筛选员工
        filterEmployee(val, update, abort) {
            update(() => {
                if (val === '') {
                    this.myEmployeeList = this.employeeList
                }
                else {
                    const needle = val.toLowerCase();
                    this.myEmployeeList = this.employeeList.filter(v => v.EmployeeName.toLowerCase().indexOf(needle) > -1);
                }
            })
        },
        filterFn(val, update) {//课程的栓选
            update(() => {
                if (val === '') {
                    this.myCourseList = this.allCourseList
                }
                else {
                    const needle = val.toLowerCase();
                    this.myCourseList = this.allCourseList.filter(v => v.CourseName.toLowerCase().indexOf(needle) > -1);
                }
            })
        },
        setAdd() {
            this.$refs.Name.validate();
            this.$refs.CourseRate.validate();
            this.$refs.FirstRate.validate();
            if(this.addMsg.SendType=='1'){
                this.addMsg.PeopleMoney = 0
                this.addMsg.ExtraMoney = 0
            }else{
                this.addMsg.RateList = []
                if(this.addMsg.PeopleMoney==''){
                    this.addMsg.PeopleMoney = 0
                }if(this.addMsg.ExtraMoney==''){
                    this.addMsg.ExtraMoney = 0
                }
            }
            if (!this.$refs.Name.hasError && !this.$refs.CourseRate.hasError && !this.$refs.FirstRate.hasError) {

                let msg = JSON.parse(JSON.stringify(this.addMsg))
                if (this.addMsg.SchoolIds && this.addMsg.SchoolIds.length == 0) {
                    this.$q.notify({
                        type: 'negative',
                        message: `请选择校区`,
                        position: 'top'
                    })
                    return
                }else{
                    msg.SchoolIds = this.addMsg.SchoolIds.join(',')
                }
                msg.CourseList =  this.getList(this.allCourseList,this.addMsg.CourseList,2,'CourseId','CourseName')//课程
                if (this.addMsg.EmpList.length == 0) {
                    this.$q.notify({
                        type: 'negative',
                        message: `请选择提成人员`,
                        position: 'top'
                    })
                    return
                }else{
                    msg.EmpList =  this.getList(this.employeeList,this.addMsg.EmpList,3,)
                }
                 msg.ChildEmpList =  this.getList(this.employeeList,this.addMsg.ChildEmpList,3,)//部门人员
                for(let i=0;i<msg.RateList.length;i++){
                    let x = msg.RateList[i]
                    if(x.StartValue==='' ){
                         this.$q.notify({
                            type: 'negative',
                            message: `请输入业绩比例初始值`,
                            position: 'top'
                        })
                        return
                    }
                    if(x.EndValue==''){
                         this.$q.notify({
                            type: 'negative',
                            message: `请输入业绩比例结束值`,
                            position: 'top'
                        })
                        return
                    }
                    if(x.Rate<0){
                         this.$q.notify({
                            type: 'negative',
                            message: `请输入业绩比例不小于0的提成比例`,
                            position: 'top'
                        })
                        return
                    }
                }
                if(msg.EnableZGAward=='1'){
                    for(let i=0;i<msg.ZGAwardList.length;i++){
                      let x = msg.ZGAwardList[i]
                      if(x.StartValue==='' ){
                          this.$q.notify({
                              type: 'negative',
                              message: `请输入有效到访奖励初始值`,
                              position: 'top'
                          })
                          return
                      }
                      if(x.EndValue==''){
                          this.$q.notify({
                              type: 'negative',
                              message: `请输入有效到访奖励结束值`,
                              position: 'top'
                          })
                          return
                      }
                      if(x.Rate<0){
                          this.$q.notify({
                              type: 'negative',
                              message: `请输入有效到访奖励不小于0的提成比例`,
                              position: 'top'
                          })
                          return
                      }
                  }
                }else{
                  msg.ZGAwardList = []
                }
                if(msg.DeptAwardList.length>0){
                  for(let i=0;i<msg.DeptAwardList.length;i++){
                    let x = msg.DeptAwardList[i]
                    if(!x.EmpId){
                        this.$q.notify({
                            type: 'negative',
                            message: `请选择奖励分配人员`,
                            position: 'top'
                        })
                        return
                    }
                    if(!x.Rate){
                        this.$q.notify({
                            type: 'negative',
                            message: `请输入奖励分配比例`,
                            position: 'top'
                        })
                        return
                    }
                  }
                }
                this.$emit('success',msg)
            }
        },
        getList(arr,xzarr,type,){
            let list = [];
            let Id = 'Id';
            let Name = 'Name';
            if(type==1){
                Id = 'SId';
                Name = 'SName';
            }else if(type==2){
                Id = 'CourseId';
                Name = 'CourseName';
            }else if(type==3){
                Id = 'Id';
                Name = 'EmployeeName';
            }
            xzarr.forEach(x => {
                for(let i= 0;i<arr.length;i++){
                    let j = arr[i]
                    if(j[Id] == x){
                        let obj = {}
                        obj[Id]=j[Id],
                        obj[Name]=j[Name],
                        list.push(obj)
                        break
                    }
                }
            });
            return list
        },
        getallpersonnel(type){
            if(type==1){//人员全选
                if(this.personnel== true){
                    this.addMsg.EmpList = []
                    this.myEmployeeList.forEach(x=>{
                        this.addMsg.EmpList.push(x.Id)
                    })
                }else{
                    this.addMsg.EmpList = []
                }
            }else{//部门人员全选
                if(this.branch== true){
                    this.addMsg.ChildEmpList = []
                    this.employeeList.forEach(x=>{
                        this.addMsg.ChildEmpList.push(x.Id)
                    })
                }else{
                    this.addMsg.ChildEmpList = []
                }
            }

        },
        getDeptPersonnel(item,i){
          let obj = this.myEmployeeList.filter(x=>{return x.Id==item.EmpId})
          if(obj&&obj.length>0)this.addMsg.DeptAwardList[i].EmName = obj[0].EmployeeName
        },
        getpersonnel(type){
            if(type==1){//人员全选
                 if(this.addMsg.EmpList.length== this.employeeList.length){
                    this.personnel=true
                }else{
                    this.personnel=false
                }
            }else{//部门人员全选
                if(this.addMsg.ChildEmpList.length== this.employeeList.length){
                    this.branch=true
                }else{
                    this.branch=false
                }
            }

        },




    },
}
</script>
<style scoped>
.cycle_Title {
    font-size: 20px;
    font-weight: 500;
    color: #1f2329;
}
.customMain {
    width: 700px !important;
    display: flex;
    flex-direction: column;
    height: 100 vh;
    padding: 15px 17px 0 17px;
    background-color: #fff;
}
</style>
