<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>{{$t('advmanager.v_line')}}</em>
            <el-select v-model="msg.LineId" size="mini" @change="handleCurrentChange(1)">
              <el-option :label="$t('pub.pleaseSel')" :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="$t('pub.addBtn')" @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>{{$t('advmanager.v_line')}}</th>
            <th>类型</th>
            <th>来源 </th>
            <th>团队类型名称 </th>
            <th>类型</th>
            <th>金额/比例</th>
            <th>修改人</th>
            <th>修改时间</th>
            <th>{{$t('system.table_operation')}}</th>
          </tr>
        </thead>
        <template v-for="(subItem,subIndex) in DataList">
          <tr v-for="(childItem,childIndex) in subItem.TempTypeList">
            <td v-if="childIndex==0" :rowspan="subItem.TempTypeList.length">{{subItem.RuleName}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.TempTypeList.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.TempTypeList.length">
              <span v-if="subItem.Type==1">销售</span>
              <span v-if="subItem.Type==2">OP</span>
              <span v-if="subItem.Type==3">自定义人员</span>
            </td>
            <td >
              <span v-if="childItem.SourceType==1">正常</span>
              <span v-if="childItem.SourceType==2">飞猪</span>
              <span v-if="childItem.SourceType==3">小红书</span>
            </td>
            <td>{{childItem.Name}}</td>
            <td>
              <span v-if="childItem.Type == 1">人头</span>
              <span v-if="childItem.Type == 2">利润比例</span>
            </td>
            <td>
              <span v-if="childItem.Type == 1">{{childItem.Money}}元/人</span>
              <span v-if="childItem.Type == 2">
                <div>利润比{{childItem.ProfitRate}}%</div>
                <div>利润<=0时 {{childItem.Money}}元/人 </div> </span> </td> <td v-if="childIndex==0"
                    :rowspan="subItem.TempTypeList.length">{{subItem.UpdateBy}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.TempTypeList.length">{{subItem.UpdateDate}}</td>
            <td v-if="childIndex==0" :rowspan="subItem.TempTypeList.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="10" align="center">{{$t('system.content_noData')}}</td>
        </tr>
        <tfoot>
          <tr>
            <td colspan="10">
              <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 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-form-item :label="$t('system.query_type')">
          <el-radio v-model="addMsg.Type" label="1">销售</el-radio>
          <el-radio v-model="addMsg.Type" label="2" style="margin-right: 20px;">OP</el-radio>
          <el-radio v-model="addMsg.Type" label="3" style="margin-right: 20px;">自定义人员</el-radio>
          <span style="font-size: 12px;color:red">(*注:自定义人员将会跟随 OP规则设置的团队类型匹配)</span>
        </el-form-item>

        <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.TempTypeList" :key='y'>
            <div style="display: flex;align-items: center;margin-top: 10px;">
              <el-form-item label="来源">
                <el-radio v-model="x.SourceType" label="1" @change='getSType(y)'>正常</el-radio>
                <el-radio v-model="x.SourceType" label="2" :disabled="x.STdisabled" style="margin-right: 20px;" @change='getSType(y)'>飞猪</el-radio>
                <el-radio v-model="x.SourceType" label="3" :disabled="x.STdisabledXHS" style="margin-right: 20px;" @change='getSType(y)'>小红书</el-radio>
              </el-form-item>
              <el-button style="margin-left: 15px;padding: 6px;" type="danger" size="mini"  class="el-icon-delete" circle
                v-if="addMsg.TempTypeList.length>1" @click="addMsg.TempTypeList.splice(y,1),selectdis()">
              </el-button>
            </div>
            <div style="display: flex;align-items: center;">
              <!-- <span style="line-height: 34px;">团队类型:</span> -->

              <el-form-item v-if='x.SourceType==1 && addMsg.Type!=3' :prop="'TempTypeList.'+ y +'.Id'" :rules="productGroupRules.Id" label="团队类型">
                <el-select v-model="x.Id" style="width: 300px;" @change="selectdis($event, y),gettdName(x.Id,y)"
                  clearable>
                  <el-option v-for="item in TeamListArr" :key="item.Id" :label="item.Name" :disabled="item.disabled"
                    :value="item.Id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="人员选择:" v-if=" addMsg.Type==3" :prop="'TempTypeList.'+ y +'.Id'" :rules="productGroupRules2.Id">
                <el-select
                    v-model="x.Id"
                    filterable
                    remote
                    reserve-keyword
                    :placeholder="$t('pub.pleaseImport')"
                    :remote-method="remoteMethod"
                    @change="getpersonnel(y)"
                    >
                    <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>



            </div>

            <div style="display: flex;align-items: center;margin-top: 10px;">
              <!-- <span>类型:</span> -->
              <el-form-item :label="$t('system.query_type')">
                <el-radio v-model="x.Type" label="1">人头</el-radio>
                <el-radio v-model="x.Type" label="2" style="margin-right: 20px;">利润比列</el-radio>
              </el-form-item>



            </div>
            <div style="display: flex;align-items: center;margin-top: 10px;">
              <el-form-item v-if="x.Type==1" :prop="'TempTypeList.'+ y +'.Money'" :rules="productGroupRules.Money"
                label="人头金额">
                <el-input style="width: 200px;" type="Number" v-model="x.Money"
                  @keyup.native="checkPrice(x,'Money',true)"><template slot="append">元/人</template>
                </el-input>
              </el-form-item>
              <el-form-item v-if="x.Type==2" :prop="'TempTypeList.'+ y +'.ProfitRate'"
                :rules="productGroupRules.ProfitRate" label="利润比例">
                <el-input style="width: 170px;" type="Number" v-model="x.ProfitRate"
                  @keyup.native="checkPrice(x,'ProfitRate',true)">
                  <template slot="append">%</template>
                </el-input>
                <!-- <span style="margin-left: 15px;" >利润小于等于0:</span>
                                -->
              </el-form-item>
              <el-form-item v-if="x.Type==2" :prop="'TempTypeList.'+ y +'.Money'" :rules="productGroupRules.Money"
                label="利润<=0时">
                <el-input style="width: 170px;" type="Number" v-model="x.Money"
                  @keyup.native="checkPrice(x,'Money',true)"><template slot="append">元/人</template>
                </el-input>
              </el-form-item>
              <!-- <span v-if="x.Type==1">人头金额:</span>
                            <span v-if="x.Type==2">利润比例:</span>
                             -->

            </div>

          </div>
          <el-button v-if="TeamListArr.length>addMsg.TempTypeList.length || addMsg.Type==3" size="mini" type="primary"
            class="el-icon-circle-plus-outline" circle @click="addTempTypeList"></el-button>

        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="ruleVisible = false">{{$t('pub.cancelBtn')}}</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: [],
    Type:'1',
    TempTypeList: [{
      Id: '',
      Name: '',
      Type: '1',
      Money: '0',
      ProfitRate: '0',
      SourceType:'1',
      STdisabled:false,
      STdisabledXHS:false
    }]
  }
  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 {
        msg: {
          pageIndex: 1,
          pageSize: 10,
          RuleName: '',
          LineId: 0,
        },
        searchList:[],//人员
        loading: false, //加载层
        DataList: [],
        total: 0,
        TeamListArr: [], //团队类型
        LineList: [], //线路
        ruleVisible: false, //弹窗的显示
        addMsg: Object.assign({}, addobj),
        rules: {
          RuleName: [{
            required: true,
            message: '请输入规则名称',
            trigger: 'change'
          }],
          LineshortIds: [{

            type: 'array',
            required: true,
            message: '请选择路线',
            trigger: 'change'
          }],


        },
        productGroupRules2:{
          Id: [{
            required: true,
            message: '请选择人员',
            trigger: 'change'
          }],
        },
        productGroupRules: {
          Id: [{
            required: true,
            message: '请选择团队类型',
            trigger: 'change'
          }],

          Money: [{
            required: true,
            message: '不能为空',
            trigger: 'change'
          }],
          ProfitRate: [{
            required: true,
            message: '不能为空',
            trigger: 'change'
          }],
        }
      };
    },
    created() {
      this.getList()
      this.getTeamList()
      this.getLineList()
    },
    methods: {
      handleCurrentChange(val) {
        //翻页功能按钮
        this.msg.pageIndex = val;
        this.getList();
      },
      getList() {
        this.loading = true;
        this.apipost(
          "sellcommission_GetGNCommissionRuleList",
          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.TempTypeList.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.TempTypeList[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.TempTypeList = data.TempTypeList;
        this.addMsg.Type = data.Type.toString();
        this.searchList=[]
        this.addMsg.TempTypeList.forEach(x => {
          x.Type = x.Type.toString()
          x.SourceType = x.SourceType.toString()
          if(this.addMsg.Type==3){
            this.searchList.push({empId:x.Id,name:x.Name,postName:''})
          }
        })
        if(this.addMsg.Type!=3){
          this.isshowfeizhu()//检测是否有飞猪 如果有就不能选择第二个
        }
        this.selectdis()
        this.ruleVisible = true;


      },
      DeleteRules(ID) { //删除规则
        this.$confirm("是否删除? ", this.$t('tips.tips'), {
            confirmButtonText: this.$t('pub.sureBtn'),
            cancelButtonText: this.$t('pub.cancelBtn'),
            type: "warning"
          })
          .then(() => {
            this.apipost('sellcommission_DelGNCommissionRule', {
              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: [],
          Type:'1',
          TempTypeList: [{
            Id: '',
            Name: '',
            Type: '1',
            Money: '0',
            ProfitRate: '0',
            SourceType:'1',
            STdisabled:false,
            STdisabledXHS:false,
          }]
        }
        this.selectdis()
        this.ruleVisible = true;
      },
      addTempTypeList() { //新增类型
        let isdisabled = false
        let isdisabledXHS = false
        for(let i = 0;i<this.addMsg.TempTypeList.length;i++){
          let x = this.addMsg.TempTypeList[i]
          if(this.addMsg.Type!=3){
            if(x.SourceType==2||x.SourceType==3){
              if(x.SourceType==2) isdisabled=true
              if(x.SourceType==3) isdisabledXHS=true
              break
            }
          }
        }
        let obj = {
          Id: '',
          Name: '',
          Type: '1',
          Money: "0",
          ProfitRate: "0",
          SourceType:'1',
          STdisabled:isdisabled,
          STdisabledXHS:isdisabledXHS,
        }
        this.addMsg.TempTypeList.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(',')
            this.apipost(
              'sellcommission_SetGNCommissionRule', 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.TempTypeList.length;i++){
          let x = this.addMsg.TempTypeList[i]
          if(x.SourceType==2){
            isfeizhu=true
          }
          if(x.SourceType==3){
            isxiaohongshu=true
          }
        }
        this.addMsg.TempTypeList.forEach(x=>{
          if(isfeizhu==true){
            if(x.SourceType==2){
              x.STdisabled = false;
              if(this.addMsg.Type!=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.Type!=3){
                x.Id=0;
                x.Name='小红书'
              }

            }else{
              x.STdisabledXHS = true
            }
          }else{
            x.STdisabledXHS = false
          }
        })
      },
      getSType(index){//选了飞猪之后 后面的不能选飞猪了
        if(this.addMsg.TempTypeList[index].SourceType==1 &&  this.addMsg.Type!=3){
          this.addMsg.TempTypeList[index].Id=''
          this.addMsg.TempTypeList[index].Name=''
        }
        if(this.addMsg.Type!=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){
          for(let i = 0;i<this.searchList.length;i++){
            let x = this.searchList[i]
            if(x.empId  == this.addMsg.TempTypeList[y].Id){
              this.addMsg.TempTypeList[y].Name = x.name;
              break
            }
          }
        }

    },
    mounted() {

    }
  };

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

</style>