<template>
  <div class="m-container">
    <h2>
      <div class="squrt"></div>
      支出记录
    </h2>
    <div class="m-core">
      <el-upload
        v-permission="'import/downloadTemplate'"
        style="display: inline-block"
        action="/api-web/import/financialExpenditure"
        :show-file-list="false"
        :before-upload="beforeUpload"
        accept=".xlsx,.xls"
        :headers="headers"
        :on-error="handleError"
        :on-success="handleSuccess"
      >
        <el-button class="btn-primary">导入</el-button>
      </el-upload>
      <el-button
        @click="downloadFile"
        v-permission="'import/downloadTemplate'"
        class="btn-primary"
        >模版文件下载</el-button
      >
      <!-- 搜索类型 -->
      <save-form
        :inline="true"
        class="searchForm"
        :model="searchForm"
        @submit="search"
        @reset="onReSet"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchForm.search"
            clearable
            placeholder="批次号、申请人等"
            type="text"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model.trim="searchForm.organId"
            clearable
            filterable
            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>
          <el-select
            clearable
            filterable
            placeholder="请选择所属学校"
            v-model="searchForm.cooperationOrganId"
          >
            <el-option
              v-for="(item, index) in cooperations"
              :key="index"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-select clearable filterable placeholder="请选择支出类型" v-model="searchForm.saleType">
            <el-option label="1" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select clearable filterable placeholder="请选择支出类别" v-model="searchForm.saleType">
            <el-option label="1" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select clearable filterable placeholder="请选择收款方式" v-model="searchForm.paymentChannel">
            <el-option v-for="item in paymentChannelStatus" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-date-picker
            style="width: 410px"
            v-model.trim="searchForm.orderDate"
            type="daterange"
            value-format="yyyy-MM-dd"
            @change="searchOrderDate"
            range-separator="至"
            start-placeholder="付款开始日期"
            end-placeholder="付款结束日期"
            :picker-options="{ firstDayOfWeek: 1 }"
          >
          </el-date-picker>
        </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>
      </save-form>
      <!-- 列表 -->
      <el-row>
        <el-col :span="24">
          <el-button
            type="primary"
            v-permission="'financialExpenditure/batchDel/4043'"
            size="medium"
            icon="el-icon-delete"
            style="
              background-color: #14928a;
              border: 1px solid #14928a;
              margin-bottom: 15px;
            "
            @click="onBatchDel"
            >批量删除</el-button
          >
        </el-col>
      </el-row>
      <div class="tableWrap">
        <el-table
          :data="tableList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#EDEEF0', color: '#444' }"
        >
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column align="center" prop="id" label="批次号">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.id }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="financialProcessNo"
            label="流程编号"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.financialProcessNo }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="dingtalkProcessNo"
            label="钉钉流程编号"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.dingtalkProcessNo }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="organName" label="费用归属分部">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.organName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="cooperationName"
            label="费用归属学校"
          >
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.cooperationName }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="applyUser" label="申请人">
            <template slot-scope="scope">
              <div>
                <copy-text>{{ scope.row.applyUser }}</copy-text>
              </div>
            </template>
          </el-table-column>
          <!-- <el-table-column align='center' prop="itemDetail" label="费用项目"></el-table-column> -->
          <el-table-column align="center" prop="amount" label="付款金额">
            <template slot-scope="scope">
              <div>
                {{ scope.row.amount | moneyFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="paymentTime" label="付款时间">
            <template slot-scope="scope">
              <div>
                {{ scope.row.paymentTime | dayjsFormat }}
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="cause" label="事由">
            <template slot-scope="scope">
              <div>
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="scope.row.cause"
                  placement="top"
                >
                  <div class="noWrap">{{ scope.row.cause }}</div>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="费用类型">
            <template slot-scope="scope">{{
              scope.row.type | feeType
            }}</template>
          </el-table-column>
          <el-table-column align="center" label="费用项目">
            <template slot-scope="scope">{{
              scope.row.feeProject | feeProject
            }}</template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="itemDetail"
            label="备注"
          ></el-table-column>
          <el-table-column
            align="center"
            width="120px"
            fixed="right"
            label="操作"
          >
            <template slot-scope="scope">
              <div>
                <el-button type="text" @click="lookDetail(scope.row)"
                  >详情</el-button
                >
                <el-popconfirm
                  title="确定删除该条数据吗？"
                  @confirm="() => removeRecord(scope.row.id)"
                  v-permission="'financialExpenditure/batchDel/4042'"
                >
                  <el-button type="text" slot="reference">删除</el-button>
                </el-popconfirm>
              </div>
            </template>
          </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>
      <recorddetail
        :show="show"
        @closeReset="closeReset"
        @getList="getList"
        :item="activeRow"
      />
    </div>
    <!-- <el-dialog
      title="修改支出记录"
      :visible.sync="visible"
    >
      <el-form :model="updateForm" :rules="updateRules" label-width="100px" ref="updateForm">
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
        <el-form-item label="流程编号" prop="financialProcessNo">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
        <el-form-item label="钉钉流程编号" prop="dingtalkProcessNo">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
        <el-form-item label="费用归属分部" prop="organId">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
        <el-form-item label="费用归属学校" prop="cooperationOrganId">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
        <el-form-item label="费用归属学校" prop="cooperationOrganId">
          <el-input v-model="ruleForm.batchNo"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="visible = false">确 定</el-button>
      </span>
    </el-dialog> -->
  </div>
</template>
<script>
import pagination from "@/components/Pagination/index";
import { Export } from "@/utils/downLoadFile";
import {
  getFinancialExpenditure,
  applyRefundAudit,
  removeFinancialExpenditure,
  updateFinancialExpenditure,
} from "@/api/orderManager";
import { getEmployeeOrgan, getCooperation } from "@/api/buildTeam";
import { getToken } from "@/utils/auth";
import { paymentChannelStatus } from "@/utils/searchArray";
import recorddetail from "@/views/businessManager/orderManager/payRecordConponents/payRecordDetail";
import load from "@/utils/loading";
import dayjs from "dayjs";
import { getTimes } from "@/utils";
export default {
  components: { pagination, recorddetail },
  name: "backMoney",
  data() {
    return {
      show: false,
      detail: null,
      paymentChannelStatus: paymentChannelStatus,
      searchForm: {
        startTime: null,
        endTime: null,
        organId: null,
        search: "",
        dingtalkProcessNo: "",
        financialProcessNo: "",
        cooperationOrganId: null,
        orderDate: [],
      },
      headers: {
        Authorization: getToken(),
      },
      tableList: [],
      organList: [],
      cooperations: [],
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
      passed: [], // 传递的参数
      activeRow: null,
    };
  },
  created(){
        if (this.searchForm.orderDate?.length < 1) {
      var now = new Date();
      var startDate = dayjs().format("YYYY-MM-DD");
      var endDate = dayjs().format("YYYY-MM-DD");
      this.searchForm.orderDate = [];
      this.searchForm.orderDate.push(startDate);
      this.searchForm.orderDate.push(endDate);
      this.searchOrderDate(this.searchForm.orderDate);
    }
  },
  mounted() {
    // getEmployeeOrgan().then(res => {
    //   if (res.code == 200) {
    //     this.organList = res.data;
    //   }
    // })
    this.$store.dispatch("setBranchs");
    getCooperation({ rows: 1000 }).then((res) => {
      if (res.code == 200) {
        this.cooperations = res.data.rows;
      }
    });


    this.getList();
  },
  methods: {
    editRecord(detail) {
      this.show = true;
      this.detail = detail;
    },
    removeRecord(id) {
      removeFinancialExpenditure({
        ids: id,
      }).then(() => {
        this.getList()
        this.$message.success("删除成功");
      }).catch((res) => {
        this.$message.error(res.msg)
      });
    },
    beforeUpload(file) {
      load.startLoading();
    },
    handleSuccess(response, file, fileList) {
      load.endLoading();
      console.log(response, file, fileList);
      if (response.code == 200) {
        this.$message.success("导入成功");
        this.getList();
      } else {
        this.$message.error(response.msg);
      }
    },
    handleError(err, file, fileList) {
      load.endLoading();
      console.log(err, file, fileList);
    },
    downloadFile() {
      Export(this, {
        url: "/api-web/import/downloadTemplate",
        fileName: "财务支出导入模板.xlsx",
        params: {
          templateType: "FINANCIAL_EXPENDITURE",
        },
      });
    },
    search() {
      this.pageInfo.page = 1;
      this.getList();
    },
    handleSelectionChange(arr) {
      this.passed = [];
      for (let i in arr) {
        // let obj = {};
        // obj.id = arr[i].id;
        // obj.name = arr[i].name;
        this.passed.push(arr[i].id);
      }
    },
    onTeachingSubmit(formName, status) {
      // 添加数据
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.status = status;
          applyRefundAudit(this.form).then((res) => {
            if (res.code == 200) {
              this.$message.success("操作成功");
              this.backStatus = false;
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },
    getList() {
      let { orderDate, ...ruset } = this.searchForm;
      let params = {
        ...ruset,
        page: this.pageInfo.page,
        rows: this.pageInfo.limit,
        ...getTimes(orderDate, ["startTime", "endTime"]),
      };
      getFinancialExpenditure(params).then((res) => {
        let result = res.data;
        if (res.code == 200) {
          this.tableList = result.rows;
          this.pageInfo.total = result.total;
        }
      });
    },
    searchOrderDate(value) {
      if (value) {
        this.searchForm.startTime = value[0];
        this.searchForm.endTime = value[1];
      } else {
        this.searchForm.startTime = null;
        this.searchForm.endTime = null;
      }
    },
    onReSet() {
      // this.orderDate = [];
      this.searchForm = {
        startTime: null,
        endTime: null,
        orderDate: [],
      };
      var now = new Date();
      var startDate = dayjs().format("YYYY-MM-DD");
      var endDate = dayjs().format("YYYY-MM-DD");
      this.searchForm.orderDate = [];
      this.searchForm.orderDate.push(startDate);
      this.searchForm.orderDate.push(endDate);
      this.pageInfo.page = 1;
      this.getList();
    },
    onBatchDel() {
      // 批量删除
      const passed = this.passed;
      if (passed.length <= 0) {
        this.$message.error("请至少选择一条数据");
        return;
      }
      this.$confirm("是否删除选择的支出记录?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return removeFinancialExpenditure({
            ids: this.passed.join(","),
          });
        })
        .then(() => this.getList())
        .catch(() => {});
    },
    lookDetail(row) {
      this.activeRow = row;
      this.show = true;
      console.log(111);
    },
    closeReset() {
      this.show = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.newBand {
  display: inline-block;
}
.noWrap {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
