<!--  -->
<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>课酬确认
    </h2>
    <div class="m-core">
      <div
        @click="openSalary"
        v-if="isOpen == 0"
        v-permission="'courseScheduleTeacherSalary/openSalaryConfirm'"
        class="newBand"
      >开启课酬确认</div>
      <div
       v-if="isOpen == 1"
        @click="closeSalary"
        v-permission="'courseScheduleTeacherSalary/closeSalaryConfirm'"
        class="newBand"
      >关闭课酬确认</div>
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            @keyup.enter.native="search"
            placeholder="课程编号、课程组名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            v-model.trim="searchForm.organIdList"
            filterable
            clearable
            placeholder="请选择分部"
          >
            <el-option
              v-for="(item,index) in organList"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="organId">
          <el-select
            class="multiple"
            v-model.trim="searchForm.groupType"
            filterable
            clearable
            placeholder="请选择课程组类型"
          >
            <el-option
              v-for="(item,index) in groupTypeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="老师姓名" v-model="searchForm.teacherId" clearable filterable>
            <el-option
              v-for="(item,index) in teacherList"
              :label="item.realName"
              :value="item.id"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="正常签到" v-model="searchForm.signInStatus" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="正常签退" v-model="searchForm.signOutStatus" clearable>
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="状态" v-model="searchForm.confirmStatus" clearable>
            <el-option label="待确定" value="1"></el-option>
            <el-option label="已确定" value="2"></el-option>
            <el-option label="已完成" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            :clearable="false"
            v-model="searchForm.month"
            type="month"
            value-format="yyyy-MM"
            placeholder="选择年月"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="search">搜索</el-button>
          <el-button @click="onReSet" type="primary">重置</el-button>
          <!-- export/isSettlementCourseSalarys -->
          <el-button
            @click="onExport"
            type="primary"
            v-permission="'export/exercisesSituations'"
            style=" background: #14928a; border:1px solid #14928a;"
          >导出</el-button>
        </el-form-item>
      </el-form>
      <div class="tableWrap">
        <el-table
          style="width: 100%"
          :header-cell-style="{background:'#EDEEF0',color:'#444'}"
          :data="tableList"
        >
          <el-table-column align="center" prop="organName" label="分部"></el-table-column>
          <el-table-column align="center" prop="groupType" width="100" label="课程组类型">
                <template slot-scope="scope">{{scope.row.groupType | coursesType}}</template>
          </el-table-column>
          <el-table-column align="center" prop="courseScheduleId" label="课程编号"></el-table-column>
          <el-table-column align="center" prop="courseScheduleId" width="150" label="时间">
            <template slot-scope="scope">{{scope.row.startClassTime | dateForMinFormat}}</template>
          </el-table-column>
          <el-table-column align="center" prop="courseName" width="120" label="课程名称"></el-table-column>
          <el-table-column align="center" prop="teacherId" label="老师编号"></el-table-column>
          <el-table-column align="center" prop="teacherName" label="老师姓名"></el-table-column>
          <el-table-column align="center" prop="courseScheduleId" width="150" label="签到时间">
            <template slot-scope="scope">
              <p
                :class="scope.row.signInStatus == 1?'':'red'"
              >{{scope.row.signInTime | dateForMinFormat}}</p>
              <p
                :class="scope.row.signInStatus == 1?'':'red'"
              >{{scope.row.signInStatus | attendanceType }}</p>
              <p class="red" v-if="!scope.row.signInStatus&&scope.row.signInStatus!=0">未签到</p>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="courseScheduleId" width="150" label="签退时间">
            <template slot-scope="scope">
              <p
                :class="scope.row.signOutStatus == 1?'':'red'"
              >{{scope.row.signOutTime | dateForMinFormat}}</p>
              <p
                :class="scope.row.signOutStatus == 1?'':'red'"
              >{{scope.row.signOutStatus | attendanceOutType}}</p>
              <p class="red" v-if="!scope.row.signOutStatus&&scope.row.signOutStatus!=0">未签到</p>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="expectSalary" label="应发课酬">
            <template slot-scope="scope">{{scope.row.expectSalary + '元'}}</template>
          </el-table-column>
          <el-table-column align="center" prop="reduceSalary" label="课酬扣款">
            <template slot-scope="scope">{{scope.row.reduceSalary + '元'}}</template>
          </el-table-column>
          <el-table-column align="center" prop="actualSalary" label="结算课酬">
            <template slot-scope="scope">{{scope.row.actualSalary + '元'}}</template>
          </el-table-column>
          <el-table-column align="center" prop label="状态" fixed="right">
            <template slot-scope="scope">{{scope.row.confirmStatus | confirmFilter }}</template>
          </el-table-column>
          <el-table-column align="center" prop="memo" label="备注" width="150" fixed="right"></el-table-column>
          <el-table-column align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text">课酬调整</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="rules.total"
          :page.sync="rules.page"
          :limit.sync="rules.limit"
          :page-sizes="rules.page_size"
          @pagination="getList"
        />
      </div>
    </div>
    <el-dialog
      title="课酬调整"
      :visible.sync="dialogVisible"
      width="width"
     >
      <div></div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import load from "@/utils/loading";
