<template>
  <div class="classHourReward page-body">
    <div class="page-search row items-center">
      <div class="col row wrap q-mr-lg q-col-gutter-md">
        <div class="col-3">
          <q-select @input="resetSearch" standout="bg-primary text-white" option-value="TId" option-label="TeacherName"
            v-model="msg.TeacherId" :options="TeacherList" emit-value map-options label="带班老师" />
        </div>
        <div class="col-3">
          <q-select @input="resetSearch" standout="bg-primary text-white" option-value="Id" option-label="Name"
            v-model="msg.State" :options="StateList" emit-value map-options label="状态" />
        </div>
        <div class="col-3 Sysuser_Date">
          <q-field filled>
             <template v-slot:control>
              <el-date-picker v-model="msg.Month" @change="resetSearch" type="month" clearable @clear="resetSearch">
              </el-date-picker>       
            </template>
          </q-field>
        </div>
      </div>
    </div>
    <div class="page-content">
      <q-table :pagination="msg" :loading="loading" no-data-label="暂无相关数据" flat class="sticky-column-table"
        separator="none" title="" :data="data" :columns="columns" row-key="name">
        <template v-slot:top="props">
          <div class="col-2 q-table__title">教师课时奖励</div>
          <q-space />
          <q-btn color="accent" style="float:right;margin-right:0;" size="sm" class="q-mr-md" icon="add"
                 label="新增课时奖励" @click="drawer=true"></q-btn>
        </template>
        <template v-slot:body-cell-State="props">
          <q-td :props="props">
            <div class="state-item" v-if="props.row.State==1" style="background: rgba(255, 204, 0, 0.2);color: #EDBE00">
              {{props.row.StateName}}
            </div>
            <div class="state-item" v-if="props.row.State==2" style="background: rgba(2, 196, 153, 0.2);color: #02C499">
              {{props.row.StateName}}
            </div>
            <div class="state-item" v-if="props.row.State==3" style="background: rgba(247, 46, 82, 0.2);color: #F72E52">
              {{props.row.StateName}}
            </div>
            <div class="state-item" v-if="props.row.State==4" style="background: rgba(41, 97, 254, 0.2);color: #2961FE">
              {{props.row.StateName}}
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-TeacherList="props">
          <q-td :props="props">
            <span style="color: #3FC4FF;cursor: pointer"
              v-if="props.row.TeacherList.length>0&&props.row.TeacherList[0].TeacherName">{{props.row.TeacherList[0].TeacherName}}{{props.row.TeacherList.length>1?('等'+props.row.TeacherList.length+'位老师'):''}}
              <q-popup-proxy>
                <q-banner>
                  <div class="price-popup">
                    <div class="row " v-for="(x,index2) in props.row.TeacherList" :key="index2"
                      style="width: 200px;justify-content: space-between;align-items: center;margin: 7px 0;cursor: pointer">
                      <div class="row" @click="goDetailed(props.row,x.TeacherId)">
                        <span style="color:#2D2D2D;">{{x.TeacherName}}</span>
                      </div>
                      <span style="color: #2860FB">{{x.Money.toFixed(2)}}</span>
                    </div>
                  </div>
                </q-banner>
              </q-popup-proxy>
            </span>
          </q-td>
        </template>
        <template v-slot:body-cell-Money="props">
          <q-td :props="props">
            <span style="color:var(--q-color-negative)">￥{{props.row.Money.toFixed(2)}}</span>
          </q-td>
        </template>
        <template v-slot:body-cell-FrIdList="props">
          <q-td :props="props">
            <div class="row wrap" style="width: 100%;">
              <div class="frIdlist row" v-for="(x,j) in props.row.FrIdList" :key="j" @click="goUrl('FinancialDocumentsDetail',x)">
                <span style="font-size: 14px;color: #111111">{{x}}</span>
              </div>
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-optioned="props">
          <q-td :props="props">
            <q-btn-dropdown flat size="xs" color="dark" label="更多" style="margin-left:10px;" v-if="props.row.State!= 3"
            >
              <q-list>
                <q-item clickable v-close-popup v-if="props.row.State==1">
                  <q-item-section @click="gostudent(props.row,1)">
                    <q-item-label>确认</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup v-if="(props.row.State==2) && props.row.Money>0">
                  <q-item-section @click="generalFinancacls(props.row)">
                    <q-item-label>制单</q-item-label>
                  </q-item-section>
                </q-item>
                <q-item clickable v-close-popup
                  v-if="(props.row.State==1 || props.row.State==2)  && props.row.FrIdList==0">
                  <q-item-section @click="gostudent(props.row,2)">
                    <q-item-label>取消</q-item-label>
                  </q-item-section>
                </q-item>
                <!-- <q-item clickable v-close-popup v-if="props.row.State==2 && props.row.FrIdList==0 && props.row.Money>0">
                  <q-item-section @click="systemShan(props.row)">
                    <q-item-label>制单</q-item-label>
                  </q-item-section>
                </q-item> -->
             
              </q-list>
            </q-btn-dropdown>
            <q-btn flat size="xs" icon="iconfont icon-xiangqing-" style="font-weight:400;color: #3FC4FF" class="q-mr-xs"
                   label="明细" @click="goDetailed(props.row,'0')" />
          </q-td>
        </template>
        <template v-slot:bottom>
          <q-pagination class="full-width justify-end" v-model="msg.pageIndex" color="primary" :max="pageCount"
            :input="true" @input="changePage" />
        </template>
      </q-table>
    </div>
    <!--    一键制单-->
    <q-dialog v-model="ISsystem" persistent>
      <q-card style="width: 400px;max-width:500px;">
        <q-card-section>
          <div class="text-h6">一键制单</div>
        </q-card-section>
        <q-card-section class="q-pt-none scroll" style="max-height: 70vh">
          <div class="col">
            <q-radio v-model="FinanceMsg.IsPublic" val="0" label="私账" />
            <q-radio v-model="FinanceMsg.IsPublic" val="1" label="公账" />
          </div>
          <div class="col" style="margin-top: 20px">
            <q-select standout="bg-primary text-white" option-value="ID" option-label="Name"
              v-model="FinanceMsg.CurrencyId" :options="coinGetList" emit-value map-options label="币种" />
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white">
          <q-btn label="取消" flat color="grey-10" style="font-weight:400 !important"
            @click="ISsystem=false,Resetsystem()" v-if="!Floading" />
          <q-btn label="立即制单" color="accent" class="q-px-md" style="font-weight:400 !important" :loading="Floading"
            @click="savesystem()" />
        </q-card-actions>
      </q-card>
    </q-dialog>
    <el-drawer title="" :visible.sync="drawer"  :with-header="false" >
      <div style="padding: 15px" class="class-popover">
        <div style="font-size: 18px;font-weight: bold;color:#2D2D2D;font-family: 'perfectFont'">新增课时奖励</div>
        <q-select class="col-12 q-pb-lg q-pr-lg" multiple clearable filled stack-label use-input use-chips
          option-value="TId" option-label="TeacherName" v-model="tempManager" ref="ManagerId" :rules="[val => !!val || '请选择课时奖励']" :options="TeacherList"
          label="选择老师" :dense="false" emit-value map-options @filter="filterFn">
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey">
                未找到相关数据
              </q-item-section>
            </q-item>
          </template>
        </q-select>
        <div class="col-12">
          <div class="col-12 Sysuser_Date">
            <q-field filled>
                <template v-slot:control>
                <el-date-picker v-model="addMsg.Month"   type="month" style="border:none;" format='yyyy-MM'
                  :picker-options="pickerOptions"></el-date-picker>       
              </template>
            </q-field>
          </div>
        </div>
        <div class="row col" style="margin-top: 30px">
          <q-btn class="q-mr-md" size="sm" label="取消" @click="drawer=false" />
          <q-btn color="accent" size="sm" class="q-mr-md" label="保存" @click="saveOrderInfo()" :loading="Dloading" />
        </div>
      </div>
