<template>
  <div class="studentOrder">
    <statistic>
      <statistic-item>
        <span>账户余额</span>
        <span>
          {{ dataInfo.balance | moneyFormat }}
          <i
            class="el-icon-edit"
            v-permission="'userCashAccount/updateBalance'"
            @click="onMoneyOperation('recharge')"
          ></i>
        </span>
      </statistic-item>
      <statistic-item>
        <span>课程余额</span>
        <span>
          {{ dataInfo.courseBalance | moneyFormat }}
          <i
            class="el-icon-edit"
            v-permission="'userCashAccount/updateCourseBalance'"
            @click="onMoneyOperation('account')"
          ></i>
        </span>
      </statistic-item>
      <statistic-item>
        <span>银行卡</span>
        <span>{{ dataInfo.cardNo || "--" }}</span>
      </statistic-item>
      <statistic-item>
        <el-button
          @click="onCashAccount"
          v-permission="'studentDetail/userCashAccountDetail'"
          type="primary"
          >交易明细</el-button
        >
      </statistic-item>
    </statistic>
    <!-- 搜索类型 -->
    <save-form
      :inline="true"
      class="searchForm"
      :model="searchForm"
      save-key="studentDetail-studentOrder"
      @submit="search"
      @reset="onReSet"
    >
      <el-form-item>
        <el-date-picker
          style="width: 400px"
          v-model.trim="searchForm.orderDate"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="订单开始日期"
          end-placeholder="订单结束日期"
          :picker-options="{
            firstDayOfWeek: 1,
          }"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model.trim="searchForm.paymentType"
          filterable
          clearable
          @clear="onClear('paymentType')"
          placeholder="交易类型"
        >
          <el-option
            v-for="(item, index) in orderStatus"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          type="text"
          @keyup.enter.native="search"
          v-model.trim="searchForm.remark"
          placeholder="订单说明"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit" type="danger">搜索</el-button>
        <el-button native-type="reset" type="primary">重置</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="userCoursesAccountExport"
          v-if="$helpers.permission('export/userCoursesAccount')"
          >课程余额明细导出</el-button
        >
        <el-button
          type="primary"
          @click="userCashAccountDetailExport"
          v-if="$helpers.permission('export/userCashAccountDetail')"
          >账户余额明细导出</el-button
        >
      </el-form-item>
    </save-form>
    <div class="tableWrap">
      <el-table
        :data="tableList"
        :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
      >
        <el-table-column
          label="订单日期"
          prop="createTime"
          align="center"
          width="150px"
        >
          <template slot-scope="scope">{{
            scope.row.createTime | dateForMinFormat
          }}</template>
        </el-table-column>
        <el-table-column label="交易类型" align="center" width="180px">
          <template slot-scope="scope">{{
            scope.row.type | orderType
          }}</template>
        </el-table-column>
        <el-table-column
          width="180px"
          align="center"
          label="应付金额"
          prop="expectAmount"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.expectAmount | moneyFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          width="180px"
          align="center"
          label="余额支付"
          prop="balancePaymentAmount"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.balancePaymentAmount | moneyFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          width="180px"
          align="center"
          label="实际金额"
          prop="actualAmount"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.actualAmount | moneyFormat }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          width="180px"
          align="center"
          label="订单状态"
          prop="status"
        >
          <template slot-scope="scope">
            <div>{{ scope.row.status | payStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column
          label="订单说明"
          align="center"
          prop="memo"
          width="220px"
        >
          <template slot-scope="scope">
            <overflow-text width="200px" :text="scope.row.memo" />
          </template>
        </el-table-column>
        <el-table-column> </el-table-column>
      </el-table>
      <pagination
        sync
        :total.sync="pageInfo.total"
        :page.sync="pageInfo.page"
        :limit.sync="pageInfo.limit"
        :page-sizes="pageInfo.page_size"
        @pagination="getList"
      />
    </div>
    <el-dialog title="交易明细" width="850px" :visible.sync="cashStatus">
      <el-row>
        <el-col :span="24">
          <el-tabs v-model="activeName" type="border-card">
            <el-tab-pane
              label="账户余额明细"
              v-if="permission('userCashAccountDetail/queryPage')"
              name="first"
            >
              <el-table :data="cashAccount.gridData">
                <!-- 交易金额，账户可用余额，交易状态，交易类型，操作时间，备注 -->
                <el-table-column
                  align="center"
                  property="amount"
                  label="交易金额"
                ></el-table-column>
                <el-table-column
                  align="center"
                  property="balance"
                  label="账户可用余额"
                ></el-table-column>
                <el-table-column align="center" label="交易状态">
                  <template slot-scope="scope">{{
                    scope.row.status | payStatus
                  }}</template>
                </el-table-column>
                <el-table-column align="center" label="交易类型">
                  <template slot-scope="scope">{{
                    scope.row.type | payType
                  }}</template>
                </el-table-column>
                <el-table-column
                  align="center"
                  width="160px"
                  property="createTime"
                  label="交易时间"
                ></el-table-column>
                <el-table-column align="center" width="140px" label="备注">
                  <template slot-scope="scope">
                    <span :title="scope.row.comment">{{
                      scope.row.comment
                    }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                :total="cashAccount.total"
                :page.sync="cashAccount.page"
                :limit.sync="cashAccount.limit"
                :page-sizes="cashAccount.page_size"
                @pagination="getCashAccount"
              />
            </el-tab-pane>
            <el-tab-pane
              label="课程余额明细"
              v-if="permission('userCoursesAccount/queryPage')"
              name="second"
            >
              <el-table :data="courseAccount.gridData">
                <!-- 交易金额，账户可用余额，交易状态，交易类型，操作时间，备注 -->
                <el-table-column
                  align="center"
                  property="amount"
                  label="交易金额"
                ></el-table-column>
                <el-table-column
                  align="center"
                  property="balance"
                  label="课程可用余额"
                ></el-table-column>
                <el-table-column align="center" label="交易状态">
                  <template slot-scope="scope">{{
                    scope.row.status | payStatus
                  }}</template>
                </el-table-column>
                <el-table-column align="center" label="交易类型">
                  <template slot-scope="scope">{{
                    scope.row.type | payType
                  }}</template>
                </el-table-column>
                <el-table-column
                  align="center"
                  width="160px"
                  property="createTime"
                  label="交易时间"
                ></el-table-column>
                <el-table-column align="center" width="140px" label="备注">
                  <template slot-scope="scope">
                    <span :title="scope.row.comment">{{
                      scope.row.comment
                    }}</span>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                :total="courseAccount.total"
                :page.sync="courseAccount.page"
                :limit.sync="courseAccount.limit"
                :page-sizes="courseAccount.page_size"
                @pagination="getCourseAccount"
              />
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-dialog>
    <el-dialog
      :title="moneyForm.title"
      width="450px"
      @close="onFormClose('moneyForm')"
      :visible.sync="moneyVisible"
    >
      <el-form
        ref="moneyForm"
        :rules="moneyRule"
        :model="moneyForm"
        label-width="80px"
      >
        <el-form-item label="操作选择" prop="type">
          <el-radio-group v-model="moneyForm.type">
            <el-radio :label="1">充值</el-radio>
            <el-radio :label="2">扣除</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :label="moneyForm.titleType == 'account' ? '课程余额' : '账户余额'"
        >
          <el-input
            type="number"
            disabled
            :value="
              moneyForm.titleType == 'account'
                ? dataInfo.courseBalance
                : dataInfo.balance
            "
          ></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="money">
          <el-input
            type="number"
            @mousewheel.native.prevent
            v-model="moneyForm.money"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="moneyForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="moneyVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMoney('moneyForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import { Export } from "@/utils/downLoadFile";
import qs from 'qs'
import {
  studentPaymentOrderList,
  getUserCashAccountBaseInfo,
  updateCourseBalance,
  transferCourseBalanceToBalance,
  userCashAccountDetail,
  userCoursesAccount,
  updateBalance,
} from "@/api/studentManager";
import { permission } from "@/utils/directivePage";
import { orderStatus } from "@/utils/searchArray";
import { getTimes } from "@/utils";
import store from "@/store";
let validPrice = (rule, value, callback) => {
  if ((value == "" && typeof value == "string") || value == null) {
    callback(new Error("请输入金额"));
  } else if (value < 0) {
    callback(new Error("输入金额必须大于或等于0"));
  } else if (value >= 100000) {
    callback(new Error("输入金额必须小于100000"));
  } else {
    callback();
  }
};
export default {
  name: "studentOrder",
  components: { pagination },
  data() {
    return {
      rechargeVisible: false,
      organId: null,
      searchForm: {
        studentId: null,
        orderStartDate: null,
        orderEndDate: null,
        paymentType: null,
        remark: null,
        orderDate: [],
      },
      orderStatus: orderStatus,
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      tableList: [],
      dataInfo: {},
      amountStatus: true, // 账户余额状态
      rechargeForm: {
        money: null,
      },
      moneyVisible: false, //
      moneyForm: {
        title: "账户余额修改",
        titleType: "recharge",
        type: 1, //
        money: null,
        remark: null, //备注
      },
      moneyRule: {
        type: [
          { required: true, message: "请选择操作类型", trigger: "change" },
        ],
        money: [{ required: true, validator: validPrice, trigger: "blur" }],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      cashStatus: false,
      cashAccount: {
        // 点名表
        status: false,
        gridData: [],
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      activeName: "first",
      courseAccount: {
        // 点名表
        status: false,
        gridData: [],
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
    };
  },
  mounted() {
    this.searchForm.studentId = this.$route.query.userId;
    this.getList();
    this.__init();
  },
  activated() {
    this.searchForm.studentId = this.$route.query.userId;
    this.getList();
    this.__init();
  },
  methods: {
    permission,
    onClear(type) {
      if (type == "paymentType") {
        this.searchForm.paymentType = null;
      }
    },
    __init() {
      getUserCashAccountBaseInfo({ userId: this.$route.query.userId }).then(
        (res) => {
          if (res.code == 200) {
            this.dataInfo = {
              balance: res.data.balance,
              courseBalance: res.data.courseBalance,
              wxBalance: 0,
              cardNo: res.data.cardNo,
              zfb: null,
            };
          }
        }
      );
    },
    onFormClose(formName) {
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
    },
    onMoneyOperation(type) {
      let moneyForm = this.moneyForm;
      if (type == "recharge") {
        moneyForm.title = "账户余额修改";
        moneyForm.titleType = "recharge";
      } else if (type == "account") {
        moneyForm.title = "课程余额修改";
        moneyForm.titleType = "account";
      }
      this.moneyVisible = true;
    },
    onCashAccount(item) {
      // 点名表
      this.cashAccount.page = 1;
      this.getCashAccount();
      this.courseAccount.page = 1;
      this.getCourseAccount();
      this.cashStatus = true;
    },
    getCashAccount() {
      let cashAccount = this.cashAccount;
      let params = {
        page: cashAccount.page,
        rows: cashAccount.limit,
        userId: this.searchForm.studentId,
      };
      userCashAccountDetail(params).then((res) => {
        let result = res.data;
        cashAccount.status = true;
        if (res.code == 200) {
          cashAccount.gridData = result.rows;
          cashAccount.total = result.total;
        }
      });
    },
    getCourseAccount() {
      let courseAccount = this.courseAccount;
      let params = {
        page: courseAccount.page,
        rows: courseAccount.limit,
        userId: this.searchForm.studentId,
      };
      userCoursesAccount(params).then((res) => {
        let result = res.data;
        courseAccount.status = true;
        if (res.code == 200) {
          courseAccount.gridData = result.rows;
          courseAccount.total = result.total;
        }
      });
    },
    submitMoney(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let moneyForm = this.moneyForm;
          let dataInfo = this.dataInfo;
          let courseBalance = 0,
            balance = 0;
          if (moneyForm.titleType == "account") {
            // 课程余额
            if (moneyForm.type == 1) {
              courseBalance = Number(
                (
                  Number(moneyForm.money) + Number(dataInfo.courseBalance)
                ).toFixed(2)
              );
            } else if (moneyForm.type == 2) {
              if (dataInfo.courseBalance - moneyForm.money < 0) {
                this.$message.error(
                  "扣除金额不能大于" + dataInfo.courseBalance
                );
                return;
              } else {
                courseBalance = Number(
                  Number(dataInfo.courseBalance) -
                    Number(moneyForm.money).toFixed(2)
                );
              }
            }
            updateCourseBalance({
              userId: this.searchForm.studentId,
              decimal: courseBalance,
              memo: moneyForm.remark,
            }).then((res) => {
              let result = res.data;
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.__init();
                this.moneyVisible = false;
              } else {
                this.$message.error(res.msg);
              }
            });
          } else if (moneyForm.titleType == "recharge") {
            // 账户余额
            if (moneyForm.type == 1) {
              balance = moneyForm.money;
            } else if (moneyForm.type == 2) {
              if (dataInfo.balance - moneyForm.money < 0) {
                this.$message.error("扣除金额不能大于" + dataInfo.balance);
                return;
              } else {
                balance = -moneyForm.money;
              }
            }
            //  (balance)
            // return
            updateBalance({
              userId: this.searchForm.studentId,
              decimal: balance,
              memo: moneyForm.remark,
            }).then((res) => {
              let result = res.data;
              if (res.code == 200) {
                this.$message.success("保存成功");
                this.__init();
                this.moneyVisible = false;
              } else {
                this.$message.error(res.msg);
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    onUpdateCourse() {
      if (!this.dataInfo.courseBalance) {
        this.$message.error("请输入课程余额");
        return;
      }
      this.$confirm(`确定是否修改该学生课程余额?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateCourseBalance({
            userId: this.searchForm.studentId,
            decimal: this.dataInfo.courseBalance,
          }).then((res) => {
            let result = res.data;
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.amountStatus = true;
              this.__init();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.amountStatus = true;
        });
    },
    search() {
      this.pageInfo.page = 1;
      this.getList();
    },
    getList() {
      // let params = this.searchForm;
      // params.rows = this.pageInfo.limit;
      // params.page = this.pageInfo.page;
      // if (params.remark == "" || !params.remark) {
      //   params.remark = null;
      // }

      const { orderDate, ...rest } = this.searchForm;
      let params = {
        ...rest,
        ...getTimes(orderDate, ["orderStartDate", "orderEndDate"]),
        page: this.pageInfo.page,
        rows: this.pageInfo.limit,
      };
      studentPaymentOrderList(params).then((res) => {
        if (res.code == 200) {
          this.tableList = res.data.rows;
          this.pageInfo.total = res.data.total;
        }
      });
    },
    searchCourseDate(value) {
      if (value) {
        this.searchForm.orderStartDate = value[0];
        this.searchForm.orderEndDate = value[1];
      } else {
        this.searchForm.orderStartDate = null;
        this.searchForm.orderEndDate = null;
      }
    },
    onReSet() {
      // 重置搜索
      this.orderDate = null;
      this.searchForm = {
        studentId: this.$route.query.userId,
        orderStartDate: null,
        orderEndDate: null,
        paymentType: null,
        remark: null,
      };
      this.getList();
    },
    userCoursesAccountExport() {
       Export(this, {
          url: '/api-web/export/userCoursesAccount',
          fileName: '学员课程明细.xls',
          method: 'post',
          params:qs.stringify({ userId: this.$route.query.userId })
        }, '您确定导出学员课程明细?')
    },
    userCashAccountDetailExport() {
           Export(this, {
          url: '/api-web/export/userCashAccountDetail',
          fileName: '学员现金明细.xls',
          method: 'post',
          params:qs.stringify({ userId: this.$route.query.userId })
        }, '您确定导出学员现金明细?')
    },
  },
};
</script>
<style lang="scss" scoped>
.headWrap .left .headItem {
  position: relative;
  /deep/.el-button {
    position: absolute;
    top: -3px;
    right: 20px;
  }
}
.header-items {
  padding: 20px 0;
  text-align: center;
  /deep/ .el-icon-edit {
    cursor: pointer;
    color: #14928a;
    font-size: 20px;
  }
  /deep/ .el-col {
    display: flex;
    align-items: center;
    min-height: 60px;
    align-items: center;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  }
  /deep/ .el-col-1 {
    font-size: 60px;
  }
  span {
    display: block;
    line-height: 1.8;
    color: rgba(0, 0, 0, 0.85);
    font-size: 24px;
    &:first-child {
      font-size: 14px;
      font-weight: normal;
      color: rgba(0, 0, 0, 0.45);
    }
  }
}
/deep/.el-table .cell {
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

// .studentOrder {
// }
</style>
