<!--  -->
<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>
      <save-form
        :inline="true"
        @submit="search"
        @reset="onReSet"
        :model="searchForm"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            @keyup.enter.native="search"
            clearable
            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 selects.branchs"
              :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>
          <remoteSearch :commit='"setTeachers"'  v-model='searchForm.teacherId' />
          <!-- <el-select
            placeholder="老师姓名"
            v-model="searchForm.teacherId"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in selects.teachers"
              :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" native-type="submit">搜索</el-button>
          <el-button native-type="reset" 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>
      </save-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="actualReceipts" label="实际收款">
            <template slot-scope="scope">{{(scope.row.actualReceipts ? scope.row.actualReceipts : 0) + '元'}}</template>
          </el-table-column> -->
          <!-- expectSalary -->
          <el-table-column align="center" prop="actualSalary" label="应发课酬">
            <template slot-scope="scope"
              >{{ scope.row.actualSalary | moneyFormat }}元</template
            >
          </el-table-column>
          <el-table-column align="center" prop="reduceSalary" label="课酬扣款">
            <template slot-scope="scope"
              >{{ scope.row.reduceSalary | moneyFormat }}元</template
            >
          </el-table-column>
          <el-table-column align="center" prop="finalSalary" label="结算课酬">
            <template slot-scope="scope"
              >{{ scope.row.finalSalary | moneyFormat }}元</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="300"
            fixed="right"
          ></el-table-column>
          <el-table-column align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="resetSalary(scope.row)"
                >课酬调整</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          sync
          :total.sync="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="400px">
      <div>
        <el-form
          ref="visibleForm"
          :model="visibleForm"
          class="visibleForm"
          :inline="true"
          label-width="60px"
        >
          <el-form-item
            label="应发"
            :rules="[
              { required: true, message: '请填写应发数', trigger: 'blur' },
            ]"
            prop="actualSalary"
          >
            <el-input-number
              :controls="false"
              :min="0"
              :precision="2"
              v-model.trim="visibleForm.actualSalary"
              type="number"
              @mousewheel.native.prevent
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="扣款"
            :rules="[
              { required: true, message: '请填写扣款数', trigger: 'blur' },
            ]"
            prop="reduceSalary"
          >
            <el-input-number
              :controls="false"
              :min="0"
              :precision="2"
              v-model.trim="visibleForm.reduceSalary"
              type="number"
              @mousewheel.native.prevent
            ></el-input-number>
          </el-form-item>
          <el-form-item label="实发">
            <el-input-number
              :controls="false"
              :min="0"
              :precision="2"
              v-model.trim="visibleForm.finalSalary"
              disabled
              type="number"
              @mousewheel.native.prevent
            ></el-input-number>
          </el-form-item>
          <el-form-item
            label="说明"
            :rules="[
              { required: true, message: '请填写说明', trigger: 'blur' },
            ]"
            prop="memo"
          >
            <el-input
              type="textarea"
              :rows="5"
              v-model.trim="visibleForm.memo"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subreset">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import numeral from "numeral";
import axios from "axios";
import { getToken } from "@/utils/auth";
import pagination from "@/components/Pagination/index";
import remoteSearch from '@/components/remote-search/index'
import load from "@/utils/loading";
import {
  findIsSettlementCourseSalarys,
  openSalaryConfirm,
  closeSalaryConfirm,
  teacherSalaryModifyLog,
} from "@/api/journal";
import { courseListType } from "@/utils/searchArray";
export default {
  components: { pagination, remoteSearch },
  data() {
    return {
      searchForm: {
        search: null,
        organIdList: null,
        groupType: null,
        teacherId: null,
        signInStatus: null,
        signOutStatus: null,
        month: null,
        confirmStatus: null,
      },
      dialogVisible: false,
      visibleForm: {
        finalSalary: null,
        reduceSalary: null,
        actualSalary: null,
        courseScheduleId: null,
        teacherId: null,
        memo: null,
      },
      isOpen: null,
      activeRow: null,
      tableList: [],
      groupTypeList: courseListType,
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
    };
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  async mounted() {
    await this.$store.dispatch('setBranchs')

    await this.$store.dispatch('setTeachers')
    // 获取分部
    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() {
      this.$confirm("您确定开启课酬确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        openSalaryConfirm({ month: this.searchForm.month }).then((res) => {
          if (res.code == 200) {
            this.$message.success("开启成功");
            this.getList();
          }
        });
      });
    },
    closeSalary() {
      this.$confirm("您确定关闭课酬确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        closeSalaryConfirm({ month: this.searchForm.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(() => {});
    },
    resetSalary(row) {
      let obj = {
        finalSalary: row.finalSalary, // 实发
        reduceSalary: row.reduceSalary, // 扣款
        actualSalary: row.actualSalary, // 应发
        courseScheduleId: row.courseScheduleId,
        memo: row.memo,
        teacherId: row.teacherId,
      };
      this.$set(this, "visibleForm", obj);
      console.log(this.visibleForm.finalSalary);
      this.dialogVisible = true;
    },
    subreset() {
      this.$refs["visibleForm"].validate((flag) => {
        if (flag) {
          let obj = {
            courseScheduleId: this.visibleForm.courseScheduleId,
            currentExpectSalary: this.visibleForm.actualSalary,
            currentReduceSalary: this.visibleForm.reduceSalary,
            memo: this.visibleForm.memo,
            teacherId: this.visibleForm.teacherId,
          };
          teacherSalaryModifyLog(obj).then((res) => {
            if (res.code == 200) {
              this.dialogVisible = false;
              this.$message.success("调整成功");
              this.getList();
            }
          });
        }
      });
    },
  },
  filters: {
    confirmFilter(val) {
      if (val) {
        let template = {
          1: "待确认",
          2: "已确认",
          3: "已完成",
        };
        return template[val];
      }
    },
  },
  computed: {
    getActualsalary() {
      // 应发
      return this.visibleForm.actualSalary;
    },
    getReduceSalary() {
      // 扣款
      return this.visibleForm.reduceSalary;
    },
  },
  watch: {
    getActualsalary(val) {
      var number = numeral(val);

      this.visibleForm.finalSalary = Math.max(
        number.subtract(this.getReduceSalary).value(),
        0
      );
    },
    getReduceSalary(val) {
      var number = numeral(this.getActualsalary);
      this.visibleForm.finalSalary = Math.max(number.subtract(val).value(), 0);
    },
    dialogVisible(val) {
      if (!val) {
        this.visibleForm = {
          expectSalary: null,
          reduceSalary: null,
          actualSalary: null,
          courseScheduleId: null,
          teacherId: null,
          memo: null,
        };
        this.$refs["visibleForm"].resetFields();
      }
    },
  },
};
</script>
<style lang='scss' scoped>
.red {
  color: red;
}
.visibleForm {
  /deep/.el-input__inner,
  /deep/.el-textarea__inner {
    width: 225px !important;
  }
}
/deep/.el-input-number .el-input__inner {
  text-align: left;
}
</style>