<!--      TODO 没显示出来-->
      <div class="dialog-out-close" @click="drawer=false"
           style="height:40px !important;border-top-left-radius: 4px !important;border-bottom-left-radius: 4px !important;">
        <q-icon name="iconfont icon-jujue1" size="26px" />
      </div>
    </el-drawer>

    <q-dialog v-model="costmode"  persistent transition-show="scale" transition-hide="scale">
      <q-card style="width: 700px;max-width:700px;">
        <q-card-section>
          <div class="text-h6">设置发放老师</div>
        </q-card-section>
        <q-card-section class="q-pt-none scroll"  >
          <el-table
            :data="SendEmployeeList"
            border
            max-height='384px'
            @selection-change="handleSelectionChange"
            style="width: 100%;">
            <el-table-column type="selection"  width="55" :selectable="checkSelectable"></el-table-column>
            <el-table-column  prop="TeacherName" label="老师" > </el-table-column>
            <el-table-column  prop="Money" label="应发提成金额" > </el-table-column>
            <el-table-column  prop="IsGiveOut" label="是否已发放" > 
              <template slot-scope="scope">
                <span v-if='scope.row.IsGiveOut==1'>已发放</span>
                <span v-if='scope.row.IsGiveOut==2'>未发放</span>
              </template>
            </el-table-column>
            
          </el-table>
          <div style="margin-top: 10px;">金额总额:{{totalAmount}}</div>
          <div slot="footer" class="dialog-footer">
            <el-button class="hollowFixedBtn" @click="costmode=false">取消</el-button>
            <el-button class="normalBtn" type="primary" @click="preservetransaction()">确定</el-button>
          </div>
          <q-separator />
          <q-card-actions align="right" class="bg-white">
            <q-btn label="取消" flat color="grey-10" style="font-weight:400 !important" @click="costmode=false" />
            <q-btn label="确定" color="accent q-px-md" style="font-weight:400 !important" :loading="saveLoading"
            @click="preservetransaction()" />
          </q-card-actions>
        </q-card-section>
       
      </q-card>
      
    </q-dialog>
  </div>
