<template>
  <div class="domesticCommissionRule">
    <div class="query-box">
      <ul>
        <li>
          <span>
            <em>规则名称</em>
            <el-input type="text" v-model="msg.RuleName" @keyup.native.enter="handleCurrentChange(1)">
            </el-input>
          </span>
        </li>
        <li>
          <span style="display: flex;align-items: center;">
            <em>线路</em>
            <el-select v-model="msg.LineId" size="mini" @change="handleCurrentChange(1)">
              <el-option label="请选择" :value="0"></el-option>
              <el-option v-for="(item,index) in LineList" :key="item.index" :label="item.LineName" :value="item.LineID">
              </el-option>
            </el-select>
          </span>
        </li>


        <li>
          <input type="button" class="normalBtn" value="新增" @click="addNew">
        </li>
      </ul>
    </div>
    <div class="commonContent">
      <table v-loading="loading" class="singeRowTable" border="0" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th>规则名称</th>
            <th>线路</th>
            <th>公司</th>
            <th>销售类型</th>
            <!-- <th>来源 </th> -->
            <!-- <th>团队类型 </th> -->
            <!-- <th>类型</th> -->
            <th>参与提成人员</th>
            <th>提成范围</th>
            <!-- <th>结束值</th> -->
            <th>提成比例</th>
            <th>地接奖金</th>
            <th>年终奖金</th>
            <th>扣除比例</th>
            <th>币种</th>
            <th>修改人</th>
            <th>修改时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <template v-for="(subItem,subIndex) in DataList">
          <tr v-for="(childItem,childIndex) in subItem.DetailList">
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">{{subItem.RuleName}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">
              <span v-for="(x,y) in subItem.LineNameList"
                :key="y+'1'">{{x}}{{subItem.LineNameList.length==y+1?'':'、'}}</span>
            </td>
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">{{subItem.BranchName}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">
              <span v-if="subItem.RuleType==1">销售</span>
              <span v-if="subItem.RuleType==2">OP</span>
              <span v-if="subItem.RuleType==3">自定义人员</span>
            </td>
            <td style="padding: 0 10px;" class="left-text-indent"  v-if="childIndex==0"
            :rowspan="subItem.DetailList.length">
              <span v-for="(son,sIndex ) in subItem.EmpNameStr.split(',')" :key="sIndex">
                <span v-if="sIndex<3">{{ son }}{{subItem.EmpNameStr.split(',').length==sIndex+1?'':'、'}}</span>
              </span>
              <el-popover
                v-if="subItem.EmpNameStr.split(',').length>2"
                placement="top-start"
                title="提成人员"
                width="400"
                trigger="click"
                :content="subItem.EmpNameStr">
                <el-button slot="reference" style="border: none;" type="text">查看更多</el-button>
              </el-popover>
            </td>
            <td>
              <span>{{childItem.StartValue}} 至 {{childItem.EndValue}}</span> </td>
            <td>
              <span>{{childItem.Rate}}% </span> </td> 
            <td>
              <span>{{childItem.DiJieBonus}} 
                <!-- {{subItem.CurrencyName}} -->
              </span> </td> 
            <td>
              <span>{{childItem.YearBonus}}</span> </td> 
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">
              {{subItem.ProfitRate}}%
            </td> 
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">{{subItem.CurrencyName}}</td>
            <td v-if="childIndex==0"
            :rowspan="subItem.DetailList.length">{{subItem.UpdateBy}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">{{subItem.UpdateDate}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.DetailList.length">
              <el-button-group size='mini'>
                <el-tooltip class="item" effect="dark" :content="$t('system.table_edit')" placement="top-start">
                  <el-button type="primary" icon="el-icon-edit"
                    @click="isShowDIv = true,divTitle='修改提成规则',getEdit(subItem)">
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="$t('system.table_delete')" placement="top-start">
                  <el-button type="danger" icon="el-icon-delete" @click="DeleteRules(subItem.Id)">
                  </el-button>
                </el-tooltip>
              </el-button-group>
            </td>


          </tr>
        </template>
        <tr v-if="DataList.length==0">
          <td colspan="14" align="center">暂无数据</td>
        </tr>
        <tfoot>
          <tr>
            <td colspan="14">
              <el-pagination background @current-change="handleCurrentChange" :current-page.sync="msg.pageIndex"
                layout="total,prev, pager, next, jumper" :page-size="msg.pageSize" :total="total">
              </el-pagination>
            </td>
          </tr>
        </tfoot>


      </table>
    </div>
    <el-dialog title="国内提成规则" :visible.sync="ruleVisible" width="800px">
      <el-form ref="addMsg" :model="addMsg" :rules="rules" label-width="110px">
        <el-form-item label="规则名称" prop="RuleName">
          <el-input type="text" v-model="addMsg.RuleName"></el-input>
        </el-form-item>
        <el-form-item label="线路" prop="LineshortIds">
          <el-select v-model="addMsg.LineshortIds" multiple placeholder="选择线路" style="width: 100%;">
            <el-option v-for="(item,index) in LineList" :key="index" :label="item.LineName" :value="item.LineID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="公司" prop="BranchId">
              <el-select v-model="addMsg.BranchId" placeholder="选择公司" style="width: 100%;">
                <el-option v-for="item in companyList" :label='item.BName' :value='item.Id' :key='item.Id'>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="结团审核人" prop="AuditEmpId">
              <el-select
                    v-model="addMsg.AuditEmpId"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="搜索审核人"
                    :remote-method="remoteMethod"
                    style="width: 100%;"
                    >
                    <el-option
                        v-for="item in searchList"
                        :key="item.empId"
                        :label="item.name"
                        :value="item.empId">
                        <span style="float: left">{{ item.name }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.postName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
          </el-col>
          
          <el-col :span="8">
            <el-form-item label="币种" prop="CurrencyId">
              <el-select placeholder="选择币种"
                v-model="addMsg.CurrencyId" style="width: 100%;" @change="getCurrent(addMsg.CurrencyId)">
                <el-option v-for="item in allCurrencyList" :key="item.ID" :label="item.Name" :value="item.ID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="参与人" prop="EmpIdList">
              <el-select
                    v-model="addMsg.EmpIdList"
                    multiple
                    collapse-tags
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请选择参与人"
                    style="width: 100%;"
                    >
                    <el-option
                        v-for="item in EmployeeList"
                        :key="item.EmployeeId"
                        :label="item.EmName"
                        :value="item.EmployeeId">
                        <span style="float: left">{{ item.EmName }}</span>
                    </el-option>
                </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="ProfitRate" label="业绩扣除比例">
              <el-input style="width: 100%;" type="Number" v-model="addMsg.ProfitRate"
                @keyup.native="checkPrice(x,'ProfitRate',true)"><template slot="append">%</template>
              </el-input>
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型" prop="RuleType">
              <el-radio v-model="addMsg.RuleType" label="1">销售</el-radio>
              <el-radio v-model="addMsg.RuleType" label="2" style="margin-right: 20px;">OP</el-radio>
              <!-- <el-radio v-model="addMsg.RuleType" label="3" style="margin-right: 20px;">自定义人员</el-radio>
              <span style="font-size: 12px;color:red">(*注:自定义人员将会跟随 OP规则设置的团队类型匹配)</span> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="提成比例表">
          <div style="width: 100%;border-bottom: 1px solid #e2e2e2;padding-bottom: 10px;margin-top: 10px;"
            v-for="(x,y) in addMsg.DetailList" :key='y'>
            <div style="display: flex;align-items: center;margin-bottom: 10px;">
              <el-row>
                <el-col :span="8">
                  <el-form-item :prop="'DetailList.'+ y +'.StartValue'" 
                  :rules="productGroupRules.StartValue" label="开始值">
                    <el-input style="width: 100%;" type="Number" v-model="x.StartValue"
                      @keyup.native="checkPrice(x,'Money',true)"><template slot="append">
                        <!-- {{CurrentNmae}} -->
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :prop="'DetailList.'+ y +'.EndValue'" 
                  :rules="productGroupRules.EndValue" label="结束值">
                    <el-input style="width: 100%;"  type="Number" v-model="x.EndValue"
                      @keyup.native="checkPrice(x,'Money',true)"><template slot="append">
                        <!-- {{CurrentNmae}} -->
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                
                <el-col :span="8">
                  <el-form-item :prop="'DetailList.'+ y +'.DiJieBonus'"
                    :rules="productGroupRules.DiJieBonus" label="地接奖金">
                    <el-input style="width: 100%;" type="Number" v-model="x.DiJieBonus"
                      @keyup.native="checkPrice(x,'DiJieBonus',true)">
                      <template slot="append"></template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :prop="'DetailList.'+ y +'.YearBonus'"
                  :rules="productGroupRules.YearBonus" label="年终奖金">
                  <el-input style="width: 100%;" type="Number" v-model="x.YearBonus"
                    @keyup.native="checkPrice(x,'YearBonus',true)">
                    <template slot="append"></template>
                  </el-input>
                </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :prop="'DetailList.'+ y +'.Rate'"
                    :rules="productGroupRules.Rate" label="提成比例(%)">
                    <el-input style="width: 100%;"  type="Number" v-model="x.Rate"
                      @keyup.native="checkPrice(x,'Rate',true)">
                      <!-- <template slot="append">%</template> -->
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div>
                <el-button style="margin-left: 15px;padding: 6px;" type="danger" size="mini"  class="el-icon-delete" circle
                v-if="addMsg.DetailList.length>1" @click="addMsg.DetailList.splice(y,1),selectdis()">
              </el-button>
              </div>
              <!-- <span v-if="x.CommissionType==1">人头金额:</span>
                            <span v-if="x.CommissionType==2">利润比例:</span>
                             -->

            </div>

          </div>
          <!-- v-if="TeamListArr.length>addMsg.DetailList.length || addMsg.RuleType==3" -->
          <el-button  size="mini" type="primary"
            class="el-icon-circle-plus-outline" circle @click="addDetailList"></el-button>
            
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="ruleVisible = false">取 消</el-button>
        <el-button size="small" type="danger" @click="RulesOk('addMsg')">确 定</el-button>
      </span>
    </el-dialog>



  </div>
</template>
<script>
  import Vue from "vue";
  const addobj = {
    Id: 0,
    RuleName: '',
    LineIds: '',
    LineshortIds: [],
    BranchId: '',
    RuleType: '1',
    CurrencyId:'',
    AuditEmpId: '',
    EmpIds: '',
    EmpIdList: '',
    ProfitRate: '',//业绩扣除比例
    DetailList: [{
      StartValue: '',
      EndValue: '',
      Rate: '',
      DiJieBonus: '',
      YearBonus: '',
    }]
  }
  export default {
    data() {
      var checkVariable = (rule, value, callback) => {
        if (value == null || value.length == 0) {
          return callback(new Error("提成比列不能为空"));
        }
        let a = parseFloat(value);
        if (isNaN(a)) {
          callback(new Error("提成比例必须是整数"));
        } else {
          callback();
        }
      };
      return {
        CurrentNmae: '',
        //所有币种
        allCurrencyList: [],
        companyList: [],
        getCompanyMsg: {
          RB_Group_Id: '0',
          Status: '0',
        },
        msg: {
          pageIndex: 1,
          pageSize: 10,
          RuleName: '',
          LineId: 0,
          BranchId: -1,
        },
        searchList:[],//人员
        loading: false, //加载层
        DataList: [],
        total: 0,
        TeamListArr: [
          {Name:'一日游',Id:1,disabled:false},
          {Name:'单项',Id:2,disabled:false},
          {Name:'出境',Id:3,disabled:false},
        ], //团队类型
        LineList: [], //线路
        ruleVisible: false, //弹窗的显示
        addMsg: Object.assign({}, addobj),
        rules: {
          RuleName: [{
            required: true,
            message: '请输入规则名称',
            trigger: 'blur'
          }],
          LineshortIds: [{
            type: 'array',
            required: true,
            message: '请选择路线',
            trigger: 'change'
          }],
          BranchId: [{
            required: true,
            message: '请选择公司',
            trigger: 'change'
          }],
          CurrencyId: [{
            required: true,
            message: '请选择币种',
            trigger: 'change'
          }],
          AuditEmpId: [{
            required: true,
            message: '请选择结团审核人',
            trigger: 'change'
          }],
          EmpIds: [{
            required: true,
            message: '请选择参与人',
            trigger: 'change'
          }],
          EmpIdList: [{
            required: true,
            message: '请选择参与人',
            trigger: 'change'
          }],
          ProfitRate: [{
            required: true,
            message: '请输入业绩扣除比例',
            trigger: 'blur'
          }]
        },
        productGroupRules2:{
          Id: [{
            required: true,
            message: '请选择人员',
            trigger: 'change'
          }],
        },
        productGroupRules: {
          StartValue: [{
            required: true,
            message: '请输入开始值',
            trigger: 'blur'
          }],
          EndValue: [{
            required: true,
            message: '请输入结束值',
            trigger: 'blur'
          }],
          Rate: [{
            required: true,
            message: '请输入提成比例',
            trigger: 'blur'
          }],
          DiJieBonus: [{
            required: true,
            message: '请输入地接奖金',
            trigger: 'blur'
          }],
          YearBonus: [{
            required: true,
            message: '请输入年终奖金',
            trigger: 'blur'
          }],
          TravelType: [{
            required: true,
            message: '请选择团队类型',
            trigger: 'change'
          }],
          Money: [{
            required: true,
            message: '不能为空',
            trigger: 'change'
          }],
          ProfitRate: [{
            required: true,
            message: '不能为空',
            trigger: 'change'
          }],
        },
        EmployeeList:[],
        employeeMsg:{ // 员工
              GroupId:'',
              BranchId:-1,
              DepartmentId:0,
              PostId:0,
              IsLeave:0,
          },
      };
    },
    created() {
      let userInfo = this.getLocalStorage();
      this.getCompanyMsg.RB_Group_Id = userInfo.RB_Group_id; //集团

      this.getList()
      this.getTeamList()
      this.getLineList()
      this.getCompany()
      this.getAllCurrency()
      this.getEmployee()
    },
    methods: {
      getEmployee() { //员工
        let userInfo=this.getLocalStorage();
        this.employeeMsg.GroupId = userInfo.RB_Group_id; 
        this.apipost('admin_get_EmployeeGetList', this.employeeMsg, res => {
            if(res.data.resultCode == 1) {
                this.EmployeeList = res.data.data;
            }
        }, err => {})
      },
      //获取当前下拉选中币种
    getCurrent(currencyId) {
      this.allCurrencyList.forEach(x => {
        if (x.ID == currencyId) {
          this.CurrentNmae = x.Name;
        }
      });
    },
      //获取所有币种
      getAllCurrency() {
        this.apipost(
          "financeinfo_post_GetList",
          {},
          res => {
            if (res.data.resultCode == 1) {
              this.allCurrencyList = res.data.data;
            }
          },
          err => { }
        );
      },
      //获取公司
      getCompany() {
        this.apipost('admin_get_BranchGetList', this.getCompanyMsg, res => {
          if (res.data.resultCode == 1) {
            this.companyList = res.data.data;
          } else {}
        }, err => {})
      },
      handleCurrentChange(val) {
        //翻页功能按钮
        this.msg.pageIndex = val;
        this.getList();
      },
      getList() {
        this.loading = true;
        this.apipost(
          "sellcommission_GetTWSellCommissionRuleList",
          this.msg,
          res => {
            this.loading = false;
            if (res.data.resultCode == 1) {
              this.DataList = res.data.data.pageData;
              this.total = res.data.data.count;
            }
          },
          err => {}
        );
      },
      selectdis(val, index) { //团队类型下拉了不能再次选择
        this.TeamListArr.forEach((x, y) => {
          let ishow = false;
          this.addMsg.DetailList.map((j, ji) => {
            if (ishow == false) {
              if (x.Id == j.Id) {
                x.disabled = true;
                ishow = true;
                return;
              } else {
                x.disabled = false;
              }
            }
          });
        });
      },
      gettdName(id, index) { //获取团队类型名称
        this.TeamListArr.map(x => {
          if (x.Id == id) {
            this.addMsg.DetailList[index].Name = x.Name;
            return false
          }
        })
      },
      //获取线路列表
      getLineList() {
        this.apipost(
          "line_post_GetAllList", {},
          res => {
            if (res.data.resultCode == 1) {
              this.LineList = res.data.data;
            }
          }
        );
      },
      getTeamList() { //获取团队类型的列表
        this.apipost("travel_get_GetTravelPriceTeamTypeList", {}, res => {
            if (res.data.resultCode == 1) {
              // this.TeamListArr = res.data.data;
              // this.TeamListArr.forEach(x => {
              //   x.disabled = false
              // })
            } else {
              this.Error(res.data.message);
            }
          },
          err => {}
        );
      },
      getEdit(row) { //修改规则
        let data = JSON.parse(JSON.stringify(row))
        this.addMsg = Object.assign({}, addobj)
        this.addMsg.Id = data.Id;
        this.addMsg.RuleName = data.RuleName;
        this.addMsg.LineIds =  data.LineIds
        this.addMsg.LineshortIds = data.LineIds.split(',').map(Number);
        this.addMsg.EmpIdList = data.EmpIds.split(',').map(Number);
        this.addMsg.DetailList = data.DetailList;
        this.addMsg.RuleType = data.RuleType.toString();
        this.addMsg.BranchId = data.BranchId
        this.addMsg.AuditEmpId = data.AuditEmpId
        this.addMsg.CurrencyId = data.CurrencyId
        this.addMsg.ProfitRate = data.ProfitRate
        this.CurrentNmae = data.CurrencyName
        this.remoteMethod(data.AuditEmpName)
        this.searchList=[]
        if(this.addMsg.RuleType!=3){
          this.isshowfeizhu()//检测是否有飞猪 如果有就不能选择第二个
        }        
        this.selectdis()
        this.ruleVisible = true;


      },
      DeleteRules(ID) { //删除规则
        this.$confirm("是否删除? ", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(() => {
            this.apipost('sellcommission_DelTWSellCommissionRule', {
              RuleId: ID
            }, res => {
              if (res.data.resultCode == 1) {
                this.Success(res.data.message)
                this.getList()
              } else {
                this.Error(res.data.message)
              }
            })
          })
          .catch(() => {});
      },
      addNew() { //新增
        this.addMsg = {
          Id: 0,
          RuleName: '',
          LineIds: '',
          LineshortIds: [],
          BranchId: '',
          RuleType: '1',
          CurrencyId:'',
          AuditEmpId: '',
          EmpIds: '',
          EmpIdList: '',
          ProfitRate: '',//业绩扣除比例
          DetailList: [{
            StartValue: '',
            EndValue: '',
            Rate: '',
            DiJieBonus: '',
            YearBonus: '',
          }]
        }
        this.selectdis()
        this.ruleVisible = true;
      },
      addDetailList() { //新增类型
        let isdisabled = false
        let isdisabledXHS = false
        let obj = {
          StartValue: '',
          EndValue: '',
          Rate: '',
          DiJieBonus: '',
          YearBonus: '',
        }
        this.addMsg.DetailList.push(obj)
      },
      RulesOk(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let LineshortIds = JSON.parse(JSON.stringify(this.addMsg.LineshortIds))
            this.addMsg.LineIds = LineshortIds.join(',')
            let EmpIds = JSON.parse(JSON.stringify(this.addMsg.EmpIdList))
            this.addMsg.EmpIds = EmpIds.join(',')
            this.apipost(
              'sellcommission_SetTWSellCommissionRule', this.addMsg,
              res => {
                if (res.data.resultCode == 1) {
                  this.getList();
                  this.ruleVisible = false;
                  this.Success(res.data.message)

                } else {
                  this.Error(res.data.message)
                }
              },
              err => {}
            )
          }
        });
      },
      isshowfeizhu(){
        let isfeizhu = false
        let isxiaohongshu = false
        for(let i = 0;i<this.addMsg.DetailList.length;i++){
          let x = this.addMsg.DetailList[i]
          if(x.SourceType==2){
            isfeizhu=true
          }
          if(x.SourceType==3){
            isxiaohongshu=true
          }
        }
        this.addMsg.DetailList.forEach(x=>{
          if(isfeizhu==true){
            if(x.SourceType==2){
              x.STdisabled = false;
              if(this.addMsg.RuleType!=3){
                x.Id=0;
                x.Name='飞猪'
              }
              
            }else{
              x.STdisabled = true
            }
          }else{
            x.STdisabled = false
          }
          if(isxiaohongshu==true){
            if(x.SourceType==3){
              x.STdisabledXHS = false;
              if(this.addMsg.RuleType!=3){
                x.Id=0;
                x.Name='小红书'
              }
              
            }else{
              x.STdisabledXHS = true
            }
          }else{
            x.STdisabledXHS = false
          }
        })
      },
      getSType(index){//选了飞猪之后 后面的不能选飞猪了
        if(this.addMsg.DetailList[index].SourceType==1 &&  this.addMsg.RuleType!=3){
          this.addMsg.DetailList[index].Id=''
          this.addMsg.DetailList[index].Name=''
        }
        if(this.addMsg.RuleType!=3){
          this.isshowfeizhu()//检测是否有飞猪 如果有就不能选择第二个
        }
        
        this.selectdis()
        this.$forceUpdate();
      },
      remoteMethod(query) {  //  转交人模糊查询
            if (query !== '') {
                this.apipost("admin_Get_Chat_All_SelectEmpName",{ EmName:query },res => {
                    if (res.data.resultCode == 1) {
                        this.searchList = res.data.data;
                    }
                },err => {});
            } else {
                this.searchList = [];
            }
        },
        getpersonnel(y){
          return
          for(let i = 0;i<this.searchList.length;i++){
            let x = this.searchList[i]
            if(x.empId  == this.addMsg.DetailList[y].Id){
              this.addMsg.DetailList[y].Name = x.name;
              break
            }
          }
        }

    },
    mounted() {

    }
  };

</script>
<style>
  /* .rule-box .el-select__tags{
    top: 100%;
  } */
  .domesticCommissionRule .query-box input {
    height: 34px !important;
  }

</style>