<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      财务管理
    </h2>
    <div class="m-core">
      <div
        class="newBand"
        v-permission="{ child: 'routeOrder/add', parent: '/financeManager' }"
        @click="
          () => {
            routeOrderStatus = true;
            (isAdd = true), (form.applyType = null);
          }
        "
      >
        添加订单
      </div>
      <div
        class="newBand"
        @click="onOrderExport"
        v-permission="{
          child: 'export/routeOrderList',
          parent: '/financeManager',
        }"
      >
        报表导出
      </div>

      <div
        class="newBand"
        v-permission="{ child: 'adapay/exportBill', parent: '/financeManager' }"
        @click="onAdaPayExport"
      >
        汇付订单导出
      </div>
      <div
        class="newBand"
        @click="onDownload"
        v-permission="'import/downloadTemplate?financeManager'"
      >
        下载模板
      </div>
      <el-upload
        v-permission="'import/routeOrder'"
        style="display: inline-block; margin: 0 10px"
        action="/api-web/import/routeOrder"
        :show-file-list="false"
        :before-upload="beforeUpload"
        accept=".xlsx,.xls"
        :headers="headers"
        :on-error="handleError"
        :on-success="handleSuccess"
      >
        <div class="newBand">导入</div>
      </el-upload>
      <!-- 搜索类型 -->
      <save-form
        :inline="true"
        class="searchForm"
        ref="searchForm"
        :model.sync="searchForm"
      >
        <el-form-item>
          <el-input
            placeholder="学生编号/姓名/手机号"
            type="text"
            v-model.trim="searchForm.search"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="交易流水号"
            type="text"
            v-model.trim="searchForm.transNo"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="订单号"
            type="text"
            v-model.trim="searchForm.orderNo"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="收款账户"
            type="text"
            v-model.trim="searchForm.merNos"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="余额支付大于等于"
            type="number"
            @mousewheel.native.prevent
            v-model.trim="searchForm.balancePaymentAmount"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="现金支付大于等于"
            type="number"
            @mousewheel.native.prevent
            v-model.trim="searchForm.actualAmount"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="余额支付小于等于"
            type="number"
            @mousewheel.native.prevent
            v-model.trim="searchForm.lessBalancePaymentAmount"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
            placeholder="现金支付小于等于"
            type="number"
            @mousewheel.native.prevent
            v-model.trim="searchForm.lessActualAmount"
          ></el-input>
        </el-form-item>
        <el-form-item prop="routingOrganId">
          <el-select
            class="multiple"
            v-model.trim="searchForm.routingOrganId"
            filterable
            clearable
            @clear="onClear('routingOrganId')"
            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>
          <el-date-picker
            v-model.trim="searchForm.orderDate"
            style="width: 410px"
            type="daterange"
            value-format="yyyy-MM-dd"
            @change="searchOrderDate"
            :picker-options="{
              firstDayOfWeek: 1,
            }"
            range-separator="至"
            start-placeholder="订单开始日期"
            end-placeholder="订单结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model.trim="searchForm.paymentType"
            clearable
            filterable
            @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-select
            v-model.trim="searchForm.paymentStatus"
            clearable
            filterable
            @clear="onClear('paymentStatus')"
            placeholder="交易状态"
          >
            <el-option
              v-for="(item, index) in dealStatus"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="search" type="danger">搜索</el-button>
          <el-button @click="onReSet" type="primary">重置</el-button>
        </el-form-item>
      </save-form>
      <!-- 列表 -->
      <div style="font-size: 14px; color: #f85043; padding-bottom: 10px">
        营收金额：{{ totalRevenueAmount | moneyFormat }}元
        <i style="width: 10px; display: inline-block"></i>
        实收金额：{{ totalActualAmount | moneyFormat }}元
        <i style="width: 10px; display: inline-block"></i>
        预收金额：{{ totalAdvanceAmount | moneyFormat }}元
        <i style="width: 10px; display: inline-block"></i>
        预收余额：{{ totalUserBalance | moneyFormat }}元
      </div>
      <div class="tableWrap">
        <el-table
          :data="tableList"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column
            align="center"
            prop="transNo"
            label="交易流水号"
          ></el-table-column>
          <el-table-column
            align="center"
            prop="orderNo"
            label="订单号"
          ></el-table-column>
          <el-table-column
            align="center"
            width="150"
            prop="createTime"
            label="订单日期"
          >
            <template slot-scope="scope">{{
              scope.row.createTime | dateForMinFormat
            }}</template>
          </el-table-column>
          <el-table-column align="center" width="100px" label="交易类型">
            <template slot-scope="scope">{{
              scope.row.type | orderType
            }}</template>
          </el-table-column>
          <el-table-column align="center" prop="expectAmount" label="应付金额">
            <template slot-scope="scope">
              <div>
                {{ scope.row.expectAmount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="balancePaymentAmount"
            label="余额支付"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.balancePaymentAmount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="actualAmount" label="现金支付">
            <template slot-scope="scope">
              <div>
                {{ scope.row.actualAmount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="routeAmount" label="分润金额">
            <template slot-scope="scope">
              <div>
                {{ scope.row.routeAmount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="routeBalanceAmount"
            label="分润余额"
          >
            <template slot-scope="scope">
              <div>
                {{ scope.row.routeBalanceAmount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="学员姓名">
            <template slot-scope="scope">
              <div>
                <!-- v-if="scope.row.type !== 'OUTORDER'" -->
                <div>
                  {{ scope.row.user.username }}
                  <!-- <span v-if="scope.row.user.username && scope.row.user.phone"
                    >/</span
                  > -->
                  <p>{{ scope.row.user.phone }}</p>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="paymentChannel"
            label="交易方式"
          >
            <template slot-scope="scope">{{
              scope.row.paymentChannel | paymentChannelStatus
            }}</template>
          </el-table-column>
          <!-- <el-table-column align="center"
                           label="收款账户">
            <template slot-scope="scope">{{ scope.row.merNo }}</template>
          </el-table-column> -->
          <el-table-column align="center" label="交易状态">
            <template slot-scope="scope">{{
              scope.row.status | dealStatus
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="备注">
            <template slot-scope="scope">{{
              scope.row.memo ? scope.row.memo : "-"
            }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            fixed="right"
            width="150px"
            label="操作"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.groupType == 'OUTORDER'">
                <el-button type="text" @click="lookOrderInfo(scope.row)"
                  >查看</el-button
                >
                <!-- <el-button type="text" @click="removeOrderInfo(scope.row)"
                  >删除</el-button
                > -->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total.sync="pageInfo.total"
          sync
          :page.sync="pageInfo.page"
          :limit.sync="pageInfo.limit"
          :page-sizes="pageInfo.page_size"
          @pagination="getList"
        />
      </div>

      <el-dialog
        :title="isAdd ? '添加订单' : '查看'"
        destroy-on-close
        :visible.sync="routeOrderStatus"
        @close="onFormClose('ruleForm')"
        width="600px"
      >
        <el-form :model="form" :rules="rules" ref="ruleForm">
          <div class="lookTitle">基本信息</div>
          <el-form-item
            label="所属分部"
            prop="routeOrganId"
            :rules="[
              { required: true, message: '请选择分部', trigger: 'change' },
            ]"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model.trim="form.routeOrganId"
              :disabled="!isAdd"
              @change="changeOrgin"
              style="width: 100% !important"
            >
              <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
            label="所属学校"
            prop="schoolId"
            :label-width="formLabelWidth"
          >
            <el-select
              v-model="form.schoolId"
              :disabled="!isAdd"
              @change="checkSchool"
              style="width: 100% !important"
            >
              <el-option
                v-for="(item, index) in cooperationList"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="缴费单号"
            prop="calenderId"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.trim="form.calenderId"
              :disabled="!isAdd"
              placeholder="请输入缴费单号"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="学员编号"
            prop="userId"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model.trim="form.userId"
              :disabled="!isAdd"
              placeholder="请输入学员编号"
            ></el-input>
          </el-form-item>
          <div class="lookTitle">交易信息</div>
          <el-form-item
            label="交易流水号"
            prop="transNo"
            :label-width="formLabelWidth"
          >
            <el-input
              placeholder="请输入交易流水号"
              type="text"
              :disabled="!isAdd"
              v-model.trim="form.transNo"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="收款账户"
            prop="merNo"
            :label-width="formLabelWidth"
          >
            <el-input
              placeholder="请输入收款账户"
              type="text"
              :disabled="!isAdd"
              v-model.trim="form.merNo"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="交易日期"
            prop="payTime"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              style="width: 100%"
              :disabled="!isAdd"
              v-model="form.payTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择交易日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            label="收入类型"
            v-if="isAdd"
            :label-width="formLabelWidth"
            prop="applyType"
          >
            <el-select
              class="multiple"
              style="width: 100% !important"
              v-model.trim="form.applyType"
              @change="changeApplyType"
              filterable
              clearable
              :disabled="!isAdd"
              placeholder="请选择收入类型"
            >
              <el-option
                v-for="(item, index) in orderServerList"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <div v-if="form.applyType == 'SELL'">
            <div v-for="(goodsList, index) in form.goodsList" :key="index">
              <el-form-item
                :label="'商品名称' + (index + 1)"
                :label-width="formLabelWidth"
                class="setWidth"
                :prop="'goodsList.' + index + '.id'"
                :rules="[
                  { required: true, message: '请选择商品', trigger: 'change' },
                ]"
              >
                <el-select
                  v-model.trim="goodsList.id"
                  filterable
                  :disabled="!isAdd"
                  @change="checkgoods"
                  placeholder="请选择商品"
                >
                  <el-option
                    v-for="(item, index) in shopList"
                    :key="index"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                class="setWidth"
                style="margin-right: 10px"
                :prop="'goodsList.' + index + '.number'"
                :rules="validAmount"
              >
                <!-- <el-input-number style="width: 160px;" v-model="goodsList.number" placeholder="商品数量"></el-input-number> -->
                <el-input
                  type="age"
                  style="width: 160px"
                  :disabled="!isAdd"
                  clearable
                  placeholder="请输入商品数量"
                  @mousewheel.native.prevent
                  v-model.number="goodsList.number"
                ></el-input>
              </el-form-item>
              <el-button
                icon="el-icon-minus"
                :disabled="!isAdd"
                v-if="form.goodsList.length > 1"
                circle
                @click.prevent="removeGoodsList(goodsList)"
              ></el-button>
              <el-button
                icon="el-icon-plus"
                :disabled="!isAdd"
                @click.prevent="addGoodsList"
                circle
                style="margin-left: 5px"
              ></el-button>
            </div>
          </div>
          <el-form-item
            label="销售金额"
            v-if="form.applyType == 'SELL' || !isAdd"
            prop="saleAmount"
            :label-width="formLabelWidth"
          >
            <el-input
              v-model="form.saleAmount"
              @mousewheel.native.prevent
              type="number"
              :disabled="!isAdd"
              placeholder="请输入销售金额"
            />
          </el-form-item>
          <el-form-item
            label="服务金额"
            v-if="form.applyType == 'SERVICE' || !isAdd"
            prop="serviceAmount"
            :label-width="formLabelWidth"
          >
            <el-input
              type="number"
              @mousewheel.native.prevent
              :disabled="!isAdd"
              v-model="form.serviceAmount"
              placeholder="请输入收入金额"
            />
          </el-form-item>
          <div class="lookTitle">其它</div>
          <el-form-item label="备注" prop="memo" :label-width="formLabelWidth">
            <el-input
              placeholder="请输入备注"
              :disabled="!isAdd"
              v-model.trim="form.memo"
              type="textarea"
              :rows="3"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="routeOrderStatus = false">取 消</el-button>
          <el-button
            v-if="!isAdd"
            @click="routeOrderStatus = false"
            type="primary"
            >确 定</el-button
          >
          <el-button v-else @click="onOrderSubmit('ruleForm')" type="primary"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import {
  routeOrderFinance,
  routeOrderAdd,
  getOrderInfo,
  orderDelete,
} from "@/api/orderManager";
import { goodsQuery } from "@/api/businessManager";
import { getEmployeeOrgan, getAddress, getCooperation } from "@/api/buildTeam";
// import store from '@/store'
import { orderStatus, dealStatus } from "@/utils/searchArray";
import cleanDeep from "clean-deep";
import axios from "axios";
import qs from "qs";
import { getToken } from "@/utils/auth";
import load from "@/utils/loading";
import { orderServerList } from "@/utils/searchArray";
import { Export } from "@/utils/downLoadFile";
let validAmount = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入商品数量"));
  } else if (value < 0) {
    callback(new Error("输入商品数量必须大于0"));
  } else if (value > 999) {
    callback(new Error("输入商品数量必须小于999"));
  } else {
    callback();
  }
};
export default {
  components: { pagination },
  name: "incomeTwo",
  data() {
    return {
      orderStatus: orderStatus,
      dealStatus: dealStatus,

      searchForm: {
        search: null,
        orderStartDate: null,
        orderEndDate: null,
        paymentStatus: "SUCCESS",
        paymentType: null,
        routingOrganId: null,
        actualAmount: null,
        balancePaymentAmount: null,
        orderNo: null,
        transNo: null,
        merNos: null,
        lessBalancePaymentAmount: null,
        lessActualAmount: null,
        orderDate: [],
      },
      tableList: [],
      organList: [],
      shopList: [],
      cooperationList: [],
      orderServerList: orderServerList,
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      totalUserBalance: 0,
      totalActualAmount: 0,
      totalAdvanceAmount: 0,
      totalRevenueAmount: 0,
      formLabelWidth: "100px",
      routeOrderStatus: false,
      isAdd: true,
      form: {
        routeOrganId: null,
        transNo: null,
        type: "OTHER",
        merNo: null,
        actualAmount: null,
        memo: null,
        payTime: null,
        serviceAmount: null,
        saleAmount: null,
        schoolId: null,
        goodsList: [
          {
            id: null,
            number: null,
          },
        ],
        applyType: null,
        userId: "",
        calenderId: "",
      },
      validAmount: [
        { required: true, validator: validAmount, trigger: "blur" },
        { type: "number", message: "商品数量必须为数字" },
      ],
      rules: {
        organId: [
          { required: true, message: "请选择所属分部", trigger: "change" },
        ],
        // schoolId: [
        //   { required: true, message: "请选择学校", trigger: "change" }
        // ],
        actualAmount: [
          { required: true, message: "请输入金额", trigger: "blur" },
        ],
        transNo: [
          { required: true, message: "请输入交易流水号", trigger: "blur" },
        ],
        merNo: [{ required: true, message: "请输入收款账户", trigger: "blur" }],
        payTime: [
          { required: true, message: "选择交易日期", trigger: "change" },
        ],
        applyType: [
          { required: true, message: "请选择收入类型", trigger: "change" },
        ],
      },
      headers: {
        Authorization: getToken(),
      },
    };
  },
  mounted() {
    getEmployeeOrgan().then((res) => {
      if (res.code == 200) {
        this.organList = res.data;
      }
    });
    goodsQuery({ status: 1, rows: 99999 }).then((res) => {
      if (res.code === 200) {
        this.shopList = res.data.rows;
      }
    });

    if (!(this.searchForm.orderDate?.length > 0)) {
      var now = new Date();
      var startDate = new Date(
        Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
      )
        .toISOString()
        .slice(0, 10);
      var endDate = new Date(
        Date.UTC(now.getFullYear(), now.getMonth(), now.getDate())
      )
        .toISOString()
        .slice(0, 10);
      this.searchForm.orderDate = [];
      this.searchForm.orderDate.push(startDate);
      this.searchForm.orderDate.push(endDate);
    }

    this.getList();
  },
  methods: {
    onClear(type) {
      if (type == "paymentType") {
        this.searchForm.paymentType = null;
      } else if (type == "paymentStatus") {
        this.searchForm.paymentStatus = null;
      } else if (type == "routingOrganId") {
        this.searchForm.routingOrganId = null;
      }
    },
    onOrderSubmit(formName) {
      // 添加订单
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = this.form;
          if (!form.saleAmount && !form.serviceAmount) {
            this.$message.error("请输入销售收入或服务收入");
            return;
          }
          if (!form.saleAmount) {
            form.goodsList = null;
          }
          let goodsJson = {};
          for (let i in form.goodsList) {
            goodsJson[form.goodsList[i]["id"]] = form.goodsList[i]["number"];
          }
          form.goodsJson =
            form.applyType == "SERVICE" ? null : JSON.stringify(goodsJson);
          routeOrderAdd(form).then((res) => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.routeOrderStatus = false;
              this.getList();
            } else {
              this.$message.error(res.msg);
                console.log('来了')
            }
          });
        } else {
          return;
        }
      });
    },
    onFormClose(formName) {
      // this.form = {
      //   organId: null,
      //   transNo: null,
      //   type: "OTHER",
      //   merNo: null,
      //   actualAmount: null,
      //   memo: null,
      //   payTime: null,
      //   goodsList: [{
      //     id: null,
      //     number: null
      //   }]
      // }
      // 关闭弹窗重置验证
      this.$refs[formName].resetFields();
    },
    onOrderExport() {
      // 报表导出
      let url = "/api-web/export/routeOrderList";
      let searchForm = this.searchForm;
      let data = {
        orderType: 3,
        search: searchForm.search,
        orderNo: searchForm.orderNo,
        transNo: searchForm.transNo,
        merNos: searchForm.merNos,
        actualAmount: searchForm.actualAmount,
        balancePaymentAmount: searchForm.balancePaymentAmount,
        paymentStatus: searchForm.paymentStatus,
        paymentType: searchForm.paymentType,
        organId: searchForm.organId,
        lessBalancePaymentAmount: searchForm.lessBalancePaymentAmount,
        lessActualAmount: searchForm.lessActualAmount,
      };

      if (this.searchForm.orderDate && this.searchForm.orderDate.length > 0) {
        data.orderStartDate = this.searchForm.orderDate[0];
        data.orderEndDate = this.searchForm.orderDate[1];
      } else {
        data.orderStartDate = null;
        data.orderEndDate = null;
      }
      const options = {
        method: "POST",
        headers: {
          Authorization: getToken(),
        },
        data: qs.stringify(cleanDeep(data)),
        url,
        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 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 = "报表导出" + new Date().getTime(); //下载文件的名字
            link.href = objectUrl;
            link.setAttribute("download", fname);
            document.body.appendChild(link);
            link.click();
            load.endLoading();
          });
        })
        .catch(() => {});
    },
    onAdaPayExport() {
      // 报表导出
      let url = "/api-web/adapay/exportBill";
      let data = {};
      if (this.searchForm.orderDate && this.searchForm.orderDate.length > 0) {
        data.startTime = this.searchForm.orderDate[0];
        data.endTime = this.searchForm.orderDate[1];
      } else {
        this.$message.error("请选择开始日期和结束日期");
        return;
      }
      const options = {
        method: "get",
        headers: {
          Authorization: getToken(),
        },
        params: data,
        url,
        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 objectUrl = URL.createObjectURL(blob);
            let link = document.createElement("a");
            let fname = "汇付订单" + new Date().getTime(); //下载文件的名字
            link.href = objectUrl;
            link.setAttribute("download", fname);
            document.body.appendChild(link);
            link.click();
            load.endLoading();
          });
        })
        .catch(() => {});
    },
    search() {
      this.pageInfo.page = 1;
      this.$refs.searchForm.save(this.searchForm);
      this.$refs.searchForm.save(this.pageInfo, "page");
      this.getList();
    },
    getList() {
      // let params = JSON.parse(JSON.stringify(this.searchForm));
      let params = Object.assign({}, this.searchForm);
      // let params = {...this.searchForm}
      params.rows = this.pageInfo.limit;
      params.page = this.pageInfo.page;
      params.orderNo = params.orderNo ? params.orderNo : null;
      params.transNo = params.transNo ? params.transNo : null;
      params.merNos = params.merNos ? params.merNos : null;
      params.actualAmount = params.actualAmount ? params.actualAmount : null;
      params.balancePaymentAmount = params.balancePaymentAmount
        ? params.balancePaymentAmount
        : null;
      if (this.searchForm.orderDate && this.searchForm.orderDate.length > 0) {
        params.orderStartDate = this.searchForm.orderDate[0];
        params.orderEndDate = this.searchForm.orderDate[1];
      } else {
        params.orderStartDate = null;
        params.orderEndDate = null;
      }
      params.orderDate = null;
      routeOrderFinance(cleanDeep(params)).then((res) => {
        let result = res.data;
        if (res.code == 200) {
          this.tableList = result.rows;
          this.pageInfo.total = result.total;
          this.totalUserBalance = result.totalUserBalance
            ? result.totalUserBalance
            : 0;
          this.totalActualAmount = result.totalActualAmount
            ? result.totalActualAmount
            : 0;
          this.totalAdvanceAmount = result.totalAdvanceAmount
            ? result.totalAdvanceAmount
            : 0;
          this.totalRevenueAmount = result.totalRevenueAmount
            ? result.totalRevenueAmount
            : 0;
        }
      });
    },
    searchOrderDate(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 = {
        search: null,
        orderStartDate: null,
        orderEndDate: null,
        paymentStatus: null,
        paymentType: null,
        routingOrganId: null,
        actualAmount: null,
        balancePaymentAmount: null,
        orderNo: null,
        transNo: null,
        merNos: null,
        lessBalancePaymentAmount: null,
        lessActualAmount: null,
        orderDate: [],
      };
      this.getList();
    },
    removeGoodsList(item) {
      const index = this.form.goodsList.indexOf(item);
      if (index !== -1) {
        this.form.goodsList.splice(index, 1);
      }
    },
    addGoodsList() {
      this.form.goodsList.push({
        id: null,
        number: null,
      });
    },
    changeOrgin(val) {
      this.$set(this.form, "schoolId", null);
      if (val) {
        getCooperation({ rows: 9999, organId: val }).then((res) => {
          if (res.code === 200) {
            this.cooperationList = res.data.rows;
          }
        });
      }
    },
    checkSchool(val) {},
    checkgoods(val) {
      for (let i = 0; i <= this.form.goodsList.length - 1; i++) {
        if (
          i != this.form.goodsList.length - 1 &&
          this.form.goodsList[i].id === val
        ) {
          this.form.goodsList[this.form.goodsList.length - 1].id = "";
        }
      }
    },
    lookOrderInfo(row) {
      //orderNo
      this.isAdd = false;

      getOrderInfo({ orderId: row.id }).then((res) => {
        if (res.code === 200) {
          this.$nextTick((some) => {
            let orderInfo = res.data.studentPaymentOrder;
            this.changeOrgin(parseInt(orderInfo.organId));
            (this.form = {
              routeOrganId: orderInfo.organId,
              transNo: orderInfo.transNo,
              userId: orderInfo.userId ? orderInfo.userId : "",
              type: "OTHER",
              merNo: orderInfo.merNos,
              actualAmount: orderInfo.actualAmount,
              memo: orderInfo.memo,
              payTime: orderInfo.payTime,
              serviceAmount: res.data.serviceAmount,
              saleAmount: res.data.goodsAmount,
              schoolId: parseInt(orderInfo.musicGroupId) || "    ",
              applyType: "SELL",
              calenderId: res.data.calenderId ? res.data.calenderId : "",
            }),
              this.$set(
                this.form,
                "goodsList",
                res.data.sellOrders.map((item) => {
                  return { id: item.goodsId, number: item.num };
                })
              );
            this.routeOrderStatus = true;
          });
        }
      });
    },
    removeOrderInfo(row) {
      this.$confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          orderDelete({ orderId: row.id }).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.getList();
              // this.routeOrderStatus = false;
            }
          });
        })
        .catch();
      // orderDelete
    },
    onDownload() {
      // 下载模板
      // // 报表导出
      Export(this, {
        url: "/api-web/import/downloadTemplate",
        params: {
          templateType: "ROUTE_ORDER",
        },
        fileName: "财务管理导入模板.xlsx",
      });
    },
    beforeUpload(file) {
      // console.log(file.type)
      // const isJPG = file.type === '.xlsx' || file.type === '.xls';
      // // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // return isJPG;
      // this.goodsLoading = true
      load.startLoading();
    },
    handleSuccess(response, file, fileList) {
      // 导入商品
      // 报表导出
      load.endLoading();
      if (response.code == 200) {
        this.$message.success("导入成功");
        // this.getList()
      } else if (response.code == 0) {
        let str = this.fomatStr(response.msg);
        this.$alert(str, "导入结果", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true,
          callback: (action) => {
            // this.getList()
          },
        });
      } else {
        this.$message.error(response.msg);
      }
    },
    handleError(err, file, fileList) {
      load.endLoading();
      console.log(err, file, fileList);
    },
    fomatStr(str) {
      let arr = str.split(";");
      let newStr = "";
      arr.forEach((item) => {
        newStr += `<p>${item}</p>`;
      });
      return newStr;
    },
    changeApplyType(val) {
      if(val=='SELL'&&!this.form.goodsList){
        this.form.goodsList = [{
        id: null,
        number: null,
      }]
      }
      this.form.serviceAmount = null;
      this.form.saleAmount = null;
    },
  },
  watch: {
    routeOrderStatus(val) {
      if (!val) {
        this.form = {
          routeOrganId: null,
          transNo: null,
          type: "OTHER",
          merNo: null,
          actualAmount: null,
          memo: null,
          payTime: null,
          serviceAmount: null,
          saleAmount: null,
          schoolId: null,
          goodsList: [
            {
              id: null,
              number: null,
            },
          ],
          applyType: null,
          userId: "",
        };
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.newBand {
  display: inline-block;
}
/deep/.el-input-number.is-controls-right .el-input__inner {
  text-align: left;
}
.setWidth {
  display: inline-block;
}
.lookTitle {
  height: 40px;
  line-height: 40px;
  font-weight: bold;
  background-color: rgb(237, 238, 240);
  padding: 0 20px;
  margin-bottom: 20px;
}
</style>
