<template>
  <div class="rule-box">
    <div class="query-box">
      <ul>
        <li>
          <input type="button" class="normalBtn" :value="$t('pub.addBtn')" @click="addNew">
        </li>
      </ul>
    </div>
    <v-table
      v-if="isReady"
      is-horizontal-resize
      column-width-drag
      column-height-drag
      style="width:100%"
      :is-loading="loading"
      :columns="columns"
      :table-data="tableData"
      :filter-method="filterMethod"
      :total="total"
      :pageSize="pageSize"
      :pageIndex="pageIndex"
      :handleCurrentChange="handleCurrentChanges"
      :multiple-sort="multipleSort"
      sort-always
      @sort-change="sortChange"
      @on-custom-comp="customCompFunc"
    ></v-table>
    <!-- @on-custom-comp="customCompFunc" -->
    <div class="bottom-box" v-show="showForm" v-loading="formLoading">
      <div class="btm-title">{{addMsg.ID==0?$t('fnc.addguize'):$t('fnc.editguize')}}</div>
      <div>
        <el-form
          class="_info_box clearfix"
          :model="addMsg"
          ref="addMsg"
          label-width="110px"
          :rules="rules"
        >
          <el-row>
            <el-col :span="4" :gutter="20">
              <el-form-item :label="$t('fnc.accBming')" prop="RuleName">
                <el-input v-model="addMsg.RuleName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.tcleibie')">
                <el-select filterable v-model="addMsg.CommissionMethod" class>
                  <el-option :label="$t('fnc.jiaoyie')" :value="1"></el-option>
                  <!-- <el-option label="毛利" :value="2"></el-option> -->
                  <el-option :label="$t('fnc.retoushu')" :value="3"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.tcfangshi')">
                <el-select filterable v-model="addMsg.CommissionType" class>
                  <el-option :label="$t('fnc.gdbfenbi')" :value="1" v-if='addMsg.CommissionMethod==1'></el-option>
                  <el-option :label="$t('fnc.jtbfenbi')" :value="2" v-if='addMsg.CommissionMethod==1'></el-option>
                  <el-option :label="$t('fnc.gdjine')" :value="3" v-if='addMsg.CommissionMethod==3'></el-option>
                  <el-option :label="$t('fnc.jtjine')" :value="4" v-if='addMsg.CommissionMethod==3'></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.tcbili')" prop="CommissionVariable">
                <el-input
                  v-model="addMsg.CommissionVariable"
                  type="int"
                  :disabled="addMsg.CommissionType%2!=1"
                >
                  <template slot="append">{{addMsg.CommissionType==1?'%':'/人'}}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.tcyaoqiu')">
                <el-select v-model="addMsg.Require" class>
                  <el-option :label="$t('fnc.ysdingjin')" :value="1"></el-option>
                  <el-option :label="$t('fnc.wkshouqi')" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" :gutter="20">
              <el-form-item :label="$t('fnc.jszhouqi')">
                <el-select v-model="addMsg.BalanceCyc" class>
                  <el-option :label="$t('fnc.andjiesuan')" :value="1"></el-option>
                  <el-option :label="$t('fnc.anyjiesuan')" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.jsyaoqiu')">
                <el-select v-model="addMsg.IsFinishAll" class>
                  <el-option :label="$t('fnc.qzwcsyyq')" :value="1"></el-option>
                  <el-option :label="$t('fnc.bqzwancheng')" :value="0"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.shiyongongsi')" prop="UsingBranchArray">
                <el-select
                  multiple
                  collapse-tags
                  @change="changeData(1)"
                  v-model="addMsg.UsingBranchArray"
                  class
                >
                  <el-option :label="$t('fnc.jttongyong')" value="-1"></el-option>
                  <el-option
                    v-for="(item, index) in CompanyList"
                    :label="item.SName"
                    :value="item.SId"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.jttongyong')" prop="UsingLineArray">
                <el-select
                  multiple
                  collapse-tags
                  @change="changeData(2)"
                  v-model="addMsg.UsingLineArray"
                  class
                >
                  <el-option :label="$t('fnc.sydxianlu')" value="-1"></el-option>
                  <el-option
                    v-for="(item, index) in lines"
                    :label="item.lineName"
                    :value="item.lineID.toString()"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5" :gutter="20">
              <el-form-item :label="$t('fnc.symdidi')">
                <el-select
                  multiple
                  collapse-tags
                  @change="changeData(3)"
                  v-model="addMsg.UsingDestinationArray"
                >
                  <el-option :label="$t('fnc.symudidi')" value="-1"></el-option>
                  <el-option
                    v-for="(item, index) in desctions"
                    :label="item.PlaceName"
                    :value="item.PlaceID.toString()"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="4" :gutter="20">
              <el-form-item :label="$t('fnc.qyshijian')">
                <el-date-picker v-model="addMsg.EffectDate" type="date" :placeholder="$t('tips.xzqyshijian')"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <table class="al-tab" v-show="addMsg.CommissionType%2==0">
              <caption>{{$t('fnc.jttcblsd')}}</caption>
              <thead>
              <th>{{$t('active.ad_xuhao')}}</th>
              <th>{{$t('fnc.qzrenshu')}}</th>
              <th>{{$t('fnc.zzrenshu')}}</th>
              <th>{{$t('fnc.jcbili')}}</th>
              <th>{{$t('fnc.ewjiangli')}}</th>
              <th>{{$t('admin.admin_operate')}}</th>
              </thead>
              <tbody>
              <tr v-for="(item, index) in addMsg.RuleClassList" :key="index">
                <td>{{index+1}}</td>
                <td>
                  <el-input-number
                    size="small"
                    style="margin:0 12px"
                    :min="1"
                    :max="item.EndPeople"
                    v-model="item.StartPeople"
                    class="w120"
                  ></el-input-number>
                </td>
                <td>
                  <el-input-number
                    size="small"
                    style="margin:0 15px"
                    :min="item.StartPeople"
                    v-model="item.EndPeople"
                    class="w100"
                  ></el-input-number>
                </td>
                <td>
                  <el-input
                    :placeholder="$t('rule.qsrjcbili')"
                    size="small"
                    v-model="item.BaseVariable"
                    class="w200"
                  >
                    <template slot="append">{{addMsg.CommissionType==2?'%':'/'+$t('hotel.hotel_people')}}</template>
                  </el-input>
                </td>
                <td>
                  <el-input
                    :placeholder="$t('rule.qsrwmjiangli')"
                    size="small"
                    v-model="item.AddedVariable"
                    class="w200 temp"
                  >
                    <template slot="append">
                      <el-select v-model="item.AddedMethod" class>
                        <el-option :label="'/'+$t('hotel.hotel_people')" :value="2"></el-option>
                        <el-option label="%" :value="1"></el-option>
                      </el-select>
                    </template>
                  </el-input>
                </td>
                <td>
                  <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    circle
                    v-if="index==addMsg.RuleClassList.length-1"
                    @click="addCommissionType"
                  ></el-button>
                  <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    circle
                    @click="deleteCommissionType(index)"
                    v-if="addMsg.RuleClassList.length>1"
                  ></el-button>
                </td>
              </tr>
              </tbody>
            </table>
          </el-row>
        </el-form>
      </div>
      <div class="btm-opera-btn">
        <input type="button" class="normalBtn" :value="$t('pub.saveBtn')" @click="save">
        <input type="button" class="cancelBtn" :value="$t('pub.cancelBtn')" @click="changeShow(0)">
      </div>
    </div>
  </div>