import { getTeacher, getEmployeeOrgan } from "@/api/buildTeam";
import { findIsSettlementCourseSalarys,openSalaryConfirm,closeSalaryConfirm } from "@/api/journal";
import { courseType } from "@/utils/searchArray";
export default {
  components: { pagination },
  data() {
    return {
      searchForm: {
        search: null,
        organIdList: null,
        groupType: null,
        teacherId: null,
        signInStatus: null,
        signOutStatus: null,
        month: null,
        confirmStatus: null
      },
      dialogVisible:true,
      isOpen: null,
      teacherList: [],
      tableList: [],
      organList: [],
      groupTypeList: courseType,
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      }
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    getTeacher().then(res => {
      if (res.code == 200) {
        this.teacherList = res.data;
      }
    });
    getEmployeeOrgan().then(res => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    });
    // 获取分部
    this.init();
  },
  activated() {
    this.init();
  },
  methods: {
    init() {
      if (!this.searchForm.month) {
        var now = new Date();
        this.searchForm.month = new Date(
          Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
        )
          .toISOString()
          .slice(0, 7);
      }

      this.getList();
    },
    getList() {
      let obj = this.getDate();
      findIsSettlementCourseSalarys(obj).then(res => {
        if (res.code == 200) {
          this.isOpen = res.data.isOpenConfirm;
          this.tableList = res.data.pageInfo.rows;
          this.rules.total = res.data.pageInfo.total;
        }
      });
    },
    search() {
      this.rules.page = 1;
      this.getList();
    },
    onReSet() {
        this.searchForm= {
        search: null,
        organIdList: null,
        groupType: null,
        teacherId: null,
        signInStatus: null,
        signOutStatus: null,
        month: null,
        confirmStatus: null
      }
      this.search()
    },
    getDate() {
      let obj = {
        search: this.searchForm.search,
        organIdList: this.searchForm.organIdList || null,
        groupType: this.searchForm.groupType || null,
        teacherId: this.searchForm.teacherId || null,
        signInStatus: this.searchForm.signInStatus || null,
        signOutStatus: this.searchForm.signOutStatus || null,
        month: this.searchForm.month || null,
        confirmStatus: this.searchForm.confirmStatus || null,
        page: this.rules.page,
        rows: this.rules.limit
      };
      return obj;
    },
    openSalary(){
        let  now = new Date();
       let month = new Date(
          Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
        )
          .toISOString()
          .slice(0, 7);
          this.$confirm("您确定开启课酬确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=>{
         openSalaryConfirm({month}).then(res=>{
        if(res.code == 200){
          this.$message.success('开启成功')
          this.getList()
        }
      })
      })
     
    },
    closeSalary(){
        let  now = new Date();
       let month = new Date(
          Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
        )
          .toISOString()
          .slice(0, 7);
        this.$confirm("您确定关闭课酬确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(()=>{
         closeSalaryConfirm({month}).then(res=>{
        if(res.code == 200){
          this.$message.success('关闭成功')
          this.getList()
        }
      })
      })
     
    },
      onExport() {
      let url = "/api-web/export/isSettlementCourseSalarys";
      let obj = this.getDate();
      const options = {
        method: "get",
        headers: {
          Authorization: getToken()
        },
        url,
        params: obj,
        responseType: "blob"
      };

      this.$confirm("您确定导出列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          load.startLoading();
          axios(options)
            .then(res => {
              let blob = new Blob([res.data], {
                // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
                type: "application/vnd.ms-excel;charset=utf-8"
                // word文档为application/msword,pdf文档为application/pdf,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
              });
              let text = new Response(blob).text();
              text.then(res => {
                // 判断是否报错
                if (res.indexOf("code") != -1) {
                  let json = JSON.parse(res);
                  this.$message.error(json.msg);
                } else {
                  let objectUrl = URL.createObjectURL(blob);
                  let link = document.createElement("a");
                  let nowTime = new Date();
                  let ymd =
                    nowTime.getFullYear() +
                    "" +
                    (nowTime.getMonth() + 1) +
                    "" +
                    nowTime.getDate() +
                    "" +
                    nowTime.getHours() +
                    "" +
                    nowTime.getMinutes();
                  let fname = ymd + "课酬确认";
                  link.href = objectUrl;
                  link.setAttribute("download", fname);
                  document.body.appendChild(link);
                  link.click();
                }
              });

              load.endLoading();
            })
            .catch(error => {
              this.$message.error("导出数据失败，请连接管理员");
              load.endLoading();
            });
        })
        .catch(() => {});
    },
  },
  filters: {
    confirmFilter(val) {
      if (val) {
        let template = {
          1: "待确认",
          2: "已确认",
          3: "已完成"
        };
        return template[val];
      }
    }
  }
};
</script>
<style lang='scss' scoped>
.red {
  color: red;
}
</style>