</template>

<script>
  import {
    getTeachingBonusPageList,
    getBonusStateEnumList, //教师奖励状态 枚举
    setTeachingBonusAdd, //新增课时奖励
    setTeachingBonusState, //教师绩效 设置状态
    setTeachingBonusFinance, //教师奖励 生成财务单据
    getTeachingRewardsSendEmployeeList,//获取课时费老师列表
    setTeachingRewardsSendEmployee,//设置  老师已发放   
  } from '../../api/course/class'
  import {
    getTeacherDropDownList,
  } from '../../api/school/index';
  export default {
    meta: {
      title: "教师课时奖励"
    },
    name: "classHourReward",
    data() {
      return {
        loading: false,
        ISsystem: false,
        Floading: false,
        Dloading: false,
        drawer: false,
        data: [],
        pageCount: 0,
        msg: {
          pageIndex: 1,
          pageSize: 10,
          rowsPerPage: 10,
          Month: '',
          TeacherId: 0,
          State: 0,
        },
        //公告column
        columns: [{
            name: 'State',
            label: '状态',
            align: 'left'
          },
          {
            name: 'Month',
            field: 'Month',
            label: '月份',
            align: 'left',
          },
          {
            name: 'TeacherList',
            label: '关联老师',
            align: 'left'
          },
          {
            name: 'Money',
            label: '发放总金额',
            align: 'left'
          },
          {
            name: 'UpdateTime',
            label: '生成时间',
            field: 'UpdateTime',
            align: 'left'
          },
          {
            name: 'FrIdList',
            label: '财务单据',
            align: 'left'
          },
          {
            name: 'UpdateByName',
            label: '操作人',
            align: 'left',
            field: 'UpdateByName'
          }, {
            name: 'optioned',
            label: '操作',
            field: 'DeptId'
          }
        ],
        TeacherList: [], //关联教师下拉数据
        AllTeacherList: [], //保存值
        StateList: [], //状态下拉
        tempManager: [],
        visible: false,
        addMsg: { //新增课时奖励
          Month: '',
          TeacherIds: '',
        },
        coinGetList: [], //币种数组
        FinanceMsg: { //生成财务单据的参数
          BonusId: 0,
          IsPublic: '0',
          CurrencyId: '',
        },
        pickerOptions: {
          disabledDate(time) {
            let nowdate = new Date();
            let upperMonth = nowdate.setMonth(nowdate.getMonth()-1)//小于本月
            return time.getTime() > upperMonth;
          },
        },
        CheckID:0,
        SendEmployeeList:[],
        costmode:false,
        totalAmount:0,
        saveLoading:false,
        multipleSelection:[]
      }
    },
    created() {
      this.getList();
      this.GetTeacherList()
      this.GetBonusStateList()
      this.financeinfo_post_GetList()
      let nowdate = new Date();
      let upperMonth = new Date(nowdate.setMonth(nowdate.getMonth()-1))//小于本月
      this.addMsg.Month = upperMonth.getFullYear()+'-'+(upperMonth.getMonth()+1)
    },
    methods: {

      financeinfo_post_GetList() { // 获取币种
        this.apipost('financeinfo_post_GetList', {
          Name: '',
          TCID: 0
        }, res => {
          if (res.data.resultCode == 1) {
            this.coinGetList = res.data.data;
            this.FinanceMsg.CurrencyId = this.coinGetList[0].ID
          }
        }, err => {})
      },
      resetSearch() {
        this.msg.pageIndex = 1;
        this.getList()
      },
      //翻页
      changePage(val) {
        this.msg.pageIndex = val;
        this.getList()
      },
      getList() {

        this.loading = true;
        getTeachingBonusPageList(this.msg).then(res => {
          this.loading = false
          this.data = res.Data.PageData
          this.pageCount = res.Data.PageCount;

        }).catch(() => {
          this.loading = false
        })
      },
      //获取教师下拉
      GetTeacherList() {
        getTeacherDropDownList({}).then(res => {
          if (res.Code == 1) {
            this.TeacherList = res.Data;
            this.TeacherList.unshift({
              TId: 0,
              TeacherName: "全部老师"
            })
            this.AllTeacherList = this.TeacherList
          }
        })
      },
      GetBonusStateList() {
        getBonusStateEnumList({}).then(res => {
          if (res.Code == 1) {
            this.StateList = res.Data;
            this.StateList.unshift({
              Id: 0,
              Name: "不限"
            })
          }
        })
      },
      //筛选员工
      filterFn(val, update) {
        update(() => {
          if (val === '') {
            this.TeacherList = JSON.parse(JSON.stringify(this.AllTeacherList))
          } else {
            const needle = val.toLowerCase()
            this.TeacherList = this.AllTeacherList.filter(v => v.TeacherName.toLowerCase().indexOf(needle) > -1)
          }
        })
      },
      saveOrderInfo() {

        if (this.tempManager && this.tempManager.length > 0) {
          let all = false
          this.tempManager.forEach(x => {
            if (x == 0) {
              all = true
            }
          })
          if (all == true) { //如果选了全部 就不所有老师带过去
            let data = []
            this.AllTeacherList.forEach(x => {
              if (x.TId != 0) {
                data.push(x.TId)
              }
            })
            this.addMsg.TeacherIds = data.join(',')
          } else {
            this.addMsg.TeacherIds = this.tempManager.join(',')
          }
        } else {
          this.$q.notify({
            type: 'negative',
            position: 'top',
            timeout: 1500,
            message: `请选择教师！`
          })
          return
        }
        if (this.addMsg.Month == '' || this.addMsg.Month == null) {
          this.$q.notify({
            type: 'negative',
            position: 'top',
            timeout: 1500,
            message: `请选择月份`
          })
          return
        }
        let date = new Date(this.addMsg.Month)
        this.addMsg.Month = date.getFullYear()+'-'+(date.getMonth()+1)
        this.Dloading = true
        setTeachingBonusAdd(this.addMsg).then(res => {
          this.Dloading = false
          if (res.Code == 1) {
            this.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: '保存成功！',
              position: 'top'
            })
            this.resetSearch()
            this.drawer = false
          }
        }).catch(err => {
          this.Dloading = false
        })

      },
      gostudent(item, type) { //确认
        let that = this
        let text = '';
        if (type == 1) {
          text = '确认奖励'
        } else if (type == 2) {
          text = '取消奖励'
        }
        this.$q.dialog({
          title: '提示信息',
          message: text,
          cancel: true,
          persistent: true,
          html: true,
          ok: "确定",
          cancel: "取消",
        }).onOk(() => {
          setTeachingBonusState({
            BonusId: item.Id,
            Type: type
          }).then(res => {
            if (res.Code == 1) {
              that.$q.notify({
                icon: 'iconfont icon-chenggong',
                color: 'accent',
                timeout: 2000,
                message: '操作成功',
                position: 'top'
              })
              that.getList()

            }
          })
        }).onCancel(() => {

        });
      },
      systemShan(item) { //一键制单
        this.FinanceMsg.BonusId = item.Id
        this.ISsystem = true;
      },
      Resetsystem() {
        this.FinanceMsg = {
          BonusId: 0,
          IsPublic: '0',
          CurrencyId: '',
        }
      },
      savesystem() {
        if (this.FinanceMsg.CurrencyId == '') {
          this.$q.notify({
            type: 'warning',
            position: 'top',
            timeout: 1500,
            message: `请选择币种`
          })
          return
        }
        let that = this
        that.Floading = true
        setTeachingBonusFinance(this.FinanceMsg).then(res => {
          if (res.Code == 1) {
            that.$q.notify({
              icon: 'iconfont icon-chenggong',
              color: 'accent',
              timeout: 2000,
              message: '制单成功',
              position: 'top'
            })
            that.getList()
            that.Resetsystem()
            that.Floading = false
            that.ISsystem = false;
            that.$forceUpdate()

          }
        }).catch(() => {
          this.Floading = false
        })

      },
      goexport() { //导出

      },
      goDetailed(item, TeacherId) { //明细
        var tempStr = '/course/rewardDetailed?Id=' + item.Id + '&TeacherId=' + TeacherId;
        this.$router.push({
          path: tempStr
        });
      },
      goUrl(path, rowData, ) {
        this.$router.push({
          path: '/financial/financalDocument/' + path,
          query: {
            "id": rowData,
            blank: 'y',
            tab: '单据详情'
          }
        })
      },
      checkSelectable(row){
          return row.IsGiveOut==2 
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        let zong = 0
        this.multipleSelection.forEach(x=>{
          zong +=x.Money
        })
        this.totalAmount = zong
      },
      generalFinancacls(item){
        this.CheckID = item.Id
        if(item.Money>0){
          this.getcomSendEmployeeList()
        }else{
          this.$message.error('提成总金额为0')
        }
        
      },
      getcomSendEmployeeList(Id){//获取可发放提成的老师
        getTeachingRewardsSendEmployeeList({PeriodId:this.CheckID}).then(res => {
            this.SendEmployeeList = res.Data;
            this.costmode = true
          }).catch(() => {

          })
      },
      preservetransaction(){
        let that = this
        if( this.multipleSelection.length == 0){
          this.$q.notify({
              type: 'negative',
              position: "top",
              message: `请选择您要发放的老师`
          })
          return
        }
        this.$q.dialog({
          title: "设置用户状态",
          message: "确认后无法更改老师制单状态，如果需修改请联系管理员",
          persistent: true,
          cancel: {
            label: "取消",
            flat: true
          },
          ok: {
            label: "确认",
            flat: true,
            focus: true
          }
        }).onOk(() => {
          let EmpIds = '';
          let data = []
          this.multipleSelection.forEach(x=>{
            data.push(x.TeacherId)
          })
          EmpIds = data.join(',')
          this.saveLoading = true
          setTeachingRewardsSendEmployee({PeriodId:this.CheckID,EmpIds:EmpIds}).then(res => {
            this.saveLoading = false
              this.goaddFinancial(this.totalAmount,this.CheckID,EmpIds)
              this.$message.success('设置成功');
          }).catch(() => {

          })
        });
      },
      goaddFinancial(Money,Id,EmpIds){
        let School_Id = 0;
        
        let obj = {
            CostType: 1250,
            Money: Money,
            CurrencyId: 21,
            XSTC: 1,
            School_Id:0,
            OtherType:26,
            ReFinanceId:Id,
            ReFinanceId2:0,
            EduCommissionEmp:EmpIds
          }
          let query = {
            blank: "y",
            tab: "新增付款单据",
            Type: 2,
            IsUploadPic: 1,
            Name:'销售提成单',
            id:143,
            orderObj: JSON.stringify(obj)
          }
          
          this.$router.push({
            path: "/financial/financalDocument/addFinancialDocuments",
            query
          });
      },
    }
  }

</script>

<style>
  .classHourReward .Sysuser_Date .el-input--prefix .el-input__inner {
    background-color: red;
    border: 0;
  }

  .classHourReward .state-item {
    padding: 2px 5px;
    border-radius: 3px;
    text-align: center;
    font-size: 10px;
  }

  .classHourReward .frIdlist {
    padding: 3px 10px;
    border-radius: 3px;
    background: #EEEEEF;
    align-items: center;
    justify-content: center;
    margin-right: 5px;
    margin-bottom: 5px;
    cursor: pointer;
  }

  .class-popover .q-pr-lg {
    padding-right: 0;
    margin-top: 20px;
  }

  .classHourReward .el-date-editor.el-input {
    width: 100%;
  }

  .classHourReward .el-date-editor.el-input input {
    background-color: transparent !important;
  }

  .classHourReward .el-range-editor .el-range-input {
    background: none;
  }

  .Sysuser_Date .el-input__inner {
    background: transparent !important;
    border: 0 !important;
  }
  .classHourReward .el-drawer.rtl{
    overflow: inherit;
  }
</style>