</template>
<script>
  import Vue from "vue";
  import {
    getSchoolDropdown
  } from '../../api/school/index'
  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 {
        columns: [],
        remoteLoading: false,
        total: 0,
        tableData: [],
        isReady: false,
        multipleSort: false,
        loading: false,
        pageSize: 1000,
        pageIndex: 1,
        msg: {},
        CompanyList: [],
        addMsg: {},
        lines: [],
        rules: {
          RuleName: [
            { required: true, message: this.$t('rule.qsrgzmingcheng'), trigger: "blur" }
          ],
          UsingLineArray: [
            {
              type: "array",
              required: true,
              message: this.$t('rule.qzsxzytxianlu'),
              trigger: "blur"
            }
          ],
          UsingBranchArray: [
            {
              type: "array",
              required: true,
              message: this.$t('rule.qzsxzyggongsi'),
              trigger: "blur"
            }
          ],
          CommissionVariable: [{ validator: checkVariable, trigger: "blur" }]
        },
        showForm: false,
        formLoading: false,
        searchMsg: {
          RB_Group_Id: 0
        },
        desctionsResources:[],
        desctions:[],
        schoolMsg:{
          pageIndex: 1,
          pageSize: 12,
          rowsPerPage: 12,
          SName: "",
          Status: '-1'
        }
      };
    },
    methods: {
      customCompFunc(params) {
        if (params.type === "delete") {
          this.delete(params.data.ID);
          //this.financeinfoRemove(params.id,params.alias)
        } else if (params.type === "edit") {
          this.addNew(params.data);
        }
      },
      delete(id) {
        this.$confirm(this.$t('tips.cicaozuoyongjiushanchu'), this.$t('tips.shanchutishi'), {
          confirmButtonText: this.$t('pub.sureBtn'),
          cancelButtonText: this.$t('pub.cancelBtn'),
          type: "warning"
        })
          .then(() => {
            let msg = {
              id
            };
            this.apipost("sellcommission_rule_delete", msg, x => {
              if (x.data.resultCode == 1) {
                this.Success(this.$t('tips.shanchuchenggong'));
                this.getData()
              } else {
                this.Error(this.data.message);
              }
            });
          })
          .catch(() => {});
      },
      addNew(data) {
        if (!data.ID) {
          this.addMsg = {
            ID: 0,
            RuleName: "",
            CommissionMethod: 1,
            CommissionType: 1,
            Require: 1,
            CommissionVariable: 0,
            UsingLineArray: ["-1"],
            UsingBranchArray: ["-1"],
            UsingDestinationArray:["-1"],
            UsingLine: "",
            UsingBranch: "",
            UsingDestination: "",
            EffectDate: null,
            RB_Group_Id: this.searchMsg.RB_Group_Id,
            BalanceCyc: 1,
            IsFinishAll: 0,
            IsDelete: 1,
            RuleClassList: [
              {
                StartPeople: 1,
                EndPeople: 1,
                BaseVariable: 0,
                AddedVariable: 0,
                AddedMethod: 1
              }
            ]
          };
        } else {
          data.UsingLineArray = data.UsingLine.split(",");
          data.UsingBranchArray = data.UsingBranch.split(",");
          this.desctions=[]
          if(data.UsingLine!='-1'){
            this.desctionsResources.forEach(x=>{
              if(data.UsingLineArray.indexOf(x.LineID.toString())!=-1){
                this.desctions.push(x);
              }
            })
          }
          this.addMsg = data;
          this.addMsg.UsingDestinationArray = data.UsingDestination.split(",");
        }
        this.changeShow(1);
      },
      save() {
        //sellcommission_rule_set
        this.$refs["addMsg"].validate(valid => {
          if (valid) {
            this.formLoading = true;
            this.addMsg.UsingLine = this.addMsg.UsingLineArray.join(",");
            this.addMsg.UsingBranch = this.addMsg.UsingBranchArray.join(",");
            this.addMsg.UsingDestination = this.addMsg.UsingDestinationArray.join(",");
            this.apipost("sellcommission_rule_set", this.addMsg, x => {
              if (x.data.resultCode == 1) {
                this.changeShow(0);
                this.Success(this.$t('tips.baocunchenggong'));
                this.getData();
              } else {
                this.Error(x.data.message);
              }
              this.formLoading = false;
            });
          } else {
            return false;
          }
        });
      },
      changeShow(t) {
        this.showForm = t == 1;
      },
      deleteCommissionType(index) {
        this.addMsg.RuleClassList.splice(index, 1);
      },
      addCommissionType() {
        let obj = {
          StartPeople:
            this.addMsg.RuleClassList[this.addMsg.RuleClassList.length - 1]
              .EndPeople + 1,
          EndPeople:
            this.addMsg.RuleClassList[this.addMsg.RuleClassList.length - 1]
              .EndPeople + 1,
          Variable: 0,
          AddedVariable: 0,
          AddedMethod: "1"
        };
        this.addMsg.RuleClassList.push(obj);
      },
      initColums() {
        this.isReady = false;
        let that = this;
        let RuleName = {
          title: that.$t('fnc.gzmingcheng'),
          field: "RuleName",
          titleAlign: "left",
          columnAlign: "left",
          result: "",
          filterMultiple: false,
          width: 40,
          filters: [{}],
          isResize: true,
          type: "text",
          isFrozen: true
        };
        let companyList = [];
        this.CompanyList.forEach(x => {
          let item = {};
          item.label = x.BName;
          item.value = x.Id;
          companyList.push(item);
        });
        let BranchName = {
          field: "BranchName",
          title: that.$t('fnc.sygongsi'),
          width: 40,
          titleAlign: "left",
          columnAlign: "left",
          isResize: true,
          filterMultiple: true,
          filters: companyList,
          result: [],
          type: "select",
          isFrozen: true
        };
        let lines = [];
        this.lines.forEach(x => {
          let item = {};
          item.label = x.lineName;
          item.value = x.lineID;
          lines.push(item);
        });
        let LineName = {
          field: "LineName",
          title: that.$t('fnc.shiyongxianlu'),
          width: 80,
          titleAlign: "left",
          columnAlign: "left",
          isResize: true,
          result: [],
          filterMultiple: true,
          filters: lines,
          isFrozen: true,
          formatter: function(rowData, rowIndex, pagingIndex, field) {
            if (rowData.UsingLine == "-1") {
              return that.$t('fnc.sydxianlu');
            } else {
              let lineNames = "";
              rowData.UsingLine.split(",").forEach(x => {
                that.lines.forEach(y => {
                  if (y.lineID == x) {
                    lineNames += y.lineName + ",";
                  }
                });
              });
              return lineNames;
            }
          }
        };
        let Rules = {
          title: that.$t('fnc.tcguize'),
          field: "RuleDescription",
          titleAlign: "left",
          columnAlign: "left",
          width: 300
          // orderBy: "desc"
        };
        let EffectDate = {
          field: "EffectDate",
          title: that.$t('active.cl_sxriqi'),
          titleAlign: "left",
          columnAlign: "left",
          isResize: true,
          width: 80,
          formatter: function(rowData, rowIndex, pagingIndex, field) {
            return rowData.EffectDate.split("T")[0];
          }
        };
        let CommissionLog = {
          title: that.$t('fnc.tcjilu'),
          titleAlign: "left",
          columnAlign: "left",
          isResize: true,
          width: 80
          // orderBy: "",
          // formatter: function(rowData, rowIndex, pagingIndex, field) {
          //   return rowData.Royalty.toFixed(2);
          // }
        };
        let Cyc = {
          title: that.$t('fnc.tczhouqi'),
          titleAlign: "left",
          columnAlign: "left",
          isResize: true,
          width: 80,
          formatter: function(rowData, rowIndex, pagingIndex, field) {
            let cyc = "";
            let dyjiesuan = that.$t('fnc.dyjiesuan')
            let ayjiesuan = that.$t('fnc.ayjiesuan')
            let dwala = that.$t('dwala')
            let awala = that.$t('awala')
            if (rowData.BalanceCyc == "1") {
              cyc = dyjiesuan+"（";
            } else {
              cyc = ayjiesuan+"（";
            }
            if (rowData.IsFinishAll == "1") {
              cyc += dwala +"）";
            } else {
              cyc += awala +"）";
            }
            return cyc;
          }
        };
        let opera = {
          title: that.$t('system.table_operation'),
          titleAlign: "left",
          columnAlign: "left",
          width: 80,
          isResize: false,
          componentName: "table-operation"
        };
        this.columns = [];
        this.columns.push(RuleName);
        this.columns.push(BranchName);
        this.columns.push(LineName);
        this.columns.push(Rules);
        this.columns.push(EffectDate);
        this.columns.push(CommissionLog);
        this.columns.push(Cyc);
        this.columns.push(opera);
        this.isReady = true;
      },
      changeData(type) {
        let temp = [];
        if (type == 1) {
          temp = this.addMsg.UsingBranchArray;
        } else if (type == 2) {
          temp = this.addMsg.UsingLineArray;
        } else if (type == 3) {
          temp = this.addMsg.UsingDestinationArray;
        }
        let len = temp.length;
        if (len > 1) {
          if (temp[len - 1] == -1) {
            temp.splice(0, len - 1);
          } else if (temp.indexOf("-1") != -1) {
            temp.splice(temp.indexOf("-1"), 1);
          }
        }

        if(type==2 || type==3){
          this.desctions=[]
          if(type==2)
            this.addMsg.UsingDestinationArray=['-1']
          this.desctionsResources.forEach(x=>{
            if(this.addMsg.UsingLineArray.indexOf(x.LineID.toString())!=-1){
              this.desctions.push(x);
            }
          })
        }
      },
      handleCurrentChanges(val) {
        this.pageIndex = val;
        this.getList();
      },
      sortChange(param) {
        if (param.Royalty != "") {
          this.msg.OrderBy = `Royalty ${param.Royalty}`;
        } else if (param.Initialbalance != "") {
          this.msg.OrderBy = `Initialbalance ${param.Initialbalance}`;
        }
        this.getList();
      },
      filterMethod(filters) {
        this.searchMsg.RuleName = filters.RuleName;
        this.searchMsg.UsingBranchArray = filters.BranchName;
        this.searchMsg.UsingLineArray = filters.LineName;
        this.getData();
      },
      getCompanyList() {
        //获取公司列表
        getSchoolDropdown({}).then(res => {
          this.CompanyList = res.Data;
        }).catch(() => {

        })
      },
      getline() {
        let msg = { pageIndex: 0, pageSize: 100 };
        this.apipost(
          "line_post_GetPageList",
          msg,
          x => {
            this.lines = x.data.data.pageData;
            this.initColums();
            this.getData();
          },
          err => {}
        );
      },
      getData() {
        this.loading = true;
        this.apipost("sellcommission_rule_get", this.searchMsg, x => {
          this.tableData = x.data.data;
          this.loading = false;
        });
      },
      getDesction(){
        this.apipost(
          "place_post_GetPageList",
          {
            LineID:0,
            PlaceName:'',
            pageIndex:1,
            pageSize:5000
          },
          res => {
            if (res.data.resultCode == 1) {
              res.data.data.pageData.forEach(x=>{
                if(x.IsShow==1)
                  this.desctionsResources.push(x)
              })
            }
          },
          err => {}
        );
      }
    },
    mounted() {
      this.searchMsg.RB_Group_Id = this.addMsg.RB_Group_Id = this.getLocalStorage().RB_Group_id;
      this.getCompanyList();
      this.getDesction();
      Vue.component("table-operation", {
        template: `<div style='width:80px;height:40px;background:#fff;text-align:center;position: relative;left:-5px;padding-top: 6px;padding-top:6px;'><el-button type="primary" size='mini' icon="el-icon-edit" circle @click="update(rowData,index)"></el-button><el-button type="danger" size='mini' icon="el-icon-delete" circle @click="deleteRow(rowData,index)"></el-button></div>`,
        props: {
          rowData: {
            type: Object
          },
          field: {
            type: String
          },
          index: {
            type: Number
          }
        },
        methods: {
          update() {
            let params = { type: "edit", data: this.rowData };
            this.$emit("on-custom-comp", params);
          },
          deleteRow() {
            let params = { type: "delete", data: this.rowData };
            this.$emit("on-custom-comp", params);
          }
        }
      });
    }
  };
</script>
<style>
  @import "./css/cssReset.css";

  /* .rule-box .el-select__tags{
    top: 100%;
  } */
  .rule-box .el-input .el-input__inner,
  .rule-box .el-select .el-input {
    height: auto;
  }
  .rule-box .el-select {
    display: block;
  }
  .el-input-group__append,
  .el-input-group__prepend {
    border-radius: 0;
  }
  .rule-box .el-date-editor.el-input,
  .rule-box .el-date-editor.el-input__inner {
    width: 100%;
  }
  .rule-box .temp .el-input-group__append {
    width: 70px;
  }
  .rule-box .temp .el-select {
    background: #409eff;
    color: #fff;
  }
  .rule-box .temp .el-select .el-input .el-select__caret {
    color: #f1f1f1;
  }
  .rule-box .el-button.is-circle{padding: 5px !important;}
</style>
